2016-11-16 21:48
浏览 196


Looking for best practices, given these 3 tables:

Task (id, title, description) User (id, name) User_task (user_id, task_id)

My class/Object User has a function addToCompletedTasks(Task task) to add a task to his list of completed task (that adds the task into the table User_task).

I'm looking for best practice to send my completed task FROM my view TO my controller. Right now I'm sending an ID but I'm wondering if it's possible to send the object so I don't have to instantiate the task in my controller to add it to the completedtasks list.

public function insertCompletedTask(Request $request)
        $task_id = $request->input('task_id');

        $user = \Auth::user();

        $task   = Task::whereId($task_id)->first();
        $update = $user->assignCompletedTask($task);

图片转代码服务由CSDN问答提供 功能建议


任务(id ,标题,描述) 用户(id,name) User_task(user_id,task_id)

我的类/对象用户有一个函数addToCompletedTasks(任务任务)将任务添加到他的列表中 已完成的任务(将任务添加到表User_task中)。

我正在寻找最佳实践,将完成的任务从我的视图发送到我的控制器。 现在我是 发送ID,但我想知道是否可以发送对象,所以我不必在控制器中实例化任务,将其添加到completedtasks列表中。

   public function insertCompletedTask(Request $ request)
 $ task_id = $ request-> input('task_id'); 
 $ user = \ Auth :: user(); 
 $ task =  Task :: whereId($ task_id) - > first(); 
 $ update = $ user-> assignCompletedTask($ task); 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • doudeng1870 2016-11-16 21:56

    You have to send the ID via a route

    Route::get('/your-url/{id}', 'YourController@addCompletedTasks');

    Then you need to have this function declared in your User model:

    public function tasks(){
        return $this->belongsToMany('Task');

    And then in your controller have this function:

    public function addCompletedTasks($id) {
         // if you want to you can also just do 

    If you want to send it via POST in the request and not via the ID in the URL your function would need to be like that:

    public function addCompletedTasks(Request $request) {

    In either case you can't send a full php object or you will have to serialize it and deserialize it, easier to just send the ID.

    But in my opinion you should check first if a task is related to the id first. But if you have this control on the database level it's ok.

    解决 无用
    打赏 举报

相关推荐 更多相似问题