Search code examples
phpvalidationconditional-statementscodeigniter-4

How to solve Trying to access array offset on value of type null in Codeigniter 4


I want to make validation for the login activity in Codeigniter 4, the login function is running properly, but there is a problem with the validation. When I try to enter a username that doesn't exist, an error will appear and.says "Trying to access array offset on value of type null"

Here's my full code:

public function index()
{
    $M_admin = new \App\Models\M_admin();
    $login = $this->request->getPost('login');


    if ($login) {
        $member_username = $this->request->getPost('member_username');
        $member_password = $this->request->getPost('member_password');

        if ($member_username ==  '' or $member_password == '') {
            $err = "Please insert username and password";
        }

        if(empty($err)) {
            $dataMember = $M_admin->where("unm",
            $member_username)->first();
            
            if ($dataMember['unm'] != $member_username
            ){
                $err="Username does not exist";
            }else 
            if ($dataMember['u_p'] != $member_password
            ){
                $err="Incorrect password";
            }
        }
        
        if(empty($err)){
            $dataSesi = [
                'member_id' => $dataMember['id'],
                'member_username' => $dataMember['unm'],
                'member_password' => $dataMember['u_p'],
                ];
                session()->set($dataSesi);
                return redirect()->to('dashboard');
        }

        if ($err) {
            session()->setFlashdata('member_username', $member_username);
            session()->setFlashdata('error', $err);
            return redirect()->to("login");
        }
    }

    return view('v_login');
}

and the cause of error are here:

 if ($dataMember['unm'] != $member_username
            ){
                $err="Username does not exist";
            }

Is there something wrong with my code? a helpful answer will mean a lot, thanks...


Solution

  • Since you don't have a " firstOrFail " function, you should add a try catch around your code at

    $dataMember = $M_admin->where("unm",
                $member_username)->first(); 
    

    You probably don't want to do the full check process if an user doesn't exist, you can also add a simple " if(!empty($dataMember))" but adding too much logic in your controller is probably not the best way, at least you should create a private function who do the full checking logic and return " true " or " err = "your_error_message"

    I hope my answer can help you. :)