I got this error after i click the approve button can someone help me fix this error, I'm beginner in laravel
controller
public function approved(Request $request)
{
try{
$leaves = LeaveAdmin::find($request->id);
$leaves->status = 'Approved';
$leaves->save();
DB::commit();
Toastr::success('Leave Request Approve Successfully','Success');
return redirect()->back();
} catch(\Exception $e) {
DB::rollback();
Toastr::error('Failed to Approve Request','Error');
return redirect()->back();
}
}
blade view
<div id="approve_leave" role="dialog">
<div >
<div >
<div >
<div >
<h3>Leave Status</h3>
<p>What do you want to do with this request?</p>
</div>
<div >
<div >
@csrf
<input type="text" name="id" value="{{ $leaves->id}}">
<div >
<a href="{{ route('Approved') }}" >Approve</a>
</div>
<div >
<a href="javascript:void(0);" data-dismiss="modal" >Reject</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
this is my approve modal and it has error when i click the approve on this modal
CodePudding user response:
Check if $leaves exist
$leaves = LeaveAdmin::find($request->id);
if( isset($leaves) && !is_null($leaves)) {
$leaves->status = 'Approved';
$leaves->save();
DB::commit();
Toastr::success('Leave Request Approve Successfully','Success');
return redirect()->back();
} else {
// do the rest part...
}
CodePudding user response:
These is happened because $leaves
return null
.
Therefore use the findOrFail
method. and also shorten the code.
$leaves = LeaveAdmin::findOrFail($request->id);
$leaves->status = 'Approved';
if ($leaves->save()) {
DB::commit();
Toastr::success('Leave Request Approve Successfully','Success');
return redirect()->back();
}else{
DB::rollback();
Toastr::error('Failed to Approve Request','Error');
return redirect()->back();
}