2
votes

In my previous question, I got to perform a raw SQL query.

I've declared an public function in my controller:

public function deaths()
{
    $getdeaths = DB::statement('SELECT * FROM player_deaths ORDER BY time DESC LIMIT 10');
    return View::make('main.latestdeaths')->with('getdeaths', $getdeaths);
}

When retrieving data, I want to display players name, so inside the view in a foreach, is tried to run a SQL query.

        @foreach($getdeaths as $getdeath)
    <tr>
        <? $name = DB::select( DB::raw('SELECT name FROM players WHERE id = '$getdeath->player_id'') ) ?>
        <td>{{ $getdeath->player_id }}</td>
        <td></td>
        <td></td>
    </tr>
    @endforeach

When I try to echo $name, the variable is not defined.

Can I parse it some other way?

3
I've seen this recently in a stranger code. Why would anyone want to query from the view? This is ugly and breaking the MVC conventions. Please avoid doing such stuff or get used to develope structured . . . . I cant tell much about Laravel but considering other MVC-Frameworks you might be interested in Model-relations which is common and following the conventions. Be clever. Split logic.Jonathan

3 Answers

2
votes

here you go :

$getDeaths = DB::table('player_deaths')->orderBy('time','desc')->take(10)->get();
return View::make('main.latestdeaths')->with('getDeaths', $getDeaths);

That will give you an object of all your player_deaths ordered by time.

0
votes

You are using DB::select so you have to do a get() to retrieve the records, by the way, is not good make SQL queries on the views, don't respect the MVC arquitecture pattern.

0
votes

look at view composers. basically a filter or class method that gets called when certain view names are rendered and assigns a view variable automatically.

tell the composer to run the query and set the deaths variable for the views you want the information available in.

you can then loop over the variable as if you had assigned it in your view.