运行测试时出现此错误:
ModelNotFoundException: No query results for model [App\Content]
这是我的测试:
/** @test */
public function it_loads_homepage()
{
$this->withoutExceptionHandling();
$response = $this->get('/');
$response->assertStatus(200);
}
这是我的 Controller :
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')
]);
}
这是我的路线文件:
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。因此,您必须首先检查用户是否存在来处理此问题。如果他这样做,您可以显示他的头像,否则您可以显示登录按钮。
您的代码有点困惑,我建议您不要将逻辑与 View 代码混合在一起。您应该在 Controller 中获取用户,然后将他传递给 View
$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')
]);
关于php - Laravel ModelNotFoundException : No query results for model [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874093/