【问题标题】:Undefined variable Laravel 8 [closed]未定义的变量 Laravel 8 [关闭]
【发布时间】:2021-08-03 19:04:39
【问题描述】:

我得到未定义的变量使用 Laravel 8 运行此代码
控制器

public  function index(){
   $customers =customers::all();
   return view('welcome',["customers"=>$customers]);
}

Welcome.blade.php

@foreach ($customers as $customers)
<tr>
 <td>{{ $customers->fullname }}</td>
 <td>{{ $customers->phone }}</td>
 <td>{{ $customers->item }}</td>
 <td>{{ $customers->itemprice }}</td>
 <td>{{ $customers->prepayment }}</td>
 <td>{{ $customers->created_at }}</td>
 <td>{{ $customers->updated_at }}</td>
</tr> 
@endforeach

【问题讨论】:

  • 欢迎来到 SO,我认为最好向我们展示您在尝试中遇到的错误以及您看到的输出。这对于社区更多地参与您的回答以解决您的问题很重要

标签: laravel laravel-8


【解决方案1】:

我认为您的问题出在刀片上:'@foreach ($customers as $customers)' 你可以试试下面的代码:

在您的控制器中:

public function index()
{ 
    $customers = Customers::all();
    return view('welcome', ['customers' => $customers]);
}

欢迎刀片:

@foreach ($customers as $customer)
<tr>
  <td>{{ $customer->fullname }}</td>
  <td>{{ $customer->phone }}</td>
  <td>{{ $customer->item }}</td>
  <td>{{ $customer->itemprice }}</td>
  <td>{{ $customer->prepayment }}</td>
  <td>{{ $customer->created_at }}</td>
  <td>{{ $customer->updated_at }}</td>
</tr> 
@endforeach

【讨论】:

  • 解决不了。
  • @Zhilamo 您能否提供有关错误的更多详细信息?
  • 这是我的错误 ErrorException Undefined variable $customers (View: C:\xampp\htdocs\test-3\resources\views\welcome.blade.php) 任何认为我确实向我展示了这个错误
  • @Zhilamo 您能否编辑您的问题并添加您的路线文件?使用新版本再次复制您的控制器和刀片,以便 SO 社区尝试帮助您
  • @Zhilamo 运行php artisan view:clearphp artisan cache:clear,因为这正确答案。您在 foreach 循环中使用了相同的变量名,这会破坏事情。
【解决方案2】:

我也遇到过同样的错误。 这可能是由于缓存而发生的。

使用清除缓存命令,稍后使用相同的代码重试

在终端中使用这两个命令

php artisan cache:clear

php artisan view:clear

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多