I'm creating a Vue SPA inside of a Laravel project, and I'm having issues with redirecting too many times while writing verified user email logic. My middleware is mostly in place for attaching authenticated user data to the request before rendering the requested component. That's all working fine, it's just this pseudo-logic that is giving me fits:
"If I have an authenticated user, check to see if the email is verified. If so, continue with the request with attached user data, if not, render the email verification component"
Here's the necessary logic to help diagnose:
Middleware:
class AuthForSPA {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($request->getRequestUri() !== '/vue/login') {
if ($request->user()) {
// This is the condition giving me redirect fits:
if ($request->user()->email_verified_at()) {
$this->share($request);
return $next($request);
}
return redirect('/vue/verify/email');
}
return redirect('/vue/login');
} else {
if ($request->user()) {
return redirect('/vue/dashboard');
}
return $next($request);
}
}
public function share($request)
{
$props = [
'auth' => [
'user' => $request->user() ? $request->user()->only('id', 'name', 'email') : null,
'roleName' => $request->user() ? $request->user()->roles->first()->name : null,
],
'roles' => Role::all(),
'flash' => [
'message' => $request->session()->get('message')
],
];
return $request->merge($props);
}
}
Route definition catching all SPA routes:
Route::get('/vue/{vue_capture?}', function() {
return view('vue.index');
})->where('vue_capture', '[\/\w\.-]*')->middleware('spa');
If y'all would like to see my Vue Router file, I'd be happy to share that as well. Any guidance here would be much appreciated, as this has become a big blocker for me, and I need to resolve this. Also, if there is a better way for me to structure this middleware, I'm all ears, as this is the first custom one I've written.