php - Laravel ModelNotFoundException : No query results for model []

标签 php mysql laravel laravel-artisan

运行测试时出现此错误:

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/

相关文章:

php - 这些功能有什么问题?

mysql - 如何在MySQL中返回数据透视表输出?

php - 在表单中加载数据并更新数据库中的行

php - Laravel hasManyThrough 与非默认本地键的关系

php - Laravel 查询记录缺少更新查询

Php 搜索脚本仅选取第一个单词

php - MySQL查询仅显示按用户分组的最后一个项目

php - 使用 Guzzle HTTP 客户端时如何禁用代理?

php - 从特定表中获取 id 并更改它

php - Laravel Eloquent 查询数据透视表