CarlosCarucce CarlosCarucce - 5 months ago 14
PHP Question

Get ids from related model laravel

I have a many to many relationship set between two objects

Now, I have to check wich tags that post have 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 }}

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


You can try with quering the results like that:

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

Thats how you get clear list of tags ids.