Php Laravel ModelNotFoundException:没有模型[]的查询结果
运行测试时出现以下错误: ModelNotFoundException:没有模型[App\Content]的查询结果 这是我的测试:Php Laravel ModelNotFoundException:没有模型[]的查询结果,php,mysql,laravel,laravel-artisan,Php,Mysql,Laravel,Laravel Artisan,运行测试时出现以下错误: ModelNotFoundException:没有模型[App\Content]的查询结果 这是我的测试: /** @test */ public function it_loads_homepage() { $this->withoutExceptionHandling(); $response = $this->get('/'); $response->assertStatus(200); } 这是我的控制器: publ
/** @test */
public function it_loads_homepage()
{
$this->withoutExceptionHandling();
$response = $this->get('/');
$response->assertStatus(200);
}
这是我的控制器:
public function home()
{
$topbar = Content::where('slug', 'topbar')->firstOrFail();
return view('welcome')->with([
'logo' => Arr::get($topbar->content, 'logo', asset('images/logo.png')),
'quote' => Arr::get($topbar->content, 'quote'),
'quote_author' => Arr::get($topbar->content, 'quote_author')
]);
}
$topbar = Content::where('slug', 'LIKE', '%topbar%')->firstOrFail();
这是我的路由文件:
Route::get('/', 'PageController@home');
Route::post('/admin/content', 'ContentsController@store');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::middleware('auth')->prefix('admin')->group(function () {
Route::get('/dashboard', 'DashboardsController@index');
Route::patch('/contents/{content}', 'ContentsController@update');
});
如果有人对如何帮助他们有任何想法,我们将不胜感激,谢谢
另外,如果我需要包括任何其他内容,请让我知道,谢谢 查询生成器中的find()方法可以返回模型实例,如果在数据库中找不到记录,则返回null。所以,您必须首先检查用户是否存在来处理此问题。如果他这样做了,你可以显示他的头像,否则你可以显示登录按钮
您的代码有点凌乱,我建议您不要将逻辑与视图代码混用。您应该在控制器中获取用户,然后将其传递给视图
$topbar = Content::where('slug', 'topbar')->get()->toArray();
return view('welcome')->with([
'logo' => Arr::get($topbar->content, 'logo', asset('images/logo.png')),
'quote' => Arr::get($topbar->content, 'quote'),
'quote_author' => Arr::get($topbar->content, 'quote_author')
]);
异常告诉您没有与该条件匹配的
Content
对象。从:
未发现异常
有时,如果找不到模型,您可能希望抛出异常。
这在路由或控制器中特别有用。findOrFail
而firstOrFail
方法将检索查询的第一个结果;
但是,如果未找到结果,则
将抛出illumb\Database\elount\ModelNotFoundException
检查您的位置
状况:
$topbar = Content::where('slug', 'topbar')->firstOrFail();
确保在目录中有一条带有slug=topbar的记录(请记住这是区分大小写的)。您在其中一条评论中说您确信,因此请使用以下内容查看:
这应该输出:
[!]将此修补程序会话的“用法”别名为“应用程序\内容”
=>1//或者更多
要获取记录,您可以尝试以下操作(在控制器中):
此外,您的句子很可能只是当前代码的一个示例,但如果不是,请确保在where子句中传递实际值:
$topbar = Content::where('slug', 'LIKE', request('slug'))->firstOrFail();
content dB表有一个存储JSON的内容列。此逻辑在我的控制器中,而不是在我的视图中。JSON包含记录的所有数据Content::where('slug','topbar')->firstOrFail()代码>或失败部分正在引发异常。测试时确保记录存在。是,测试只确保页面加载返回200状态代码。我已经核实了记录确实存在。谢谢。我明天会看一看
$topbar = Content::where('slug', 'LIKE', request('slug'))->firstOrFail();