Asynchronous query to load products from laravel controller The following code works fine. When a user clicks on an element, an AJAX request is made, which will return the query result. The results are being displayed in a view. I read many articles where everyone is doing HTML code in controller when getting data with AJAX and show in view as same I did. Any good suggestions to avoid HTML code in controller make controller view and script separate.

Controller:

public function ajax(Request $request){ 

// $data = $request-&gt;all();

$data['products'] = Product::select('products.id', 'products.name', 'products.banner')-&gt;get();

foreach ($data['products'] as $product){
    echo $product-&gt;name;
}



// dd($data);
// if($request-&gt;ajax()){
//     return "AJAX";
// }
// return "HTTP";

// $data['products'] = Product::select('products.id', 'products.name', 'products.banner')-&gt;get();
// return $data;


}

Script

 &lt;script type="text/javascript"&gt;

    // $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
        $(document).ready(function(){

        // Load more data
        $('.load-more').click(function(){
            var row = Number($('#row').val());
            var allcount = Number($('#all').val());
            var rowperpage = 3;
            // row = row + rowperpage;
            row = row + 3;

            if(row &lt;= allcount){
                $("#row").val(row);

                $.ajax({
                url: "{{ route('ajax') }}",
                type: 'post',
                datatype: 'JSON',
                headers: {
                    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
                },
                data: {row:row},
                // error: function(XMLHttpRequest, textStatus, errorThrown) {
                //     alert('hi');
                // }

                success: function(response){

                // Setting little delay while displaying new content
                setTimeout(function() {
                    // appending posts after last post with class="post"
                    $(".post:last").after(response).show().fadeIn("slow");

                    var rowno = row + 3;

                    // checking row value is greater than allcount or not
                    if(rowno &gt; allcount){

                        // Change the text and background
                        $('.load-more').text("show less");
                        $('.load-more').css("background","darkorchid");
                    }else{
                        $(".load-more").text("Load more");
                    }
                }, 2000);


                }

 });

            }else{
        $('.load-more').text("Loading...");

        // Setting little delay while removing contents
        setTimeout(function() {

            // When row is greater than allcount then remove all class='post' element after 3 element
            $('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");

            // Reset the value of row
            $("#row").val(0);

            // Change the text and background
            $('.load-more').text("Load more");
            $('.load-more').css("background","#15a9ce");

        }, 2000);


    }

        });

        });
&lt;/script&gt;


view

    @foreach($leedManufacturers as $leedsManufacturer)
                    {{-- @foreach($leedManufacturers as $leedsManufacturer)  --}}
                        &lt;div class="post" id="post{{$leedsManufacturer['id']}}"&gt;
                            &lt;label class=" my-checkbox gry2" id="manufacturer"&gt;{{str_limit($leedsManufacturer['name'], 300)}}
                                    &lt;input type="checkbox"&gt;
                                    &lt;span class="checkmark"&gt;&lt;/span&gt;
                            &lt;/label&gt;
                        &lt;/div&gt;
                        {{-- for load more script --}}
                    {{-- &lt;input type="hidden" id="row" value="0"&gt; --}}

                    {{-- &lt;input type="hidden" id="all" value="{{$total_manufacturers}}"&gt; --}}
                    @endforeach
Your example:

public function ajax(Request $request){ 
$data['products'] = Product::select('products.id', 'products.name', 'products.banner')-&gt;get();

foreach ($data['products'] as $product){
    echo $product-&gt;name;
}


Attn: I omit commented string.

You do not need to get the query results into $data, especially if before you perform $data = $request-&gt;all();. Use another variable, in this case the $products may be okay.

If your 'Product' model is correct, then in the query you not need to use products.id - i.e. table name, need just field name.

Next, when you want pass the result to view, you need to do so as described in Doc:

return view('your_view_name', ['products' =&gt; $products]);

As described in official documentation  - versions there are from 5.0 up to 5.8, choose any you need.

So, this part of your code becomes:

public function ajax(Request $request){ 
    $products = Product::select('id', 'name', 'banner')-&gt;get();
    return view('your_view_name', ['products' =&gt; $products]);
}


Remember 2 things: 


With that query you'll get all products from DB and there may be a huge number of results.
the view has to be a blade type of template.


In your 'view' I see this line:

@foreach($leedManufacturers as $leedsManufacturer)

but I do not see a variable $leedManufacturers in the controller so you have no data for it.

To show $products result use the same but for $products, like:

&lt;ol&gt;
    @foreach($products as $product)
        &lt;li&gt;
            &lt;div&gt;id: {{$product-&gt;id}}, name: {{$product-&gt;name}}&lt;/div&gt;
            &lt;div&gt;{{$product-&gt;banner}}&lt;/div&gt;
        &lt;/li&gt;
    @endforeach
&lt;/ol&gt;


Also, when you need , you may use this (example)

@if (xxxxxxxxx === 1)
    I have one record!
@elseif (yyyyyyyyyy &gt; 1)
    I have multiple records!
@else
    I don't have any records!
@endif


https://laravel.com/docs/5.3/blade#if-statements

And in view you can use even

@php
    pure php code here
@endphp