Laravel Blade组件传递post变量后访问属性报错问题
Laravel Blade组件变量访问异常问题
问题场景
在Laravel中通过Blade组件实现页面嵌套,父视图循环传递post变量:
@foreach($posts->skip(1) as $post) <x-post-card :post="$post"/> @endforeach
组件文件中通过@props(['post'])接收变量,执行@dd($post)时能正常输出变量内容,但访问$post->title等属性时,Laravel报错:Undefined variable: post。组件代码如下:
@props(['post']) @dd($post) <article class="transition-colors duration-300 hover:bg-gray-100 border border-black border-opacity-0 hover:border-opacity-5 rounded-xl"> <div class="py-6 px-5 lg:flex"> <div class="flex-1 lg:mr-8"> <img src="/images/illustration-1.png" alt="Blog Post illustration" class="rounded-xl"> </div> <div class="flex-1 flex flex-col justify-between"> <header class="mt-8 lg:mt-0"> <div class="space-x-2"> <a href="/categories/{{$post->category->slug }}" class="px-3 py-1 border border-blue-300 rounded-full text-blue-300 text-xs uppercase font-semibold" style="font-size: 10px">{{$post->category->name}}</a> </div> <div class="mt-4"> <h1 class="text-3xl .bold"> {{$post->title}} </h1> <span class="mt-2 block text-gray-400 text-xs"> Published <time>{{$post->created_at->diffForHumans()}}</time> </span> </div> </header> <div class="text-sm mt-2"> <p> {{$post->excerpt}} </p> </div> <footer class="flex justify-between items-center mt-8"> <div class="flex items-center text-sm"> <img src="/images/lary-avatar.svg" alt="Lary avatar"> <div class="ml-3"> <a href="/authors/{{$post->user->username}}"><h5 class="font-bold">{{$post->user->name}}</h5></a> <h6>Mascot at Laracasts</h6> </div> </div> <div class="hidden lg:block"> <a href="#" class="transition-colors duration-300 text-xs font-semibold bg-gray-200 hover:bg-gray-300 rounded-full py-2 px-8">Read More</a> </div> </footer> </div> </div> </article>
解决方案
清除Blade视图缓存
运行以下命令清除编译后的视图缓存,避免旧缓存导致的变量解析异常:php artisan view:clear移除
@dd语句后测试@dd($post)会终止脚本执行,导致后续代码未被实际解析。移除该语句后重新运行,确认变量是否能正常访问。检查组件文件命名与路径
确保组件文件位于resources/views/components/post-card.blade.php,文件名需与组件标签x-post-card对应(Laravel会自动解析短横线命名的组件标签)。确认变量传递语法正确性
父视图中:post="$post"的绑定语法正确(冒号表示传递PHP变量),此写法符合Blade组件变量传递规范,无需修改。辅助检查模型关联与属性
确保Post模型中存在title、excerpt等属性,且已正确定义category、user关联关系(避免因关联不存在导致的间接错误,当前报错核心为变量未定义,此为补充验证)。
内容的提问来源于stack exchange,提问作者RAM KAF
相关产品推荐
相关产品推荐

