user3755946
user3755946

Reputation: 804

My variable does not seem to be available in blade view

My Route...

   Route::get('/test', function () {

    $word = ['Hello'];



    return view('test', $word);
});

My Blade View...

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel Quickstart - Basic</title>
    <link href="{{ asset('/css/app.css') }}" rel="stylesheet"/>
    <link href="{{ asset('/css/Test.css') }}" rel="stylesheet"/>
    <!-- CSS And JavaScript -->
</head>

<body>

<div class="container">
    <nav class="navbar navbar-default">
        {{$word}}
    </nav>
</div>



</body>
</html>

I get the following erro when accessing the app via a browser...

(2/2) ErrorException Undefined variable: word (View: /home/vagrant/Code/Laravel/resources/views/test.blade.php)

When I remove $word form the blade view and replace with a static string "test" it displays correctly.

no idea why the blade view can't see the $word varible, any ideas anyone?

Upvotes: 0

Views: 84

Answers (3)

Karl
Karl

Reputation: 5463

You need to return it to the view in one of two ways:

return view('test', compact('word'));

Or

return view('test', ['word' => $word]);

Either of these methods will then enable you to use the $word variable from within the blade file

You can see an example of this within the documentation here: https://laravel.com/docs/5.4/blade#displaying-data

Upvotes: 2

Exiam
Exiam

Reputation: 91

To complete Karl's answer, you can see an example there : https://laravel.com/docs/5.4/views#creating-views

Upvotes: 1

Sagar Gautam
Sagar Gautam

Reputation: 9369

Change this line

return view('test', $word);

To

return view('test', compact('word'));

The variable will be available in your blade.

Upvotes: 1

Related Questions