Laravel polymorphic relations: Passing model to controller

后端 未结 3 1108
自闭症患者
自闭症患者 2020-12-19 20:31

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 functi         


        
3条回答
  •  一生所求
    2020-12-19 20:57

    I implemented this way if you want, according to me it's the one of the bests way to do that.

    // 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
    }
    
    }
    

提交回复
热议问题