0

I have to register a user in the database and when I click on the register button an error appears saying:

Trying to access array offset on value of type null (View: C:\laragon\www\digital-valley-psico\resources\views\guest\pages\register-student.blade.php)

A GET request is failing when I look at the browser's network tab

I'm using Laravel 5.4 and PHP 7.4

@section('content')
       
     <cadastrar-aluno :cursos="{{$cursos}}" 
                        :old='{"nome":"{{old("nome",$dadosPedido['nome'])}}",
                                "data_nascimento": "{{old("data_nascimento")}}",
                                "genero": "{{old("genero")}}",
                                "matricula": "{{old("matricula",$dadosPedido['matricula'])}}",
                                "id_pais": "{{old("id_pais")}}", 
                                "id_estado": "{{old("id_estado")}}",
                                "id_cidade": "{{old("id_cidade")}}",
                                "endereco": "{{old("endereco")}}", 
                                "bairro": "{{old("bairro")}}", 
                                "numero": "{{old("numero")}}", 
                                "email": "{{old("email")}}", 
                                "telefone_celular": "{{old("telefone_celular")}}", 
                                "telefone_residencial": "{{old("telefone_residencial")}}", 
                                "curso": "{{old("id_curso")}}", 
                                "semestre": "{{old("semestre_matricula")}}" }' 
                        :url="'{{$base_url}}'"/>
    
@endsection

error

Routes:

    $this->get('/pedidoCadastro','Site\AlunoController@mostrarformularioPedidoCadastro');
$this->post('/pedidoCadastro','Site\AlunoController@verificarPedidoCadastro')->name('verificarPedidoCadastro');
$this->get('/realizarCadastro','Site\AlunoController@mostrarFormularioCadastrarAluno');
$this->post('/realizarCadastro','Aluno\RegistrarAlunoController@registrarAluno')->name('registrarAluno');

Controller :

 public function mostrarFormularioCadastrarAluno(Request $request)
{

   
    if(!$request->session()->get('dadosPedido') && !$request->session()->get('_old_input'))
        return redirect('/pedidoCadastro')->withErrors(['credenciais' => 'Informe os dados abaixo para acessar o cadastro de aluno.'])->withInput();

    
    return view('guest.pages.cadastrar-aluno',['cursos' => Curso::all(), 'base_url' => env('APP_URL'), 'dadosPedido' => $request->session()->get('dadosPedido')]);   
}

public function mostrarformularioPedidoCadastro(Request $request)
{
    return view("guest.pages.register-initial");
}

public function verificarPedidoCadastro(Request $request)
{

    $validacao = Validator::make($request->input(), [
        'nome' => 'required',
        'matricula' => 'required'
    ]);

    if ($validacao->fails())
        return redirect()->back()->withErrors($validacao);

    if($this->verificarAluno($request->matricula))
        return redirect()->back()->withErrors(['credenciais' => 'A matrícula informada já pertence a outro usuário.']);

    $res = $this->buscarAlunoApi($request->matricula);
    $statusCode = $res->getStatusCode();
    switch($statusCode){
        case 200:
            $data = json_decode($res->getBody());
            if(count($data) > 0){
                $data = $data[0];
                if($data->matricula == $request->matricula && strtoupper($data->nome) == strtoupper($request->nome)){
                    return redirect('/realizarCadastro')->with(['dadosPedido' => ['nome' => $data->nome, 'matricula' => $data->matricula]]);
                }else{
                    return redirect()->back()->withErrors(['credenciais' => 'O nome do aluno informado é inválido'])->withInput();
                }   
            }else{
                return redirect()->back()->withErrors(['credenciais' => 'A matrícula não existe em nossa base de dados. Favor entrar em contato com o N2S.'])->withInput();
            } 
        break;
        default:
            return redirect()->back()->withErrors(['credenciais' => 'A matrícula não existe em nossa base de dados. Favor entrar em contato com o N2S.'])->withInput();
        break;
    }
}

Session.php

class Session extends Facade
{       
protected static function getFacadeAccessor()
    {
        return 'session';
    }
}
  • Firstly, include your code so we have a change to debug, controller and view. Secondly, i would print out the different values in the controller using dd($yourVar); to see if some of them are unexpectedly null. – mrhn Aug 02 '21 at 19:01
  • @mrhn I printed and they are not null – Alexandre Vila Nova Aug 02 '21 at 21:26
  • They clearly are somehow :) but it is hard to help you without the whole code so we can see the flow. – mrhn Aug 02 '21 at 21:51
  • @AlexandreVilaNova Look at the error trace, the first one is the error, the second one is a strange file (cached view), third one ignore it, fourth one shows you what you are sending to the view and you can see that `dadosPedido` is `null`... so, show us your controller please... Your issue is in the controller – matiaslauriti Aug 03 '21 at 04:56
  • @matiaslauriti I added the routes and controllers, I didn't write this code so the pattern is very bad. – Alexandre Vila Nova Aug 03 '21 at 15:57
  • @AlexandreVilaNova do you know where is the session set ? It is a real horrible code – matiaslauriti Aug 03 '21 at 16:12
  • @matiaslauriti I'm not sure how to tell you, I'm having my first contact with laravel, but I was looking in the code and saw in a config file that 'Session' => Illuminate\Support\Facades\Session::class, I added what's in the class. – Alexandre Vila Nova Aug 03 '21 at 16:58
  • @AlexandreVilaNova that is a definition, so you can use `Session` facade (like helper). Do a search for `session()->set(` or `session()->put(` and see if you find where is that set. – matiaslauriti Aug 03 '21 at 17:52
  • @matiaslauriti I didn't find anything in the code ;-; – Alexandre Vila Nova Aug 03 '21 at 18:54
  • @AlexandreVilaNova look for `dadosPedido` so we will find where it is setting the session, it should be something like `put` or `flash` or `push` or similar. This is the [documentation](https://laravel.com/docs/5.4/session#storing-data) about sessions. – matiaslauriti Aug 03 '21 at 18:58
  • 1
    @matiaslauriti Dude, you helped a lot. I fixed the problem, it was missing that you said. In the code there was nothing defining the session. So I went there and set it via the global "session" helper. (session(['key' => 'value']);) Thank you very much – Alexandre Vila Nova Aug 03 '21 at 21:54

0 Answers0