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

Time:06-14

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');
    }

CodePudding user response:

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

CodePudding user response:

No, it won't add it automatically. When you add to the shelter table you must set the foreignid to the user id of the user that is creating it.

  • Related