You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 向同一视图传递多个参数报Undefined variable $blogs错误

问题原因

你的web.php路由文件中存在两条路径、名称完全一致的/home路由:

Route::get('/home', [App\Http\Controllers\BlogController::class, 'index'])->name('home');
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Laravel路由匹配逻辑为后定义的同路径/同名路由会覆盖先定义的规则,因此实际生效的只有HomeController@index对应的路由,你写的BlogController@index根本不会被触发。而HomeController的index方法仅传递了all_cards和chefs变量,未传递blogs,自然会报变量未定义的错误。

修复步骤

  1. 删除web.php中BlogController对应的重复/home路由,仅保留HomeController对应的那条/home路由即可。
  2. 修改HomeController.php的index方法,补充blogs变量的查询和传递:
// 首先确保文件顶部已引入Blog模型
use App\Models\Blog;

public function index(Request $request)
{
    $search = $request->get('search');
    $all_cards = DB::table('posts')->where('name','like','%'.$search.'%')->paginate(5);
    $chefs = HomeChef::all();
    // 新增Blog数据查询
    $blogs = Blog::all();
    return view('home.home',compact('all_cards','chefs','blogs'));
}
  1. (可选优化)在home.blade.php中增加变量存在判断,避免无数据时报错:
@isset($blogs)
    @foreach ($blogs as $blog)
    <!-- 原有循环代码
    @endforeach
@endisset

内容的提问来源于stack exchange,提问作者riledrat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:30:00