CarlosCarucce
CarlosCarucce

Reputation: 3569

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 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 }}
@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 ?

Upvotes: 4

Views: 2409

Answers (3)

Filip Koblański
Filip Koblański

Reputation: 10018

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.

Upvotes: 2

CarlosCarucce
CarlosCarucce

Reputation: 3569

Thanks to Filip's answer, I found another possible solution.

$post->tags->pluck('id')->toArray();

I hope someone find it useful

Upvotes: 2

Shyam Naru
Shyam Naru

Reputation: 305

Use this it will fetch only id and description that you need.

$allTags = DB::table('tags')->lists('description', 'id');

Upvotes: 2

Related Questions