0

I'm trying to build tags system. In my database, I have table topics with column tags. Tags are a JSON object.

My route:

Route::get('t/{tag}', 'myController@tag')->name('tag');

public function tag( $tag )
{
    return view('tags.tag', ['tag' => $tag, 'topics' => DB::table('topics')->get()]);
}

And then:

@foreach ($topics as $topic)
    @if (in_array($tag, json_decode($topic->tags, true)))
    <tr>
        <td class="col-md-6 col-sm-6">
            <a href="#" title="">
                <strong>{{ $topic->topic_name }}</strong>
            </a>    
        </td>
        <td class="col-md-1 col-sm-1 text-right">
            @foreach (json_decode($topic->tags) as $tag)
                <span class="badge badge-primary">{{ $tag }}</span>
            @endforeach
        </td>
    </tr>
    @endif
 @endforeach

I know this is not a perfect solution and I need to use that if in a query. How can I do this? Thanks in advance. P.S I know about '->where('topics->tags', '..')

But my MySQL is older than 5.7 and I can't use these new functions. Any suggestions?

2
  • Why wouldn't you be able to use where()? Commented Oct 10, 2017 at 11:54
  • .. or the best way is to update mysql? Commented Oct 10, 2017 at 11:54

1 Answer 1

1

Please use casts in your model

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

It will convert JSON to array when retrieving from DB

Refer https://laravel.com/docs/5.4/eloquent-mutators#attribute-casting

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.