Mover Mover - 3 months ago 26
PHP Question

Laravel Implicit Model Route Binding and Vue JS

I want to know if there is a way to automatically bind models and routes in vuejs and laravel just as one will do with just laravel. What I mean is, assuming, I want to update a certain post with a given id, In laravel I will do just this:

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

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

}


Notice that I did not have to specify the post id because laravel automatically does that behind the scenes.

According what I have learned so far, using the same function with some post data from vuejs, I have first get the id by doing the following:

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

}


Notice the function doesn't accept any post model anymore. If I try by adding the Model as input parameter and calling on some edit function in vuejs do reach a route where I hit the edit in some controller, I get an internal server error 500.
Code I used is like so:

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

});
}

Answer

You can pass the post id as a route parameter:

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

So it will automatically inject the model instance to post parameter.

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

Then in your vue you can do like this:

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