在下面的示例代码中,我将如何审核Eloquent无法保存或更新字段或断开SQL连接等错误?
$user = new User;
$user->name = 'John';
$user->save();
答案 0 :(得分:5)
eloquent的save()方法在失败时返回一个布尔值,并在成功时返回一个集合对象,因此如果save()方法返回false,则可以显示错误;
例如:
$user = new User;
$user->name = 'John';
if($user->save()){
return Redirect::to('users')->with('message', sprintf('User: "%s" successfully saved', $user->name));
} else{
return Redirect::to('users')->with('message', 'Failed to create user');
}
这里是详细的口才保存功能:
http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_save
您可能还想查看模型事件:
http://laravel.com/docs/5.1/eloquent#events
编辑: 对于捕获数据库连接错误的其他问题,可以使用try / catch块,例如:
try{
if (Auth::attempt(array('email' => $email, 'password' => $password))){
return Redirect::to('dashboard');
} else{
//Authentication failed
return Redirect::to('home')->with('message', 'Authentication failed, username/password inccorrect');
}
} catch(PDOException $e){
return Redirect::to('home')->with('message', sprintf('Failed to connect to database: %s', $e));
}