简体   繁体   中英

Laravel - Several related models saving

Laravel 5.4.*

I have the following controllers and functions:

AuthorController

class AuthorController extends Controller {
    public function store(StoreAuthor $request) {
        Author::create($request->all());
        return response()->json(["message" => "done"]);
    }
}

BookController

class BookController extends Controller {
    public function store(StoreBook $request) {
        Book::create($request->all());
        return response()->json(["message" => "done"]);
    }
}

CategoryController

class CategoryController extends Controller {
    public function store(StoreCategory $request) {
        Category::create($request->all());
        return response()->json(["message" => "done"]);
    }
}

And more like these.

I handle validation and security through the FormRequest, and this is clean and elegant.

What I'm trying to achieve has been asked before, but I haven't really found a solution that worked for me.

I want to send one form and save many models which are related. I imagine i'd send a json object which contains data for all the models like this: {author:author, book:book, category:category, ....}

Should I create a different controller which handles the logic of multiple models? If so how do I avoid repeating the logic within the original controllers?

Should i create a Trait for every controller that can be saved for other controllers (ie: AuthorTrait )? If so how can i keep the formRequest validation and policies logic?

I have seen the laravel methods associate and attach , but they seem to work only if the record has been already created.

The first thing that comes to my mind is chaining different controllers methods, but that seems really unclean to me.

Thank You.

It sounds to me like you want to create a service that handles these. I would say in general your feeling that chaining different controller methods is definitely not the way to handle this. You basically need a service that examines the request data and saves them appropriately.

In your controller:

class AuthorController extends Controller {
    public function store(StoreAuthor $request, CustomService $service) {
        return $service->execute($request);
    }
}

This service would handle the logic of parsing and validating the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM