Form submit intercepted by auth middleware in laravel 5

Viewed 710

I've been working on a laravel 5.7 blog project. I want to comment an article.

I need to achieve this:

  • Before logging in, I can type anything in comment textarea
  • I submit comment (of course it would be intercepted by auth middleware)
  • then I'm redirected to login page
  • After logging in, I hope my app could submit previous form data (or comment) automatically instead of typing the same comment again
  • I think that's a very common business logic in many websites nowadays, but how am I supposed to achieve this?

My comments controller here:

public function __construct()
{
    $this->middleware('auth');
}

public function store(Post $post) {
    $comment = Comment::create([
        'body' => session('comment')?:request('body'),
        'post_id'  => $post->id,
        'user_id' => auth()->user()->id 
    //before logging in, you don't have an user_id yet.
    ]);        
    return back()->with('success', 'Add comment succeeded');
}

web.php Route here:

Route::post('/posts/{post}/comments', 'CommentsController@store')->name('addComment');

Basically auth middleware intercepted my form data submit, I want to go across the auth middleware with my form data. Not lost them after logging in.

2 Answers

Here is the solution.A little tricky.Save comment to the session first before go to auth middleware.After logging in, GET that route to create comment. Route:

Route::get('/posts/{post}/comments', 'CommentsController@store')->name('addComment');
Route::post('/posts/{post}/comments', 'CommentsController@commentSave');

Comments controller:

public function __construct()
{
    $this->middleware('auth', ['except' => ['commentSave']]);
}
public function commentSave(Request $request){
    $url = \URL::previous();
    session(['comment' => $request->input('body')]);
    return redirect("$url/comments");
}  

public function store(Post $post){
    if(session('comment')){
        $comment = Comment::create([
            'body' => session('comment'),
            'post_id'  => $post->id,
            'user_id' => auth()->user()->id
        ]);
        session(['comment' => null]);
        return redirect("posts/$post->id")->with('success', 'Add comment succeeded');
    }
    return redirect("posts/$post->id");         
}
Related