Question

I just started with Laravel and got stuck when I tried to retrieve values from databse and tried to output them on the view through the router. Here's my code in router:

Route::get('/', function(){
    $posts =  DB::select("select title from posts");
    return View::make("hello", $posts);
});

Code in view using blade template:

@extends('master')

@section('title')
    @foreach ($posts as $post) {
        {{ $post->title }}
    @endforeach
@endsection

I tried to check the query and it runs perfectly, but I get the undefined variable error on the viewed page.

enter image description here

What is it that I'm doing wrong and how do I correct it? Please help..

Était-ce utile?

La solution

Try this:

$posts = DB::select(DB::raw('SELECT title FROM posts'));

or:

$posts = DB::table('posts')->select('title')->get();

And returning View:

return View::make('hello', ['posts' => $posts]);

You need to assign the $posts to a variable before sending to the view. In the above, the variable is posts.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top