在错误页面上显示表单错误并在 Laravel 中进行验证

如果$request->SN无效或为空,我会收到如下错误。


试图获取非对象的属性


Ticket::create([

    'user_id' => Laptop::where('SN', $request->SN)->first()->user_id,

    'laptop_id' => Laptop::where('SN', $request->SN)->first()->id,

    'title' => $request->title,

    'body' => $request->body,

    'laptop_ww' => $request->laptop_ww

]);

如何显示自定义错误而不是此异常?默认情况下,它会转到状态为 500 的错误页面。


噜噜哒
浏览 101回答 2
2回答

慕雪6442864

public function save(Request $request){    try{    Ticket::create([        'user_id' => Laptop::where('SN', $request->SN)->first()->user_id,        'laptop_id' => Laptop::where('SN', $request->SN)->first()->id,        'title' => $request->title,        'body' => $request->body,        'laptop_ww' => $request->laptop_ww    return view(your_address, "successfully saved");    ]);    }catch(Exception ex){    return view(your_address, "Custom error here");    }  }

牧羊人nacy

试试下面 -$laptop = Laptop::where('SN', $request->SN)->first();if(null === $laptop){    throw new Exception('No laptop found with SN'.$request->SN);}if(null === $laptop->user_id){    throw new Exception('Laptop with SN:'.$request->SN.' does has any user'.);}Ticket::create([            'user_id' => $laptop->user_id,            'laptop_id' => $laptop->id,            'title' => $request->title,            'body' => $request->body,            'laptop_ww' => $request->laptop_ww        ]);您将保存查询并处理错误。
打开App,查看更多内容
随时随地看视频慕课网APP