简体   繁体   中英

why do the Models work in routes and in controllers but not in views?

I am a pretty experienced programmer in laravel and have worked on some projects in laravel 4.2. However I have started working with laravel 5, and something is bugging me, I have spent hours on it and I haven't been able to solve this.

Whenever I want to grab a model from a database table and set it to a variable in order to use it, it seems that it works correctly when doing it in the routes.php or a controller file, but it doesn't work in the view files.

for example this simple piece of code works in the routes and controllers but not in view files:

$user = App\Models\User::find(1); 
        echo $user->username;

if I have a view file that doesn't contain any html, except for the piece of code above I get this: see image http://i.imgur.com/WhRcxYl.png

however if I do have html in the view file and I use the same code with it like this:

<html>
<head>
    <title>example</title>

</head>
<body>
    <? $user = App\Models\User::find(1); ?>
    <p>this doesn't work <?= $user->username; ?></p>    
</body>

I get the error Undefined variable: user

I have no idea, it could be something really small that I am not seeing, but I really can't see it. I have made a folder Models and put the models in that folder..the code is correct and it works everywhere except in the views if I used it directly like above. the table is filled with users and is not empty.

the problem has been solved. Thank you treeface, I actually overlooked that I didn't have the php short tags enabled.

It's generally correct practice to separate logic from presentation so it's probably best to set the variable in the controller and then pass the variable to the view, but if you want or need to set the variable in the view, you should use <?php ?> tags to set the variable. You can then output the variable as you would normally with Blade syntax.

<body>
    <?php $foo = 'bar'; ?>
    {{ $foo }}
</body>

Would output:

<body>
    bar
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM