How to use with relationship to model param in controller method?

Viewed 44

Normally I can use CustomerAddress::with(["province", "city", "district"]); to include relationship to the response but I use the model as method params like below:

public function show(CustomerAddress $address)
{
    return $address;
}

Currently, I can get a query with relationship using:

public function show(CustomerAddress $address)
{
    $address = CustomerAddress::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail();
    return $address;
}

But I think it's will make a double query, which bad for performance. My another solution is don't call Model in the param like below:

public function show($address_id)
{
    $address = CustomerAddress::with(["province", "city", "postalcode", "district"])->where("id", $address_id)->firstOrFail();

   return $address;
}

But for some reason, I need to use CustomerAddress model in method params. Is any other solution to include relation to $address without call model class again?

2 Answers

You already have the model loaded, so you only need to load the relations. This is called lazy eager loading.

public function show(CustomerAddress $address)
{
    return $address->load("province", "city", "postalcode", "district");
}

Hope that helps :)

The show method like this

public function show(CustomerAddress $address) { 
return $address::with(["province", "city", "postalcode", "district"])->where("id", $address->id)->firstOrFail();
}

And you can use the show method and pass the CustomerAddress as argument

show(new CustomerAddress())
Related