Php Laravel多态关系:将模型传递给控制器

Php Laravel多态关系:将模型传递给控制器,php,laravel,laravel-5,polymorphism,Php,Laravel,Laravel 5,Polymorphism,我想使用一个控制器来保存多个模型的注释。因此,我使用以下存储方法创建了CommentController: public function store(Teacher $teacher, Request $request) { $input = $request->all(); $comment = new Comment(); $comment->user_id = Auth::user()->id;

我想使用一个控制器来保存多个模型的注释。因此,我使用以下存储方法创建了CommentController:

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来存储学校的评论,我应该如何修改控制器的存储方法

我不确定这是否是拉拉维尔公约,但我已经做了以下工作:

制定路线:

Route::post('/Comment/{model}/{id}', [
    // etc
]);
然后在控制器中获取模型并对照一组允许的模型进行检查,将id传递并附加:

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();
}

就像我说的,很可能有更好的方法来完成,但我就是这样做的。它保持它的简短和甜美,并检查模型是否可以接受注释。

Adam的解决方案很好,但我不会以这种方式硬编码模型的名称空间。相反,我要做的是利用Laravel的
关系::morpmap()
,您可以在这里查看它:

这样,还可以使数据库条目更具可读性。我建议使用服务提供商来映射变形

另外,
Model
基类有一个
getMorphClass()
方法,因此

$comment->commentable_type='App\\Models\\\'。$model;
我会用

$comment->commentable_type=$model->getMorphClass();


这样,您就可以将Laravel的逻辑集成到您的代码中。

如果您愿意,我可以用这种方式实现,据我说,这是最好的方法之一

// Route::post('/comments/{model}/{id}', 'CommentController@store');
class CommentController extends Controller {

protected $model;

public function __construct()
{
    $this->model = Relation::getMorphedModel(
        request()->route()->parameter('model')
    );
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    dd($this->model); // return 'App\Post' or null
}

}

感谢您提供的解决方案!我不得不更改
“App\\Models\\”$模型
'App\\\'$模型啊,是的,对不起,我通常把我所有的模型都放在模型目录中。很高兴它对你有用:)我这辈子见过的最丑的东西。。。这是公认的答案吗D什么模型是
关系
?你的意思是
评论
?关系模型是
illumb\Database\elount\Relations\Relations