简体   繁体   中英

Show form errors on error page with validation in Laravel

If the $request->SN is either invalid or empty, I get an error like the following.

Trying to get property of non-object

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
]);

How can I display a custom error instead of this exception? By default, it goes to an error page with status 500.

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");
    }
  }

Try below -

$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
        ]);

You will save a query and also errors are handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM