Reputation: 343
I have a section of a Laravel 5 app where the same basic company info needs to be passed into every view, for use in the navbar include as well as within the main part of the view in a few instances.
I am making the same three Eloquent queries to match the company against a URL segment, retrieve that company's basic contact info and the phone numbers and links which belong to it. Then compacting this up and passing it to the view. I would prefer not to have to repeat this in every single one of my controller methods.
public function showPropertyDetails($realtor, $listing) {
$realtor = Realtor::where('accountUrl', $realtor)->first();
$phoneNumbers = $realtor->phoneNumbers()->orderBy('displayIndex', 'ASC')->get();
$links = $realtor->links()->orderBy('displayIndex', 'ASC')->get();
return view('realtorSites.showListingDetails', compact('realtor', 'phoneNumbers', 'links'));
}
I'm familiar with view composers but I haven't found a way to dynamically pass the request URL segment into the composer, and I'm not even sure if this is a good idea.
Could someone help me understand what the correct way to approach this is?
Upvotes: 0
Views: 123
Reputation: 9280
How about passing the request url segment to the view and letting the composer figure the rest out?
public function showPropertyDetails($realtor, $listing) {
return view('realtorSites.showListingDetails')
->with('accountUrl', $realtor);
}
And then...
View::composer('...', function ($view)
{
$view->realtor = Realtor::where('accountUrl', $view->accountUrl)
->first();
$view->phoneNumbers = $view->realtor->phoneNumbers()
->orderBy('displayIndex', 'ASC')->get();
$view->links = $view->realtor->links()
->orderBy('displayIndex', 'ASC')->get();
}
The only real hangup on this is it could result in a lot of DB calls if the composer applies to several views rendered in the same request. This is more of an Eloquent ORM issue than anything else and is solved by using lazy loaders and ordering the cached result. This is something I consider an important best practice when you use relationships a lot.
// Makes a DB call, caches nothing in the model
$model->relationship()->orderBy('foo')->get();
// Caches relationships on model and reuses if possible
$model->relationship->sortBy('foo');
Upvotes: 1
Reputation: 8663
I have done similar thing. I will just create the view and instead of just returning it I will return method where I modify the view, Something like this:
public function index() {
$view = view("index");
return $this->addDetails($view);
}
private function addDetails($view) {
$realtor = Realtor::where('accountUrl', $realtor)->first();
return $view->with('realtor', $realtor);
}
Upvotes: 0