Laravel多态关系:将模型传递给控制器 [英] Laravel polymorphic relations: Passing model to controller
问题描述
我想使用一个控制器来保存我对多个模型的注释.因此,我使用以下存储方法创建了CommentController:
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();
}
我认为,我有:
{!! Form::open([
'route' => ['teachers.comments.store', $teacher->id]
]) !!}
这正在工作.如果我想使用相同的CommentController来存储学校的评论,应该如何修改控制器的存储方法?
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?
推荐答案
我不确定这是否是Laravel召集,但我已经执行了以下操作:
Im not sure if this is the Laravel convension, but i have done the following:
制定路线:
Route::post('/Comment/{model}/{id}', [
// etc
]);
然后在控制器中获取模型,并对照允许的模型数组进行检查,将id传递并附加:
Then in the controller get the model and check against an array of allowed models, pass the id through and attach:
public function store(Request $request, $model, $id) {
$allowed = ['']; // list all models here
if(!in_array($model, $allowed) {
// return redirect back with error
}
$comment = new Comment();
$comment->user_id = $request->user()->id;
$comment->commentable_type = 'App\\Models\\'.$model;
$comment->commentable_id = $id;
$comment->body = $request->body;
$comment->save();
return redirect()->back();
}
就像我说的那样,最有可能实现更好的方法,但这就是我做到的方式.它使代码简短有趣,并检查模型是否可以发表评论.
Like I say, there is most likely a much better way to accomplish, but this is how I've done it. It keeps it short and sweet and checks if the model can take a comment.
这篇关于Laravel多态关系:将模型传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!