【问题标题】:Laravel whereSlug not workingLaravel whereSlug 不工作
【发布时间】:2016-01-20 20:03:48
【问题描述】:

当我想用这样的 slug 在 laravel 中搜索票时:

 public function showTicket(Request $slug)
{
     $ticket = Ticket::whereSlug($slug)->firstOrFail();
     if(Auth::user()->id == $ticket->user_id)
     {
        return view('users.ticket')->with('ticket',$ticket);
     }
}

我收到错误:

> ModelNotFoundException in Builder.php line 157:
No query results for model [App\Ticket].
in Builder.php line 157
at Builder->firstOrFail() in UserTicketsController.php line 66
at UserTicketsController->showTicket(object(Request), '5627caed7b3bb')
at call_user_func_array(array(object(UserTicketsController), 'showTicket'), array(object(Request), 'slug' => '5627caed7b3bb')) in Controller.php line 256
at Controller->callAction('showTicket', array(object(Request), 'slug' => '5627caed7b3bb')) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(UserTicketsController), object(Route), 'showTicket') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))

还有这个错误:

Handler.php 第 46 行中的 NotFoundHttpException:没有查询结果 模型 [App\Ticket]。在 Handler.php 第 46 行 处理程序->渲染(对象(请求),对象(ModelNotFoundException)) Kernel->renderException(object(Request) 处的 Kernel.php 第 281 行, object(ModelNotFoundException)) 在 Kernel.php 第 91 行 index.php 第 54 行中的 Kernel->handle(object(Request))

但是当我这样做时:

$ticket = Ticket::whereId(1)->firstOrFail();

有效吗?所以它可以找到模型。我现在知道可能出了什么问题。当我查看数据库时,当我点击一张票时,slug 也存在,网址是正确的,这是我的路线:

Route::get('ticket/{slug?}','UserTicketsController@showTicket');

请帮助我。

【问题讨论】:

    标签: php mysql model laravel-5


    【解决方案1】:

    如果你使用Request 类试试这个:

    $ticket = Ticket::whereSlug($slug->get('id'))->firstOrFail();
    

    如果您要传递参数,请不要使用Request 类型。

    public function showTicket($slug)
    {
        $ticket = Ticket::whereSlug($slug)->firstOrFail();
    

    【讨论】:

    • 谢谢你的工作。已经为此搜索了一个小时-_-。
    猜你喜欢
    • 2014-03-19
    • 2018-07-22
    • 2019-01-03
    • 2018-02-12
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多