0
votes

PHP Version:7.2
Laravel Version:6.2

I am doing a simple project by laravel by article.
When I meet with redirect()->action, I am a little confused about that. I want to pass a variable named id by redirect()->action but it does't work.

Error Message is Missing required parameters for [Route: blog/post.show] [URI: blog/post/{post}].

If I remove the variable name, only pass the variable value and it would work. I read the manual but still could not understand the reason. Could you help me explain the logic. Thank you. Below is the sample code.

Router.php

Route::group(['prefix' => 'blog',
              'as' => 'blog/',
              'namespace' => 'Blog'],
              function(){
                    Route::resource('/post',"PostController");
              });



PostController.php

Create new blog post ( wrong )
Couldn't understant why this does't work ? Variable name($id) is the same.

    public function store(Request $request)
    {
        $post = new BlogPost;
        $post->title = $title;
        $post->content = $content;
        $post->save();

        return redirect()->action(
            'Blog\PostController@show', ['id' => $post->id]
        );
    }

Create new blog post ( correct )

    public function store(Request $request)
    {
        $post = new BlogPost;
        $post->title = $title;
        $post->content = $content;
        $post->save();

        return redirect()->action(
            'Blog\PostController@show', [$post->id]
        );
        //Or 'Blog\PostController@show', $post->id
    }

Show the new blog post

    public function show($id)
    {
        $post = BlogPost::find($id);
        if(! $post) {
            abort(404);
        }
        $content = $post->content;

        return view("blog.post", [
            "title" => $post->title,
            "content" => $content,
        ]);
    }

Thank you

2

2 Answers

0
votes

Here is code :

return redirect()->route('routename', ['id' => 1]);
0
votes

You got the error message because you are using the Resource Route and it will automatic bind the Model with Route

For More Info please refer: https://laravel.com/docs/6.x/routing#route-model-binding