Search code examples
laravellaravel-5eloquenteager-loading

How to output Eloquent Eager Loading in View (blade files) in Laravel?


I have a question related to this LINK:

Laravel / Eloquent eager loading

Can you help me with the output in blade now with this? I implement this eloquent relation and add this in controller correctly, But how to output this in view now - in blade file!?

Can you write a little code for this example Comments - Tags. If we want to show that in a blade. To see this like child's into parents in some way.?

For example to output Questions and related tags what belongs in particular question. Like for example: Question1 [ Tag1 - Tag4 - Tag12 ] - - - Question2 [ Tag1 Tag 8 Tag5 ] ... and so on, like in some tree in view like in olx we see categories inside that it shows subcategories. olx.com.om/en. Or another example when we have: COUNTRIES AND CATEGORIES (MANY TO MANY RELATION), and want to list CATEGORIES in view above, and countries that belong to particular category below.

Thanks in advance, I am new to laravel want to start my own blog I am learning laravel for 2 + months.


Solution

  • In your controller function, will look like this.

    $questions = Question::with('tags')->get();
    
    $title = "List of questions";
    
    return view('test', compact('questions', 'title'));
    

    In your blade will look like this and see how the tags relationships being called.

       <!-- ouput: List of questions-->
        <h2> {{ $title }} </h2>
    
        <!-- ouput:list of questions -->
        @foreach($questions as $question) 
           Question Name : {{ $question->name }}
    
            <b> Tags: </b> 
            @foreach($question->tags as $tag) 
                  {{ $tag->name }} 
            @endforeach
    
        @endforeach 
    

    That's how you output the data to your blade file. Hope that gives you an idea.