Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jhyaps's avatar

Laravel Relationship hasMany and Belongs to

I have following relationship

  1. Supplier Model
public function supplierAddress()
    {
        return $this->hasMany(SupplierAddress::class);
    }
  1. SupplierAddress Model
public function address()
    {
        return $this->belongsTo(Address::class, 'address_id', 'id');
    }
  1. in supplier controller, i fetch the value by this
$suppliers = Supplier::with('status', 'supplierAddress.address')->orderBy('id', 'DESC')->get();

But in supplier blade how to display the address name

{{ $supplier->supplierAddress }}

this displays all the value

[{"id":1,"supplier_id":1,"address_id":1,"created_at":null,"updated_at":null,"address":{"id":1,"name":"Birtamode","name_nepali":"\u092c\u093f\u0930\u094d\u0924\u093e\u092e\u094b\u0921","statuses_id":1,"deleted_at":null,"created_at":"2023-02-21T09:16:29.000000Z","updated_at":"2023-02-21T09:16:29.000000Z"}},{"id":2,"supplier_id":1,"address_id":2,"created_at":null,"updated_at":null,"address":{"id":2,"name":"Charpane","name_nepali":"\u091a\u093e\u0930\u092a\u093e\u0928\u0947","statuses_id":1,"deleted_at":null,"created_at":"2023-02-21T09:16:30.000000Z","updated_at":"2023-02-21T09:16:30.000000Z"}}]

But i Need only address like, Charpane or Birtamode in my blade

0 likes
5 replies
Sinnbeck's avatar
{{ $supplier->supplierAddress->first()->address?->name }}
1 like
jhyaps's avatar

@Sinnbeck , did this works if the supplier has many address ? like he has 2 -3 address ?? as i tried this above code i am getting only one value

jhyaps's avatar

@sinnbeck , I found this in the forum, which actually works but,

{{ $supplier->supplierAddress->pluck('address.name')->implode(', ') }}

it is the proper way to do ?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@jhyaps or you do a foreach

@foreach ($supplier->supplierAddress as $supAddress) 
    {{$supAddress->address?->name }}
@endforeach 
1 like
LaryAI's avatar
Level 58

You can access the address name from the $supplier object like this:

@foreach($suppliers as $supplier)
    @foreach($supplier->supplierAddress as $address)
        {{ $address->address->name }}
    @endforeach
@endforeach
1 like

Please or to participate in this conversation.