【问题标题】:Undefined variable: students (View: D:\exam\curd\resources\views\home.blade.php) in Laravel 5.7 [duplicate]未定义变量:Laravel 5.7 中的学生(查看:D:\exam\curd\resources\views\home.blade.php)[重复]
【发布时间】:2019-09-22 15:40:24
【问题描述】:

使用 laravel 5.7 需要在主页 home.blade.php 中显示学生表数据

<table class="table">
    <thered>
     <tr>
         <td>Id</td>
         <td>Name</td>
         <td>Address</td>
         <td>Telephone</td>
         <td>Actions</td>
     </tr>
    </thead>

    <tbody>
      @foreach ($students as $student)
      <tr>
        <td>{{$student->id}}</td>
        <td>{{$student->name}}</td>
        <td>{{$student->address}}</td>
        <td>{{$student->telephone}}</td>
        <td><a class="button is-outlined" href="">Edit</a></td>
        <td><a class="button is-outlined" href="">Delete</a></td>
      </tr>
      @endforeach
    </tbody>
</table>

StudentController.php

public function index()
{
    $students = Student::all();

    return view('home');
}

web.php

Route::get('StudentController@index');

但收到这样的错误消息,

未定义变量:students(查看:D:\exam\curd\resources\views\home.blade.php)

我该如何解决这个问题?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您需要将学生传递给视图,因此请在您的控制器中添加以下内容:

    return view('home', compact('students'));
    

    你的路线:

    Route::get('/home', 'StudentController@index'); // if this is your root route
    

    【讨论】:

    • 做了但同样的错误在这里
    • @banda 除非您不通过该控制器方法加载页面,否则这是不可能的。检查我对路线的编辑。
    • 也使用了上面的路线,但这里没有成功,这里同样的错误
    • 您可以尝试在控制器中倾倒一些东西,以确保您至少可以进入那里吗?如果在您的浏览器中打印,请在您的索引函数中尝试dd('test');
    • 很好 @nakov 现在它工作正常
    【解决方案2】:

    您需要在视图中传递$students 变量。您可以使用compact() 函数或其他许多方式来做到这一点。

    public function index()
    {
        $students = Student::all();
        return view('home', compact('students'));
    }
    

    【讨论】:

    • 做了但同样的错误在这里
    • 在你的控制器方法中尝试dd('hit')。确保它符合index() 方法。
    猜你喜欢
    • 2019-11-07
    • 2019-11-07
    • 2021-01-08
    • 2018-07-10
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多