Nick Villaume
Nick Villaume

Reputation: 47

Retrieving a single value from belongsToMany relationship in blade template

I have created a model with a belongsToMany relationship. The model is Vendor and the relationship with Location. So, in my blade template, I would normally do something like this:

@foreach ($vendor->locations as $loc)
{{$loc-id}}
@endforeach

However, I would like to simply json_encode only the id values for each of the locations. If possible, I would like to do so without creating a loop. So, I know I can do this:

{{json_encode($vendor->locations)}}

But as you can guess, this dumps out JSON data of all of the fields in the locations table.

I know I can modify my relationship to only include the ID fields, but I do not want to do this because I want to use the relationship elsewhere.

Is there a way to just grab the ID fields using something like:

{{json_encode($vendor->locations->id)}}

Upvotes: 0

Views: 476

Answers (2)

AlexH_269
AlexH_269

Reputation: 25

You can use Laravel's pluck and json methods:

{{ $vendor->locations->pluck('id')->toJson() }}

You can refer to the documentation for more information: https://laravel.com/docs/8.x/collections#method-tojson

Upvotes: 1

Nortol
Nortol

Reputation: 449

You can pluck the 'id' and convert it directly to json.

{{ $vendor->locations->pluck('id')->toJson() }}

This requires that $vendor->locations is a Collection.

Upvotes: 1

Related Questions