Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to use a single controller to save my comments for multiple models. So I created the CommentController, with the following store method:

public function store(Teacher $teacher, Request $request)
    {    
        $input = $request->all();

        $comment = new Comment();

        $comment->user_id = Auth::user()->id;
        $comment->body = $input['body'];

        $teacher->comments()->save($comment);

        return redirect()->back();
    }

In my view, I have:

{!! Form::open([
    'route' => ['teachers.comments.store', $teacher->id]
]) !!}

This is working. If I want to use the same CommentController to store the comments for a school, how should I modify the store method of the controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
571 views
Welcome To Ask or Share your Answers For Others

1 Answer

Adam's solution is great, but I would not hard-code the model's namespace that way. Instead, what I would do is make use of Laravel's Relation::morphMap(), you can check it out here: https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations

That way, you will also make your database entries more readable. I recommend using a service provider to map the morphs.

Also, the Model base class has a getMorphClass() method, so instead of $comment->commentable_type = 'App\Models\'.$model; I would use $comment->commentable_type = $model->getMorphClass();

That way you integrate Laravel's logic into your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...