Php ErrorException未定义变量:posts
我想在几个不同的表中获取数据库中的一些字段数据,我在post模型中建立了表之间的关系,在ListingPageController中,我分配了post模型,并创建了名为$posts的变量,以便在list.blade.php页面中使用它。当我试图使用它时,它会给我这个错误,请帮助 下面的代码是ListingPageController页面:Php ErrorException未定义变量:posts,php,laravel,laravel-5,laravel-5.8,Php,Laravel,Laravel 5,Laravel 5.8,我想在几个不同的表中获取数据库中的一些字段数据,我在post模型中建立了表之间的关系,在ListingPageController中,我分配了post模型,并创建了名为$posts的变量,以便在list.blade.php页面中使用它。当我试图使用它时,它会给我这个错误,请帮助 下面的代码是ListingPageController页面: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class ListingPageController extends Controller
{
public function index(){
return view('front.listing');
}
public function listing($id){
$posts = Post::with(['comments','category','creator'])
->where('status',1)
->where('category_id',$id)
->orWhere('created_by',$id)
->orderBy('id','DESC')->paginate(3);
return view('front.listing',compact('posts'));
}
}
索引函数没有定义posts
变量。您需要更新视图或传递空变量:
public function index(){
return view('front.listing', ['posts'=>[]]);
}
或者在你看来:
@if(isset($posts))
@foreach($posts as $key=>$post)
...
@endif
或者创建一个新视图,更改逻辑等等,这取决于您。您可以这样尝试,看看它告诉您什么吗
return view('front.listing', ['posts' => $posts]);
EDIT1
验证传递给listing.blade.php
的内容是否正确。。在listing.blade.php
的第一行键入{{dd($posts)}
然后检查您得到的结果。控制器使用front.listing
文件,但您向我们显示的是list.blade.php
,它不是同一个文件。抱歉,我写错了,页面已经命名为listing哪个文件/行是错误的?如果它是一个视图,您可以在storage/framework/views
u中获得解析的代码,您可以将->where('status',1)->where('category_id',$id)
替换为->where(['status'=>1,'category_id'=>$id])->……
@ledsoft它会给出相同的错误我更喜欢为帖子传递一个空变量。非常感谢。
return view('front.listing', ['posts' => $posts]);