Relationship Table Data With Route Model Binding In Laravel


04th August 2020 1 min read
Share On        


Many times you might want to use this wonderful thing called Route Model Binding in Laravel but back off because you might need its related table data too. Yup! I too had come across this situation.


Example - You want to show Customer details and CustomerAddress details so you would have done something like the following


Common Way

public function show($customer)
{
    $customer = Customer::with('customerAddress')->where('id', $customer)->first();
    return view('customer.show', [
        'customer' => $customer
    ]);
}


But let me explain 2 simple approaches to achieve it.


1) Relationship Table Data Along With Route Model


Route Model Binding (Common Way)

public function show(Customer $customer)
{
    $customerAddress = CustomerAddress::where('id', $customer)->get();
    return view('customer.show', [
        'customer'          => $customer,
        'customerAddress'   => $customerAddress
    ]);
}


Now lets see the simple way


Route Model Binding (Super cool way - load)

public function show(Customer $customer)
{
    /** Super Awesome Right? */
    $customer->load(['customerAddress']);

    return view('customer.show', [
        'customer'          => $customer
    ]);
}


Yup the following is the super cool line.

$customer->load(['customerAddress']);

2) $with In Model (Use wisely)


Make sure to use this wisely as it will load all the related table every time you query.


class Customer extends Model
{
    use SoftDeletes;
    protected $with = ['customerAddress'];
}

Conclusion


Hope the article was helpful. Kindly share it with your friends.







AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing