Bipin Regmi
Bipin Regmi

Reputation: 137

How to queue the logics in controller

I have used two logic in my controller in my laravel project

public function multiStore()
{
 $user = User::create([
      'name'=>$request->name,
      'email'=>$request->email,
      'password'=>Hash::make($request->name),
 ]);
 $post = MyPost::create([
     'name'=>$request->post_name,
     'body'=>$request->post_body,
 ]);
 return redirect()->to('/admin/home);
}

Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship

I have tried something like if condition but it is not working

Upvotes: 1

Views: 86

Answers (2)

gjhuerte
gjhuerte

Reputation: 66

Enclose your query in database transaction

https://laravel.com/docs/5.8/database#database-transactions

Either you can:

DB::transaction(function() {
     Model::create();
     AnotherModel::create();
});

Or you can use the following to find and catch error...

DB::beginTransaction();

// Your queries here...
// Model::create();
// AnotherModel::create();

DB::commit();

Upvotes: 1

Mohammed Omer
Mohammed Omer

Reputation: 1236

You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.

Note : make sure you listed all the table fields in protected $fillable in your model before using Create()

public function multiStore()
    {
     $user = User::create([
          'name'=>$request->name,
          'email'=>$request->email,
          'password'=>Hash::make($request->name),
     ]);

    if($user){
     $post = MyPost::create([
         'user_id' => $user->id
         'name'=>$request->post_name,
         'body'=>$request->post_body,
     ]);
    }
     return redirect()->to('/admin/home);
    }

Upvotes: 1

Related Questions