【问题标题】:Laravel Implicit Model Route Binding and Vue JSLaravel 隐式模型路由绑定和 Vue JS
【发布时间】:2017-01-12 00:41:19
【问题描述】:

我想知道是否有一种方法可以在 vuejs 和 laravel 中自动绑定模型和路由,就像使用 laravel 一样。我的意思是,假设我想用给定的 id 更新某个帖子,在 laravel 中我会这样做:

  public function edit(Request $request Post $post)
  {   

      $post->update($request->all());
    // then  I will return some view or do some redirect here

   }

请注意,我不必指定帖子 ID,因为 laravel 会在后台自动执行此操作。

根据我到目前为止所学到的,使用相同的函数和来自 vuejs 的一些帖子数据,我首先通过执行以下操作获取 id:

  public function edit(Request $request)
  {

   $post = $request->input('id');
   $post =  Post::where('id', $id)->first();
  // Then I perform other logic  here
  // then  I will return some view or do some redirect here

  }

请注意,该函数不再接受任何后期模型。如果我尝试通过添加模型作为输入参数并在 vuejs 中调用某些编辑函数确实到达了我在某些控制器中进行编辑的路由,我会收到内部服务器错误 500。 我使用的代码是这样的:

  public function edit(Request $request Post $post)
  {


  // Then I perform other logic  here
  // then  I will return some view or do some redirect here

  }


  //vuejs method
  editPost(post){
  var postData = {id: this.post.id};
  this.$http.post('edit/'+ postData).then((response)=>
  {
     //Some logic goes here including catch part

  });
 }

【问题讨论】:

    标签: php laravel-5.2 vue.js


    【解决方案1】:

    您可以将帖子 id 作为路由参数传递:

    Route::get('posts/{post}/edit', 'PostController@edit');
    

    所以它会自动将模型实例注入post参数。

    public function edit(Request $request, Post $post)
    {
        $post->update($request->all());
    }
    

    然后在你的 vue 中你可以这样做:

    editPost(post) {
        let postId = post.id;
        let postData = {
            title: '',
            content: ''
        };
    
        this.$http.post('posts/' + postId + '/edit', postData).then((response) => {
            //Some logic goes here including catch part
        });
    }
    

    【讨论】:

    • 这行得通。我还有一个问题,我正在使用授权方法来检查只有帖子的所有者才能删除帖子,但我得到了 403
    • 当您收到 403 时,这意味着您无权这样做。您必须确保登录用户是帖子所有者。
    猜你喜欢
    • 2019-01-10
    • 2017-12-16
    • 2019-02-27
    • 2016-06-10
    • 2021-05-24
    • 2023-03-20
    • 1970-01-01
    • 2020-09-22
    • 2016-06-04
    相关资源
    最近更新 更多