我想建議如何處理,哪種方法最好。 隱式綁定或正常綁定方法。Laravel Implict Binding獲取關於型號的查詢結果
我正在使用Laravel路由隱式綁定。當我發佈錯誤的ID,我得到錯誤沒有查詢結果模型如何處理控制器不是異常處理程序。現在我完成異常處理程序,但需要更好的解決方案來處理這個問題或避免隱式綁定。
//Web.php
Route::delete('/master/user/department/{department}/delete', ['as' => 'master.user.department.destroy', 'middleware' => 'permission:master.user.department.destroy', 'uses' => 'Master\User\[email protected]']);
//DepartmentContrller.php
public function destroy(Department $department)
{
try {
$department->delete();
return redirect(route('master.user.department.index'))->with('success', array(' Department Deleted successfully'));
} catch (Exception $e) {
return back()->with('criticalError', array($e->getMessage()));
}
}
//Handler.php
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException)
{
return redirect()->back()->with('custom_modal', ['Model Not Found Exception', $exception->getMessage()]);
}
下面的代碼是完全正常工作,我想知道哪種方法是最好的。 //DepartmentContrller.php
public function destroy($id)
{
try {
$department=Department::find($id);
if($department){
$department->delete();
return redirect(route('master.user.department.index'))->with('success', array(' Department Deleted successfully'));
}
else{
return back()->with('criticalError', array('Department is not found.'));
}
} catch (Exception $e) {
return back()->with('criticalError', array($e->getMessage()));
}
}
當未找到記錄時,Laravel find()將返回NULL。您可以使用is_null()來檢查find方法的響應。 –