Menu

Laravel Transaction – Post Create Example

Laravel Transaction – Post Create Example

Laravel Transaction – Post Create Example

User ek post create karta hai:

posts table me data insert

post_images me images insert

notifications me entry

Agar inme se koi ek bhi fail ho → to poora process rollback ho jaaye




use Illuminate\Support\Facades\DB;

public function store(Request $request)

{

    DB::beginTransaction();


    try {

        // 1️⃣ Post create

        $postId = DB::table('posts')->insertGetId([

            'user_id'    => auth()->id(),

            'title'      => $request->title,

            'description'=> $request->description,

            'created_at' => now(),

            'updated_at' => now(),

        ]);


        // 2️⃣ Post Images (agar images hain)

        if ($request->hasFile('images')) {

            foreach ($request->file('images') as $image) {

                $path = $image->store('post_images', 'public');


                DB::table('post_images')->insert([

                    'post_id'    => $postId,

                    'image_path' => $path,

                    'created_at' => now(),

                ]);

            }

        }


        // 3️⃣ Notification

        DB::table('notifications')->insert([

            'user_id'    => auth()->id(),

            'message'    => 'Your post has been created successfully.',

            'created_at' => now(),

        ]);


        DB::commit(); // 🎉 Sab successful → save


        return redirect()->back()->with('success', 'Post created successfully');


    } catch (\Exception $e) {

        DB::rollBack(); // ❌ Koi error aaya → sab cancel

        return redirect()->back()->with('error', 'Post create failed: ' . $e->getMessage());

    }

}



 Laravel Short Version (Clean Way)

DB::transaction(function () use ($request) {

    $post = Post::create([...]);

    foreach ($request->images as $image) {

        PostImage::create([...]);

    }

    Notification::create([...]);

});


Laravel khud commit / rollback kar dega 

Flow-chart laravel

Contact