phplaraveleloquentrelationship

Get ids from related model Laravel


I have a many to many relationship set between two objects Tag and Post. Now, I have to check which tags that post has in a checkbox list, like so:

//Load all possible tags in the controller
//and send it to view
$allTags = \App\Tag::all();
return view('post.edit')->with('allTags');

In the view:

@foreach($allTags as $tag)
    <input type="checkbox" name="tags[]" value="{{ $tag->id }}"/>
    {{ $tag->description }}
@endforeach

Now, when the user reloads the page, I have to check those checkboxes.

My question is:

This certainly work, but seems like overkill to me

$relatedTags = [];
foreach($post->tags as $tag){
    $relatedTags[]= $tag->id;
}

Is there a way to get only the ids without loading all those objects?

Something like: $relatedTags = $post->tags()->ids?


Solution

  • You can try with querying the results like that:

    $relatedTagIds = $post->tags()->select('id')->get()->pluck('id')->toArray();
    

    That's how you get clear list of tags ids.