简体   繁体   English

为什么模型在路径和控制器中起作用而在视图中不起作用?

[英]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. 我是laravel中非常有经验的程序员,并且在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. 但是,我已经开始使用laravel 5了,有些问题困扰着我,我花了几个小时而无法解决这个问题。

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. 每当我想从数据库表中获取模型并将其设置为变量以使用它时,在routes.php或控制器文件中执行该操作时,它似乎都能正常工作,但在查看文件。

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 如果我的视图文件不包含任何html,除了上面的代码段外,我得到以下信息:请参见图片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,并且我使用相同的代码,例如:

<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 我收到错误的未定义变量: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. 我已经制作了一个Models文件夹,并将模型放在该文件夹中。代码是正确的,并且它可以在所有地方使用,但如果我像上面那样直接使用它,则在视图中除外。 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. 谢谢treeface,我实际上忽略了我没有启用php short标签的情况。

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. 通常,将逻辑与表示分离是正确的做法,因此最好在控制器中设置变量,然后将变量传递给视图,但是,如果要或需要在视图中设置变量,则应使用<?php ?>标签以设置变量。 You can then output the variable as you would normally with Blade syntax. 然后,您可以像通常使用Blade语法那样输出变量。

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

Would output: 将输出:

<body>
    bar
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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