Home » Php » laravel – How can I print this query result on my show.blade.php?

laravel – How can I print this query result on my show.blade.php?

Posted by: admin February 25, 2020 Leave a comment

Questions:

How can I print the result of this query on my show.blade.php? This is what I did on my Controller:

public function getRating(Request $request){
            $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();
        }

And this is what I tried on my show.blade.php

<li class="nav-item">
     <form action="{{ action('[email protected]')}}" method="GET">
       <div>
         {{$results}}
       </div>
     </form>
</li>

I’m still learning and I looked for this before making this question but I don’t know if I couldn’t find it or if I wasn’t searching for the right thing, thanks.

How to&Answers:

try this

in your controller

public function getRating()
{
    $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();

    return view('show', ['results' => $results]);
}

you should pass variable to view
see this link

Answer:

Are you looking for something like this, perhaps?

RatingsController:

use DB; // Make sure you call this above the class

public function returnAverageStars()
{
    $results = DB::table('reviews')->where('stars', '>=', 1)->avg('stars');

    return $results;
}

public function show()
{
    return view('show', [
        'reviews' => $this->returnAverageStars()
    ]);
}

web.php

Route::get('/show', '[email protected]');

show.blade.php

<ul>
    <li>{{ $reviews }}</li>
</ul>