adamnet's avatar

Create tables transaction corresponding through a field

I have 4 tables posts, postas, postbs and postcs with the corresponding models Post, Posta, Postb and Postc. They will be related through the groupid field. So in the store method of the controller I have:

0 likes
5 replies
Glukinho's avatar
  1. implement validation with Form Request: https://laravel.com/docs/12.x/validation#form-request-validation

  2. when creating a model no need to pick fields from request one by one, you can create a model with just one command:

$post = Post::create($request->safe()->only('field1', 'field2')); // assumed you already have validation via form request

$post = Post::create($request->only('field1', 'field2')); // if you leave Request unvalidated

// for subsequent posts depending on first created
$posta = Posta::create([
    ...$request->only('fielda1', 'fielda2'),
    'groupid' => $post->id,
]);

// or using relation:
$posta = new Posta($request->only('fielda1', 'fielda2')):
$posta->group()->associate($post);
$posta->save();

https://laravel.com/docs/12.x/requests#retrieving-a-portion-of-the-input-data

Of course, it is applicable only if field names in a request and a model match.

  1. no need to DB::rollback() in catch block, a transaction is rolled back automatically if any exception was thrown inside. But you may leave it for clarity.
1 like
adamnet's avatar

Thank you very much. The associate example helped me a lot! One last question: My project is written in Laravel 11. Is your example applicable in Laravel 11? Also another question which has to do with the validated data in case I use a Request: If in the store method, I want to save an extra value in a field what should I do?

Glukinho's avatar

Yes, I think Laravel 11 is the same. However I recommend to upgrade to 12 and stick to latest. The longer you stay on outdated version the harder it is to upgrade to actual one.

Can you give an example for your last question?

adamnet's avatar
        $pagamData['user_id'] = $request->user()->id;
        $pagamData['etoscreated'] = Carbon::now()->year;
        $pagamData['unit_id'] = Helper::getCurrentPolitisEnoriaId();
        $pagamData['apodektis'] = "Ιερός Ναός";
        $pagamData['polit_id'] = auth()->user()->polit->id;

        $pagam = Pagam::create($pagamData);```

I found the answer myself. I have to include in the $pagamData validated array the fields user_id, etoscreated etc 
By the way talking about upgrading from Laravel 11 to 12 which is the practically easiest way to upgrade my project to 12?
Glukinho's avatar

There is an upgrade guide: https://laravel.com/docs/12.x/upgrade

Just follow it step by step on local version (not touching production!). If you face some incompatibilities (PHP version, packages versions etc) you should resolve them and repeat again. Just don't touch production until you have success with local upgrade.

Please or to participate in this conversation.