PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

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)

loading comments