Sorry, this video is only available to Pro accounts.

Upgrade your account to get access to all content.

Database Transactions in Laravel

Created on August 24th, 2017

Using Database Transactions in Laravel we can easily rollback any changes in case a database error occurs or a syntax error occurs during the transaction. In this video we will show you an example of creating a user profile along with creating a user. If the user profile does not get created successfully the user will not be created as well.

Here is the code that was used in the video above:

use Illuminate\Support\Facades\DB;

Route::get('new_user', function(){

	try{

		DB::beginTransaction();

		$user = App\User::create([
			'name' => 'Mike Smith',
			'email' => '[email protected]',
			'password' => \Hash::make('password')
		]);

		$profile = new App\Profile;

		$profile->user_id = $user->id;
		$profile->about = 'A little about Mike Smith';
		//$profile->avatar = 'default.jpg';

		$profile->save();

		DB::commit();

		echo 'User and Profile Saved';
	} catch(\Exception $e){
		DB::rollback();

		echo $e->getMessage();
	}	

});

You can find out more about database transactions by checking out the official documentation on transactions at: https://laravel.com/docs/5.4/database#database-transactions.

Comments (0)