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 App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use App\Models\UserAudidence;
/**
* @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 App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
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 >UserName</label>
<input type="text" placeholder="Username" name="username">
<label >Email</label>
<input type="email" placeholder="Email Address" name="email">
<label >Password</label>
<input type="password" placeholder="Enter password" name="password">
<label >Company Name</label>
<input name="company_name" placeholder="Company Name" value="">
<label >Customer Number</label>
<input name="customer_number" placeholder="Customer Number" value="">
<label >Phone</label>
<input name="phone" value="Phone Number">
<label >Address</label>
<input name="address" placeholder="Street Address" value="">
<label >City</label>
<input name="city" placeholder="City" value="">
<label >State</label>
<input name="state" placeholder="State" value="">
<label >Zipcode</label>
<input name="zipcode" placeholder="Zipcode" value="">
<label >Select Audiences
<label >Agricultural Worker</span>
<input type="checkbox" value="true" name="worker_contractor">
<button type="submit" 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');
});
}
CodePudding user response:
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.
$user = new User();
$user->name = $request->input('name');
$user->name = $request->input('email');
//and soo on...
//then save it...
$user->save();
After that... create UserAudience object and save it...
$userAudience = new UserAudience();
$userAudience->user_id = $user->id
//access then above created user ID and store in user_id column...
$userAudience->school= $request->input('school');
$userAudience->worker_ag = $request->input('worker_ag');
//and soo on...
//then save it...
$userAudience->save();
After that use the above user object to save audience id to it
$user->audience_id = $userAudience->id;
$user->save();
In this way you have already created user record in DB and it will not give constraint error
CodePudding user response:
First you need to add user_id
to the fillable
array on UserAudience
model and the same thing for audience_id
on User
model.
then you need to create the user first, since audience_id
is nullable:
$user = User::create([
//your basic data here
]);
then you create the audience and fill the user_id
with the previously created id
$audience = UserAudience::create([
'user_id' => $user->id,
//the rest of your data
]) ;
then updating the $user
with the associated audience_id
$user->audience_id = $audience->id;
$user->save() ;