bentz
1 month ago
117
5
Laravel

Return View or Redirect From Private Method

Posted 1 month ago by bentz

Hi all - I ran into an issue today when I tried to consolidate duplicate code into a private method in my controller. Every method in my controller must check the passed in $user object against the current authenticated user. If they are a match, redirect the request to an error page:

public function show(User $user)
{
        if (($user->id === Auth::user()->id))
        {
            $flash = flash("danger", "You cannot administer your own account. Showing user page instead.");
            return view('user.show')->with($flash);
        }

        return view('admin.users.edit')->with('user', $user);
}

(The "flash" helper above just returns an associative array to help with flashing data to the session)

Obviously, repeating this logic in all six methods is not a good idea. My thought was to move it into a dedicated private method that the other methods could call:

public function show(User $user)
{
    $this->activeUserCheck($user);
    return view('admin.users.edit')->with('user', $user);
}

private function activeUserCheck($user)
{
        if (($user->id === Auth::user()->id))
        {
            $flash = flash("danger", "You cannot administer your own account. Showing user page instead.");
            return view('user.show')->with($flash);
        }
}

The problem is when I try to return the view within activeUserCheck() it doesn't work. The flashed session data is still set... but the view returned is from the show() method.

Is there a way to force the return of the view from within activeUserCheck(), or am I missing a better approach?

Thanks!

Please sign in or create an account to participate in this conversation.