Home » Php » Error "Trying to access array offset on value of type null" laravel 5.8.26 Php 7.4.2

Error "Trying to access array offset on value of type null" laravel 5.8.26 Php 7.4.2

Posted by: admin February 25, 2020 Leave a comment

Questions:

I use below function for insert/create new user from admin panel:

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|same:confirm-password'
    ]);


    $input = $request->all();
    $input['password'] = Hash::make($input['password']);


    User::create($input);

    return redirect()->route('admin.pages.users.index')
        ->with('success','User created successfully');
}

when I submit I get error as below :-

Trying to access array offset on value of type null

EDIT:
I found my problem. my problem is email validation rule. when i remove email validation insert data is true.

enter image description here

How do can i fix this error !

How to&Answers:

Try this:

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email|unique:users,email',
        'password' => 'required'
    ]);

    $user = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = Hash::make($request->password);
    $user->save();

    return redirect()->route('admin.pages.users.index')
    ->with('success','User created successfully');
}

Answer:

Try this Hope it will help You

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|same:confirm-password'
    ]);


    $insert_array = [
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password)
            ];

    User::create($insert_array );

    return redirect()->route('admin.pages.users.index')
        ->with('success','User created successfully');
}