doumindang2416 2016-11-16 21:48
浏览 201
已采纳

Laravel将对象从视图传递到控制器

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);
}
  • 写回答

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 
         Auth::user()->tasks()->attach($id);
    }
    

    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) {
      Auth::user()->tasks()->attach($request->get('id'));
    }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算