Search code examples
phplaraveleloquentviewmodel

Laravel: display data in view without Eloquent


Let's say I need to display a list of articles in a view. So I run a complex query to get all needed data and I get a resulting table, for example, like this:

| id | article_name | article_body | article_tag_id | ... (many more columns)

There is also a model defined: Article.php.

Question: what is the proper way to prepare data for view in Laravel? I'd also like to add that I'm looking for a way to do this without using Eloquent. Sure I could just do $articles = Article::all(); but what if I'm dealing with very complex queries and I need to load objects manually by controlling the loading logic.

In the case above, what I would like to do is to create a model and pass each row to a method load() like this:

$model = new Article();
$model.load(row);
array_push($dataForView, $model);

and finally send data to view

return view('articles')->with('articles', $dataForView);

Is this something I should do in Laravel?


Solution

  • I'm not sure that you want to be avoiding Eloquent all together. But you can abstract your complex query to a method on your model:

    // article.php
    
    public function my_complex_query()
    {
    
        // code here. Eloquent, or Query Builder or 
        // Raw SQL
    
        return $result;
    
    }
    

    Then call that from your Controller:

    return view('the-view')
        ->withArticles(Article::my_complex_query());
    
    // or you can inject your model into your controller and call $this->article->my_complex_query()
    

    And then loop through the data in your view. This is the beauty of eloquent because it maps your database results to an object.

    @foreach ($articles as $article)
    {{ $article->name }}
    // ...
    @endforeach