Save object with foreign keys in laravel - php

I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}

You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...

When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.

Related

Cannot update using findOrFail method in Laravel

I am a newbie in Laravel. So I am trying to update my form but it kept returning fail because I used the findOrFail method on the Controller.
But when I tried to dump the Id, the Id does exists.
Only when I call it using the method, it returns null.
Route for update
Route::post('/alumni/updateProfile','AlumniController#update');
Update method
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
Profile model
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
User model
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Glad if any of you noticed anything, thank you.
You can write findOrFail() in try catch blog and get the exception in catch blog to understand the error.
OR
you can write below code instead of findOrFail().
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}

Create one to many table relationship with text input Laravel

I have two tables with a one to many relationship - gratitude_journal_entries and self_gratitudes. Multiple self gratitudes (which are submitted as text entries by the user) can apply to 1 gratitude_journal_entry. The data is passed to these two tables via a form.
I am trying to store the self gratitude text entries in an array and then pass these to the self_gratitude table along with the foreign key from the gratitude_journal_entries table.
The problem I'm having is I'm not sure how to take the input from the array and store this in the self_gratitude column.
Here are the columns for the gratitude_journal_entries table
Here are the columns for the self_gratitudes table
Here are the models and the store method in my controller
class SelfGratitudes extends Model
{
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
class GratitudeJournalEntry extends Model
{
protected $table = 'gratitude_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function selfGratitudes()
{
return $this->hasMany(SelfGratitudes::class);
}
public function store(Request $request)
{
$this->validate($request, [
]);
$gj_entry = new GratitudeJournalEntry;
$gj_entry->user_id = auth()->user()->id;
$gj_entry['entry_date'] = date('Y-m-d H:i');
$self_gratitudes = $request->has('self_gratitudes') ? $request->get('self_gratitudes') : [];
$tj_entry->save();
$gj_entry->selfGratitudes()->sync($self_gratitudes);
return redirect('/dashboard')->with('success', 'You submitted a new journal entry');
}
If you want to keep array in database you can use casting on your columns:
laravel document
class SelfGratitudes extends Model
{
protected $casts = [
'self_graitude' => 'array',
];
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

laravel eloquent: many to many relations

I would like to add some items in my db table pivot using eloquent ->attach but i don' t understand why it don't work:
I have 2 models (Salade=>(table 'salades' in DB) and Ingredient=>(table 'ingredients' in DB),
the pivot table is ingredient_salade( 3columns : id, ingredient_id,salade_id).
My Models:
class Ingredient extends Model
{
protected $table = 'ingredients';
protected $fillable = ['nom'];
public function Salades()
{
return $this->belongsToMany('App\Salade');
}
}
class Salade extends Model
{
protected $table = 'salades';
protected $fillable = ['nom','prix'];
public function ingredients()
{
return $this->belongsToMany('App\Ingredient');
}
}
SaladeController#Store
public function store(Request $request)
{
$this->validate($request, [
'nom' => 'required',
'prix' => 'required' ]);
$salade = $request->only(['nom', 'prix']);
// insert new salade in DB
$lanouvelleSalade = \App\Salade::create($salade);
//insert relation in pivot table
$lanouvelleSalade->ingredients()->attach([21,22,23]);
return redirect('salade')->withOk("Le Salade " . $request->input('name') . " a été modifié.");
}
the tables:
image of the tables
the new salade is insert in table salades but the relation in Pivot is not insert. Why?
change:
$lanouvelleSalade->ingredients()->attach([21,22,23]);
to:
$lanouvelleSalade->ingredients()->sync([21,22,23]);
replace your relation codes with this codes and check it:
Ingredient Class:
public function Salades()
{
return $this->belongsToMany('App\Salade','ingredient_salade','ingredient_id','salade_id');
}
And Salade Class:
public function ingredients()
{
return $this->belongsToMany('App\Ingredient','ingredient_salade','salade_id','ingredient_id');
}
let me know if you have any error

Laravel 5: no foreign key when saving related models

I have a simple one-to-one relationship between a User and a Profile, I'm trying to create a user and save their profile with the foreign key in one go and avoid having to pass the primary key and do two save() calls.
Laravel will try to insert the corresponding Profile values without the id pointing back to the user. What am I doing wrong ?
class User extends Model
{
public function profile()
{
return $this->hasOne('App\Profile');
}
}
class Profile extends Model
{
protected $table = 'user_profile';
public function user()
{
return $this->belongsTo('App\User');
}
}
class UserController extends Controller
{
public function create(Request $request)
{
$this->validate($request, [
...
]) ;
$user = new User() ;
$profile = new Profile() ;
$user->name = $request->input('name') ;
...
$profile->first_name = $request->input('first_name') ;
$profile->last_name = $request->input('last_name') ;
...
$user->profile()->save($profile) ;
// $profile->user()->save($user) ; // doesn't work
// $profile->user()->associate($user) ; // doesn't work
// $profile->save() ;
}
}
you need first to save the user
$user = new User;
$user->name = $request->input('name') ;
$user->save();
$profile = new Profile;
$profile->first_name = $request->input('first_name') ;
$user->profile()->save($profile);
The function name you are looking is "associate"
$user->profile()->associate($profile);
$user->save();

Categories