Reputation: 17380
In this sample code below how would I moderate errors such as Eloquent could not save or update fields or break SQL connection?
$user = new User;
$user->name = 'John';
$user->save();
Upvotes: 3
Views: 9252
Reputation: 8688
The save() method for eloquent returns a boolean on failure and a collection object on success, so you can display an error if the save() method returns false;
For example:
$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');
}
Here's the eloquent save function in detail:
http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_save
You may also want to look at model events:
http://laravel.com/docs/5.1/eloquent#events
EDIT: For your other question to catch a database connection error you can use a try/catch block such as:
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));
}
Upvotes: 5