未定义变量:posts(视图:/home/../annonces/resources/views/welcome.blade.php)
你好,我有问题,我尝试在laravel 5.8中创建搜索栏 欢迎使用.blade.php未定义变量:posts(视图:/home/../annonces/resources/views/welcome.blade.php),php,laravel,laravel-5.8,Php,Laravel,Laravel 5.8,你好,我有问题,我尝试在laravel 5.8中创建搜索栏 欢迎使用.blade.php @extends('layouts.app') @section('content') <div class="container"> @foreach ($posts as $post) <div class="card" style="width: 18rem;"> <img class="card-img-top" src
@extends('layouts.app')
@section('content')
<div class="container">
@foreach ($posts as $post)
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
@endforeach
</div>
@endsection
但我有一个错误:
未定义变量:posts(视图:
/home/savinov/annonces/resources/views/welcome.blade.php)
不明白为什么它是未定义的变量如果我在控制器中定义他,
如果可能的话,有人可以帮我吗?您可以尝试以下选项 选项1
public function index()
{
$posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(10);
return view('welcome', ['posts' => $posts]);
}
选项2
public function index()
{
$posts = Post::orderBy('created_at', 'DESC')->paginate(10);
return view('welcome',compact('posts'));
or
return view('welcome', ['posts' => $posts]);
}
您是否已检查控制器中是否有数据$posts?请尝试控制器中的
dd($posts)
,以查看您得到了什么。您也可以将其作为returnview('welcome',$posts)传入代码>因为你只传递了一个变量Dont work my friend…@DenKot什么不起作用?你能说得更具体些吗?他让你做的不止一件事。dd($posts)
返回给你的是什么?当我添加选项1时,它使用了未定义的常量posts-假定的“posts”(这将在未来的PHP版本中抛出一个错误)是的,因为它是$posts
,而不是posts
。另外,@Hamelraj,尽管你给了他其他选择,你的答案并没有回答问题本身。你是最好的((()())())))
public function index()
{
$posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(10);
return view('welcome', ['posts' => $posts]);
}
public function index()
{
$posts = Post::orderBy('created_at', 'DESC')->paginate(10);
return view('welcome',compact('posts'));
or
return view('welcome', ['posts' => $posts]);
}