Laravel: Redirect to custom class?

I'm not sure if this is the β€œright” way of doing things, but the logic works. I have my own class in my Laravel setup, which I am usein the controller. In my controller, I call the function in my custom class, however I would like to redirect the user if something happens inside this function.

After talking to the IRC, they told me that you cannot redirect in your class, you need to "return the redirect response object from the controller."

Not quite sure what this means, but I think you need to do a redirect from the controller.

Code (simplified, it works):

Controller method:

    // Validate the incoming user
    $v = new SteamValidation( $steam64Id );

    // Check whether they're the first user
    $v->checkFirstTimeUser();

This goes into my SteamValidation class (app / Acme / Steam / SteamValidation.php and namespaced) and it checks:

public function checkFirstTimeUser() {

    // Is there any users?
    if( \User::count() == 0 ) {

        $user_data = [
           // Data
        ];

        // Create the new user
        $newUser = \User::create( $user_data );

        // Log that user in
        \Auth::login($newUser);

        // Redirect to specific page
        return \Redirect::route('settings');
    }

    return;
}

, 0, , . , , (return \Redirect::route('settings');), !

, :

  • ?
  • , ?
+4
1

, , , Redirect:: route() . , Laravel , - , , , . , , , , .

, , Redirect . validate (, , ), true/false, , :

// Validate the incoming user
$v = new SteamValidation( $steam64Id );

// Check whether they're the first user
if ($v->isFirstTimeUser()) { // note I renamed this method, see below
    return \Redirect::route('settings');
}

, , :

// SteamValidation
public function isFirstTimeUser() {
    return (\User::count() == 0);
}

// Controller

// Validate the incoming user
$v = new SteamValidation( $steam64Id );

// Check whether they're the first user
if ($v->isFirstTimeUser()) {
    // you may even wish to extract this user creation code out to something like a repository if you wanna go for it

    $user_data = [
       // Data
    ];

    // Create the new user
    $newUser = \User::create( $user_data );

    // Log that user in
    \Auth::login($newUser);

    // Redirect to specific page
    return \Redirect::route('settings');
}
+6

Source: https://habr.com/ru/post/1526730/


All Articles