Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cant send a variable to Blade in Laravel 5.1

I'm trying to send a variable to blade view, but throw this error:

Undefined variable: data (View: D:\wamp\www\tienda\resources\views\cliente.blade.php)

This is my Route:

Route::resource('cliente','ClienteController');

This is my Controller Cliente:

public function index(){

    $data = Cliente::all();

    return view('cliente',compact($data));
}

And my Blade:

 @foreach ($data as $user)
        <tr>
            <td>{{$user->nombre}}</td>
        </tr>
    @endforeach

What I'm doing wrong?

Additionally, if a try to do for example this Controller Cliente:

    public function index(){
    return view('cliente', ['name' => 'James']);
}

And Blade:

{{$name}}

That yes work... Only the variables and arrays, doesnt work.

like image 585
Alejandro Martinez Avatar asked Aug 02 '15 05:08

Alejandro Martinez


2 Answers

Try this on your Controller:

public function index(){
    $data = Cliente::all();
    return view('cliente',compact('data'));
}

From the compact documentation: "Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively. "

like image 80
Juan Serrats Avatar answered Oct 25 '22 02:10

Juan Serrats


you can try this way

public function index(){
$data['data'] = Cliente::all();
return view('cliente', $data);
}

Then you can catch it in blade as like this

 @foreach ($data as $user)
    <tr>
        <td>{{$user->nombre}}</td>
    </tr>
@endforeach
like image 44
Imtiaz Pabel Avatar answered Oct 25 '22 02:10

Imtiaz Pabel