php - Laravel Implicit Model Route Binding and Vue JS
Get the solution ↓↓↓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
Solution:
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 topost
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
});
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: method illuminate\database\eloquent\collection::paginate does not exist.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.