Home > Software design >  Displaying Meta Tag Keywords as JSON Data From Database Not Seem To Be Working
Displaying Meta Tag Keywords as JSON Data From Database Not Seem To Be Working

Time:12-15

I'm working with Laravel 5.8 and I wanted to update my page meta keywords as JSON data.

So I created a new column named prd_meta_keywords and set its structure to JSON.

Now I can successfully insert JSON data into this column like this example:

[
    "video product",
    "new product"
]

And for retrieving this data on the Blade, I did this:

@section('meta')
   <meta name="keywords" content="@if(!empty($product->prd_meta_keywords)) @if(is_array($product->prd_meta_keywords) || is_object($product->prd_meta_keywords)) @foreach(json_decode($product->prd_meta_keywords) as $keyword) {{$keyword}}{{$loop->remaining ? ',' : ''}} @endforeach @endif @endif">
@endsection

But as you can see, it does not work and does not show the keywords on page source code:

<meta name="keywords" content="  ">

However I can properly get result from @dd(json_decode($product->prd_meta_keywords)).

So what's going wrong here? How can I retrieve this JSON data as keyword tags properly in the Blade?

CodePudding user response:

You can use Laravel Casting there.

Just cast your column in the respective model. So it will auto store data in JSON and at the time of retrieving it will auto-cast in PHP array.

 protected $casts = [
     'prd_meta_keywords' => 'array',
 ];

After retrieving the array you can easily implode in meta,

<meta name="keywords" content="{{ ($product->prd_meta_keywords) ? implode(",", $product->prd_meta_keywords) : ''}}">

Let me know the results.

  • Related