skip to Main Content

Im trying to get the id of the logged in user. When the user is clicking on the button his id need to get send to the data base, But I get an error: 1048 Column ‘user_id’ cannot be null.

This is my controller function:

    public function LendBook(Request $request)
    {
        $user_id = $request->session()->get('User_id');
        $book_id = $request->book_id;


        $q = new lend;
        $q->user_id = $user_id;
        $q->book_id = $book_id;

        $q->save();

        return 'test';
}
}

2

Answers


  1. here with this you get current user’s id

    use IlluminateSupportFacadesAuth;
    
        $user = Auth::user();
        $user_id = $user->id;
    
    Login or Signup to reply.
  2. public function LendBook(Request $request)
    {
        $user_id = auth()->user()->id;
        $book_id = $request->book_id;
    
        $q = new Lend; // naming class should be Upper case "Lend"
        $q->user_id = $user_id;
        $q->book_id = $book_id;
        $q->save();
    
        return 'test';
    }
    

    Shorthand getting user id from current login user auth()->user()->id;

    Adding Tips:
    naming class should be Uppercase look the basic php standard (PSR) enter link description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search