Redirect after login Standard 5.5

Asked

Viewed 696 times

1

Good morning, I’m using Laravel’s standard authentication scafold, and repurposing the structure by overriding the methods I need for you to behave the way I want you to.

I customized the default model, I was able to authenticate and register, everything ok. However after registration, I wanted to redirect the user to a route of my, post registration. The Laravel provides me some for this as the protected function registered( $user ), however, everything I do within it seems to be ignored. On account of middleware RedirectIfAuthenticated (guest).

I’ve tried several other ways and a half that the structure of the Laravel provides me. I’ve tried changing the variables $redirectTo Registercontroller and Logincontroller, and create redirect methods in both.

Nothing seems to work. The controller in question is this:

/**
     * @Middleware("auth")
     * @Get("Painel", as="painel")
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function painel()
    {
        dump('chegou na home controller');
//      $usuario = auth()->user();
//      if ( $usuario->tipo == 'aluno' ) {
//          $aluno = AlunoModel::where('usuario_id',$usuario->id)->first();
//          return view('home.painel-aluno', compact( 'aluno') );
//      }
    }

I’m using the laravelcollective/Annotations package, but I don’t think it has any influence.

My user model:

<?php

namespace ContrateUmAluno\Models\Cadastros;

use ContrateUmAluno\Traits\Uuids;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class UsuarioModel extends Authenticatable
{
    use Notifiable, Uuids, SoftDeletes;

    protected $table = 'usuarios';
    public $incrementing = false;
    protected $fillable = [
        'nome', 'email', 'senha', 'tipo'
    ];
    protected $hidden = [
        'senha', 'remember_token',
    ];

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->senha;
    }
}

Registercontroller:

<?php

namespace ContrateUmAluno\Http\Controllers\Auth;

use ContrateUmAluno\Models\Cadastros\AlunoModel;
use ContrateUmAluno\Models\Cadastros\EmpresaModel;
use ContrateUmAluno\Models\Cadastros\UsuarioModel;
use ContrateUmAluno\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */
    use RegistersUsers;

    protected $redirectTo = 'painel';
    /**
     * Handle a registration request for the application.
     */
    public function redirectTo() {
        return route($this->redirectTo);
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create([
            'nome'          => $request['name'],
            'email'         => $request['email'],
            'senha'         => $request['password'],
            'tipo_usuario'  => $request['tipo_usuario'],
        ])));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'          => 'required|string|max:255',
            'email'         => 'required|string|email|max:255|unique:usuarios',
            'password'      => 'required|string|min:6|confirmed',
            'tipo_usuario'  => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return UsuarioModel
     */
    protected function create(array $data)
    {
        $usuario = UsuarioModel::create([
            'nome'  => $data['nome'],
            'email' => $data['email'],
            'tipo'  => $data['tipo_usuario'],
            'senha' => bcrypt($data['senha']),
        ]);

        $this->criar_tipo($data['tipo_usuario'], $data, $usuario);
        return $usuario;
    }

    /**
     * @param string       $tipo_usuario
     * @param array        $dados
     * @param UsuarioModel $usuario
     *
     * @return void
     */
    private function criar_tipo(string $tipo_usuario, array $dados, UsuarioModel $usuario)
    {
        $usuario_id = $usuario->id;
        if ( $tipo_usuario == 'aluno' ) {
            AlunoModel::create([ 'nome' => $dados['nome'], 'usuario_id' => $usuario_id ]);
        } else {
            EmpresaModel::create([ 'nome' => $dados['nome'], 'usuario_id' => $usuario_id ]);
        }
    }
}

After a few attempts to manually change all the written places /home (which I don’t think is right, since we have the inheritance so we don’t have to do this) I get him to throw the route /Painel, however the browser accuses incorrect redirect. Imagem do erro em questão

PS: in print is /login, but it is because I had removed the middleware to do some other tests.

I no longer know what to test and how to try. From what I already looked in the issues on github, already have Ports of this same pattern, however all the solutions that were given, does not work, I can play for the route in question, but accuses me of this error. And some cases of the issues, it was just a matter of reversing the use of the $redirectTo variable and the methods autenticated and registered.

From now on, thank you!

1 answer

1


If you are using routes by Annotation, check that the panel controller is using the "web" middleware, because without it Laravel does not start, nor does it read the user’s session on that route.

  • 1

    Really, that’s what it was. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.