laravel-blog-tutorial icon indicating copy to clipboard operation
laravel-blog-tutorial copied to clipboard

Edit the validate method in update post

Open Ahmad-Fathy opened this issue 7 years ago • 0 comments

We can edit the validate method in PostController to ignore a given ID during the unique check for slug (instead using if)

    public function update(Request $request, $id)
    {
        // Validate the data
        $post = Post::find($id);
        $this->validate($request, array(
            'title' => 'required|max:255',
            'slug' => [
                'required',
                'alpha_dash',
                'min:5',
                'max:255',
                Rule::unique('posts')->ignore($post->id)
            ],
            'body' => 'required|min:5',
        ));
        

        // Save the data to the database

        $post->title = $request->input('title');
        $post->slug = $request->input('slug');
        $post->body = $request->input('body');
        $post->save();
        // Set flash data with success message
        Session::flash('Success', 'This post was successfully updated.');
        // redirect with flash data to posts.show
        return redirect()->route('posts.show', $post->id);
    }

Ahmad-Fathy avatar Oct 16 '18 19:10 Ahmad-Fathy