Home > Software engineering >  User_id in session table is all null
User_id in session table is all null

Time:01-18

I'm doing a session in laravel 9 but when I try to store user session. Other data can be store but the user_id column are all null. How to solve this? ( I use laravel for Backend so that I don't have any view in laravel.)

public function createUser(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return [
                "status" => "error",
                "error" => $errors
            ];
        } else {
            $user = new User();
            $user->name = $request->name;

            if ($user->save()) {
                Session::put('user', ['user_id' => $user->id, 'name' => $user->name]);
                Session::save();

                return
                    [
                        'status' => 'success',
                        'data' => $user,
                    ];
            } else {
                return [
                    'status' => 'error',
                    'data' => "Can't create a user",
                ];
            }
        }
    }

and the database after I push this session will be like this. User_id always be null. I want to push it in the same time with createUser function.

    {
        "id": 0,
        "user_id": null,
        "payload": "YToyOntzOjQ6InVzZXIiO2E6Mjp7czo3OiJ1c2VyX2lkIjtpOjE2O3M6NDoibmFtZSI7czo5OiJQZWFudXRlcnoiO31zOjY6Il9mbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX19",
        "last_activity": 1674040627
    }

CodePudding user response:

You're not saving the user! You're missing the $user->save(); line.

$user = new User();
$user->name = $request->name;
$user->save();

And also in your condition do it like:

if ($user->save())

Do the following instead:

if ($user){
    YOUR CONDITION HERE
  }

CodePudding user response:

Could I ask why you are storing the new created user in a session. i.e. what is the outcome of it.. where are you retrieving the session data?

As in the most part, you can just query the users table where needed in controllers, and you can get specific users or get latest submission etc..

  • Related