Reputation: 1331
Is it faster to query everything in the controller and return every query back, or query in view as you use it?
Assuming all the models had the relationship
Example:
Do everythig in cotroller and then return
Public function articlesHome($id)
{
$art = Articles::find($id);
$cit = Articles::city();
$tag = Articles::tags();
Return view('articles', compact('art', 'tag', 'cit');
}
Or in view (after controller returned $article)
{{ $article->name }}
...
{{ $article->city->name }}
...
@foreach($article->tags as tag)
{{ tag->name }}
@endforeach
Which is best in practice and faster.
Upvotes: 1
Views: 2791
Reputation: 3299
Performance wise it's just a matter of finding a way to get fewer database queries to achieve the same result.
A good approach would be let laravel do it for you in a single command:
Public function articlesHome($id)
{
$article = Articles::whereId($id)->with('city','tags')->get();
Return view('articles', compact('article');
}
Your view would be the same. The articles relationships is already built, so no extra queries will be made.
{{ $article->name }}
...
{{ $article->city->name }}
...
@foreach($article->tags as tag)
{{ tag->name }}
@endforeach
Upvotes: 2
Reputation: 137
I assume it is faster to do it in the view as long as you save time sending it to the view. I recommend you that you install laravel debugbar to see the details.
Upvotes: 1
Reputation: 4167
A good pattern to read up on is MVC which stands for Models, Views and Controllers.
It's a design pattern that focuses of Separation of Concerns, where you separate the different concerns of your applications into different sections. The data retrieval is the Model (typically a database but not necessarily), a View (the Blade templates) and the Controller.
You can go beyond just MVC and separate things further to include Repositories, Events & Commands for a better separation.
The reason you might want to use Repositories (which are just wrappers around your Model) is to abstract the actual retrieval and persistence of your data from your Controller, allowing you to change from using a database to another form of strange without having to update the code in your controllers.
Upvotes: 2