Returning to route after middleware triggered in Laravel

Viewed 202

I am working in Laravel 7 and have a middleware that checks if the user has a current user agreement, if not it redirects to a form that offers the current agreement. When the offer is accepted I need to redirect back to where they were originally going. I think I need to put something in the session so that when my controller stores their acceptance it can redirect back to the original route.

class VerifyAgreement
{
    public function handle($request, Closure $next, $agreement)
    {
        if(UserAgreement::outOfDate($agreement)){
           return redirect()->route('agreement.offer', $agreement);
        }
        return $next($request);
    }
}

I think I need to get the current request and pass it to the redirect so the User Agreement controller can capture it somehow and then redirect once the agreement is stored... I am not sure.

class AgreementController extends Controller
{
    public function offer(Agreement $agreement)
    {
        return view('agreement.offer',['agreement' => $agreement]);
    }

    public function agree(Request $request)
    {
        $agreement_uuid = App\Agreement::findOrFail($request->agreement)->uuid;
        UserAgreement::create(['user_uuid'=>auth()->user()->uuid, 'agreement_uuid'=>$agreement_uuid]);
        //redirect something something something
    }
}
1 Answers

As mentioned in the comments by @Ruben Danielyan, the Illuminate\Routing\Redirector has some methods that you may find useful

Redirector.php

/**
 * Create a new redirect response to the previously intended location.
 *
 * @param  string  $default
 * @param  int     $status
 * @param  array   $headers
 * @param  bool|null    $secure
 * @return \Illuminate\Http\RedirectResponse
 */
public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
    $path = $this->session->pull('url.intended', $default);

    return $this->to($path, $status, $headers, $secure);
}

/**
 * Set the intended url.
 *
 * @param  string  $url
 * @return void
 */
public function setIntendedUrl($url)
{
    $this->session->put('url.intended', $url);
}
Related