Laravel Faster to query everything in controller or view

后端 未结 3 1293
[愿得一人]
[愿得一人] 2021-01-27 01:13

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

Exam

相关标签:
3条回答
  • 2021-01-27 01:37

    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.

    0 讨论(0)
  • 2021-01-27 01:39

    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 
    
    0 讨论(0)
  • 2021-01-27 01:55

    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.

    0 讨论(0)
提交回复
热议问题