I am trying to create a user and extend the data to another table using foreign key.
For example. I have a user and the user has the basic fields name, email, password etc. I am trying to extend the data into another table called user_audience. I can create a users with the basic fields but cant data to save to the user_audience table with a check mark. If a a new user falls into an audience we want to checkmark it and save the value of 1 to the database under that user audience column. Just not sure how to handle data sent to another table Im sure I need some adjustments. Thanks in advance.
UserController
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required',
'username' => 'required',
'email' => 'required|email',
'company' => 'required',
'customer_number' => 'required',
'password' => 'required'
]);
$user = User::create(request(
[
'name',
'email',
'password',
'username',
'company',
'customer_number'
]));
return redirect()->route('admin.users.index')->with('success','User has been created successfully.');
}
UserModel
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentRelationsBelongsTo;
use IlluminateDatabaseEloquentRelationsBelongsToMany;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;
use SpatiePermissionTraitsHasRoles;
use AppModelsUserAudidence;
/**
* @property Role $role
*/
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'role_id',
'customer_id',
'name',
'username',
'company',
'email',
'password',
'affected_public',
'affected_public_mu',
'affected_public_row',
'affected_public_mfdu',
'damage_prevention_demo',
'damage_prevention',
'damage_prevention_residential',
'emergency_official',
'excavator',
'first_responder',
'first_responder_fire',
'first_responder_police',
'public_official',
'public_official_school',
'school',
'worker_ag',
'worker_contractor',
'worker_contractor_ag',
'worker_contractor_tree',
'worker_cranes',
'worker_crop_duster',
'worker_farm',
'worker_fence',
'worker_fiber',
'worker_landscaping',
'worker_overhead',
'worker_orchard',
'worker_roofers_overhead',
'worker_roofers',
'worker_tree',
'worker_tree_landscaping',
'worker_right_tree',
'worker_loggers',
'worker_tree_rental_equip',
'worker_at_risk',
'worker_cross_bore',
];
/**
* Add a mutator to ensure hashed passwords
*/
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// Relationship between User and UserAudience
public function UserAudidence(): BelongsTo
{
return $this->belongsTo(UserAudidence::class,);
}
UserAudience Model
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class UserAudience extends Model
{
protected $fillable = [
'affected_public',
'affected_public_mu',
'affected_public_row',
'affected_public_mfdu',
'damage_prevention_demo',
'damage_prevention',
'damage_prevention_residential',
'emergency_official',
'excavator',
'first_responder',
'first_responder_fire',
'first_responder_police',
'public_official',
'public_official_school',
'school',
'worker_ag',
'worker_contractor',
'worker_contractor_ag',
'worker_contractor_tree',
'worker_cranes',
'worker_crop_duster',
'worker_farm',
'worker_fence',
'worker_fiber',
'worker_landscaping',
'worker_overhead',
'worker_orchard',
'worker_roofers_overhead',
'worker_roofers',
'worker_tree',
'worker_tree_landscaping',
'worker_right_tree',
'worker_loggers',
'worker_tree_rental_equip',
'worker_at_risk',
'worker_cross_bore',
];
}
Bladefile
<form action="{{ route('admin.users.store') }}" method="POST" novalidate="novalidate" id="kt_create_account_form">
@csrf
<label class="required fs-6 fw-semibold mb-2">UserName</label>
<input type="text" class="form-control form-control-solid" placeholder="Username" name="username">
<label class="fs-6 fw-semibold mb-2">Email</label>
<input type="email" class="form-control form-control-solid" placeholder="Email Address" name="email">
<label class="required fs-6 fw-semibold mb-2">Password</label>
<input type="password" class="form-control form-control-solid" placeholder="Enter password" name="password">
<label class="form-label required">Company Name</label>
<input name="company_name" class="form-control form-control-lg form-control-solid" placeholder="Company Name" value="">
<label class="form-label required">Customer Number</label>
<input name="customer_number" class="form-control form-control-lg form-control-solid" placeholder="Customer Number" value="">
<label class="d-flex align-items-center form-label">Phone</label>
<input name="phone" class="form-control form-control-lg form-control-solid" value="Phone Number">
<label class="d-flex align-items-center form-label">Address</label>
<input name="address" class="form-control form-control-lg form-control-solid" placeholder="Street Address" value="">
<label class="d-flex align-items-center form-label">City</label>
<input name="city" class="form-control form-control-lg form-control-solid" placeholder="City" value="">
<label class="d-flex align-items-center form-label">State</label>
<input name="state" class="form-control form-control-lg form-control-solid" placeholder="State" value="">
<label class="d-flex align-items-center form-label">Zipcode</label>
<input name="zipcode" class="form-control form-control-lg form-control-solid" placeholder="Zipcode" value="">
<label class="d-flex align-items-center form-label mb-5">Select Audiences
<label class="d-flex flex-stack mb-5 cursor-pointer">Agricultural Worker</span>
<input class="form-check-input" type="checkbox" value="true" name="worker_contractor">
<button type="submit" class="btn btn-lg btn-primary me-3" data-kt-stepper-action="submit">Submit</button>
</form>
Create users migrations
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->unique();
$table->string('name');
$table->string('username')->unique();
$table->integer('customer_number');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('company');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zipcode');
$table->string('country');
$table->rememberToken();
$table->timestamps();
$table->unsignedBigInteger('audience_id')->nullable();
});
add user audience table migration
public function up()
{
Schema::create('users_audiences', function (Blueprint $table) {
$table->bigIncrements('id'); // by default the primary key is set to unsigned big integer
$table->unsignedBigInteger('user_id'); //associate the address with a user
$table->string('affected_public');
$table->string('affected_public_mu');
$table->string('affected_public_row');
$table->string('affected_public_mfdu');
$table->string('damage_prevention_demo');
$table->string('damage_prevention');
$table->string('damage_prevention_residential');
$table->string('emergency_official');
$table->string('excavator');
$table->string('first_responder');
$table->string('first_responder_fire');
$table->string('first_responder_police');
$table->string('public_official');
$table->string('public_official_school');
$table->string('school');
$table->string('worker_ag');
$table->string('worker_contractor');
$table->string('worker_contractor_ag');
$table->string('worker_contractor_tree');
$table->string('worker_cranes');
$table->string('worker_crop_duster');
$table->string('worker_farm');
$table->string('worker_fence');
$table->string('worker_fiber');
$table->string('worker_landscaping');
$table->string('worker_overhead');
$table->string('worker_orchard');
$table->string('worker_roofers_overhead');
$table->string('worker_roofers');
$table->string('worker_tree');
$table->string('worker_tree_landscaping');
$table->string('worker_right_tree');
$table->string('worker_loggers');
$table->string('worker_tree_rental_equip');
$table->string('worker_at_risk');
$table->string('worker_cross_bore');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
2
Answers
What I understand. You want to save data in users table then in users_audiences table.
As per naming conventions it is showing that it has one to many relationship. each user has many user_audiences.
And it you has foregin key constraint on users_audience. Therefore, you cannot add data to users_audiences untill you have coresponding record in users table.
For that you must create users record and save it to DB.
After that… create UserAudience object and save it…
After that use the above user object to save audience id to it
In this way you have already created user record in DB and it will not give constraint error
First you need to add
user_id
to thefillable
array onUserAudience
model and the same thing foraudience_id
onUser
model.then you need to create the user first, since
audience_id
is nullable:then you create the audience and fill the
user_id
with the previously created idthen updating the
$user
with the associatedaudience_id