Search code examples
phpmysqllaravelexceptionforeign-keys

Laravel add the ID of current user into the table when he adds a new entry


yeah so I have a user table with user id and another table of shelters, users will add shelters to the table and I want to show the user id of the person that adds that particular shelter to the table i am using $table->foreignId('id')->references('id')->on('users'); that gives me SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value

Shelter Table

 public function up()
    {
        Schema::create('animal_shelters', function (Blueprint $table) {
            $table->id('shelter_id');
            $table->timestamps();
            $table->foreignId('id')->references('id')->on('users');
            $table->string('shelter_name');
            $table->string('shelter_address');
            $table->string('shelter_mobile_number');
            $table->string('shelter_type');
        });
    }
 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->string('profile_photo_path', 2048)->nullable();
            $table->timestamps();
        });
    }

Error :

Illuminate \ Database \ QueryException

SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value

inserting into database

public function store(Request $request)
    {
$Animal_shelter = new Animalshelter();
$Animal_shelter->shelter_name = $request->input('shelter_name');
 $Animal_shelter->shelter_address = $request->input('shelter_address');
 $Animal_shelter->shelter_mobile_number = $request->input('shelter_mobile_number');
 $Animal_shelter->shelter_type = $request->input('shelter_type');
  $Animal_shelter->save();
  return redirect()->back()->with('status', 'shelter added successfully');
    }

Solution

  • It's just because you not set the user_id field. simply add it to your object before save() will fix the problem

    $Animal_shelter->user_id = auth()->id() // In case you need to get authenticated user id
    

    Or just change your shelter migration file so the column accept null value

    $table->foreignId('user_id')->nullable()->constrained();
    

    Or last solution, if you set up relationship between User and Shelter on eloquent level, you can chain function, something like this

    auth()->user()->shelters()->create(['your data']);
    

    Second solution Third solution