0

I have a page for creating a driver and adding his cars - drivers/create. A driver must have at least one car. So I keep all the logic of storing the driver info in DriverController@store, but I also need to save cars info. I feel it is not a correct way to store elements of a Car class in the DriverController.

What would be a correct (or just a better) way in my case?

Zlautumn
  • 89
  • 1
  • 11

2 Answers2

0

You can create a public static store method in CarController, and then invoke the method in DriverController@store. Or create a car in CarModule and invoke it in DriverController@store.

Gavin Kwok
  • 98
  • 6
0

If you're using Eloquent ORM, Laracasts has a free video series on v5.4 from scratch.

Two of the videos show you one way to set up a one-to-many relationship, but using a blog with comments. You could follow their example but substitute blog with driver, and comments with cars.

Laravel 5.4 From Scratch: Eloquent Relationships and Comments

https://laracasts.com/series/laravel-from-scratch-2017/episodes/15

Laravel 5.4 From Scratch: Add Comments

https://laracasts.com/series/laravel-from-scratch-2017/episodes/16

There's also a lot of other ways to approach the problem, with the Repositories or Service Layers, but those can lead you down a rabbit hole.

ourmandave
  • 1,505
  • 2
  • 15
  • 49
  • That's what I started with. And I also tried to follow that example, but I found it quite different from what I have. There a post is created, then comments are added and there everything is clear, no problems with it. But in my case the driver and the cars are created at the same time, and I have to validate some driver's data, the fact that he has at least one car and some car data. So this is what I am struggling with – Zlautumn Sep 03 '18 at 04:22
  • I've come across Service Layer, and so far I feel like it is what I need. So an example on using services applicable to my case would be extremely appreciated – Zlautumn Sep 03 '18 at 04:24
  • [Here's a long answer about the various strategies](https://stackoverflow.com/a/25298736/3585500) and it links to an [article on setting up all of them](https://dfg.gd/blog/decoupling-your-code-in-laravel-using-repositiories-and-services), including a service (half way down the article). It's from 2014 though. – ourmandave Sep 03 '18 at 04:29