samedi 30 avril 2016

Is there a way to delegate a job to another action in Laravel?

Suppose we have two models: Users, and Posts. These models have many-to-many relationship defined between them - a user can have many posts, and post can have many editors(users).

When this form is submitted to PostsController, it's store action must handle not only the new post's fields, but also it's editors, which seems wrong. Example:

enter image description here

public function store()
{
    // creating a post
    $post = Post::create(request()->get('post_fields'));

    // adding editors to the post (this should be done somewhere else)
    $editors = request()->get('editors');
    foreach($editors as $editor){
        $post->editors()->attach($editor->id);
    }

    return redirect('/');
}

As I already mentioned, this approach seems wrong and clumsy to me. Because of this I want to delegate editors handling task to PostsEditorsController, which will be a separate controller dedicated only to posts-editors relationship management. So the store will now look something like this:

public function store()
{
    // creating a post
    $post = Post::create(request()->get('post_fields'));

    $editors = request()->get('editors');
    PostsEditorsController::doSomething($post, $editors); // <-- just to show what I want to achieve

    return redirect('/');
}

How can I do this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire