Using foreign key in controllers Laravel 9 - laravel-9

I was creating two tables user and user_info and i want to use the userid in userinfo.
I don't know how to use the userid in userinfocontroller.

You must define one to one relation in your models.
in User Model :
public function info()
{
return $this->hasOne(Info::class,'foreign key'); // (Info = your userinfo model)
}
and in your Info model :
public function user()
{
return $this->belongsTo(User::class, 'foreign key');
}
you can read documents too.

In the User Model
public function info()
{
return $this->hasOne(userinfo::class);
}
And in userinfo Model
public function user()
{
return $this->belongsTo(User::class);
'user_id'
}

Related

Why is my Eloquent Relation not filling all of my objects?

I have a "types" table which contains only ID and Name, the relation works on the first object but returns null on the following objects. Here is what my JSON looks like:
{"id":1,"type_id":1,"name":"test1","enabled":1,"measurement_type":{"id":1,"name":"test"}},
{"id":2,"type_id":2,"name":"test2","enabled":0,"measurement_type":null}]},
{"id":3,"type_id":1,"name":"test3","enabled":1,"measurement_type":null}]}
Here are my relations:
MeasurementFields Model
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}
MeasurementTypes Model
public function measurement_type() {
return $this->belongsTo(MeasurementData::class);
}
In this Model I already have a measurement_field function which declares a belongsTo to MeasurementData (different Model) So, how do I name the new function with hasMany for types?
My Controller:
public function index()
{
return JsonResource::collection(MeasurementField::with('measurement_type')->get());
}
They all contain data, as you can see from the JSON, the relation just doesn't do anything with it.
My migrations:
Schema::create('measurement_types', function (Blueprint $table) {
$table->id()->autoincrement();
$table->string('name');
});
Schema::create('measurement_fields', function (Blueprint $table) {
$table->id()->autoincrement();
$table->foreignId('type_id')->constrained('measurement_types');
$table->string('name')->unique();
$table->boolean('enabled');
});
I think your measurement_type has many measurement_field.
and I guess you have to put this in your MeasurementField Model:
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}

Property [client] does not exist on this collection instance

I can't get the value of the foreign key that is inside the booking table.
Booking Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class booking extends Model
{
protected $primaryKey = 'bookingID';
protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
public function client()
{
return $this->hasOne(Client::class,'clientID');
}
}
Client Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class client extends Model
{
protected $primaryKey = 'clientID';
protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
public function booking()
{
return $this->hasMany(Booking::class);
}
}
I tried adding the protected $primaryKey = 'bookingID'; and protected $primaryKey = 'clientID'; as suggested in my previous question but now I still can't get just the FirstName from the client table.
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
You are trying to get a property from a collection in these lines:
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
but this property client is defined for object, not a collection. so to solve it you must take one object from the collection like the following:
$bookingDetail = booking::with('client')->first();
return $bookingDetail->client->firstName;
i thing you need to try this one:
in your booking model:
// 'App\Client' these is example you need to put your client model path
public function client()
{
return $this->belongsTo('App\Client','clientID');
}
in your client model:
public function booking()
{
return $this->hasMany('App\Booking' , 'clientID');
}

override relation in Laravel

I am working on limiting access depending on user roles.
I want to be able to somehow override a belongsToMany relation to return all, if user->isAdmin() returns true.
Currently have as the AccountController index method:
public function index()
{
if(Auth::user()->isAdmin()) // can this go in beforeFilter?
return Account::all();
else
return Auth::user()->accounts;
}
in my User model:
public function accounts()
{
return $this->belongsToMany("Account");
}
Is there a neat way to do this without needing an if statement in the controller functions?
You cannot do this.
The relation method must return an instance of Relation, otherwise it throws an error.
There's nothing stopping you from creating a separate method for this:
AccountController.php:
public function index()
{
return Auth::user()->userAccounts();
}
User.php:
public function accounts()
{
return $this->belongsToMany("Account");
}
public function userAccounts()
{
if ($this->isAdmin()) return Account::all();
return $this->accounts;
}

Laravel relational delete between three models

I have a simple relational models that I've built like that :
Parent :
<?php
class Appartement extends Eloquent {
public function gallery()
{
return $this->hasOne('Gallery', 'object_id')->where('type', '=', 'appartement');
}
public function delete()
{
$this->gallery()->delete();
return parent::delete();
}
}
First children Gallery
class Gallery extends \Eloquent {
protected $fillable = [];
public function images()
{
return $this->hasMany('GalleryImage');
}
public function delete()
{
$this->images()->delete();
return parent::delete();
}
}
Second Children Images
class GalleryImage extends \Eloquent {
protected $fillable = [];
public function gallery()
{
return $this->belongsTo('Gallery');
}
public function delete()
{
unlink(public_path().$this->link);
return parent::delete();
}
}
So basically nothing big : One appartement has one gallery, one gallery has many images.
It works pretty well, the problem is that when I delete an appartement, I would like to delete the gallery and the images associated to the appartement.
So I've tried to override the delete method.
Appartement get deleted, as well as gallery, but the images are not deleted, and it seems that there is no access to the delete function of Gallery, because I've tried to add a die; in the function, but it never dies.
Does anyone know how I can overcome this ?
Thanks
You have 2 options, the first is to set up foreign key constraints and cascade on delete using your migrations
// gallery migration
DB::table('galleries', function($table){
$table->foreign('object_id')
->references('id')->on('appartments')
->onDelete('cascade');
});
// images migration
DB::table('images', function($table){
$table->foreign('gallery_id')
->references('id')->on('galleries')
->onDelete('cascade');
});
The other option is to use model observers
here is an example: http://www.laravel-tricks.com/tricks/cascading-deletes-with-model-events this is useful on DB's that don't support FK constraints.

Laravel Eloquent, return JSON with "belongsTo" object?

I have two models with a one-to-many relationship.
class User extends ConfideUser {
public function shouts()
{
return $this->hasMany('Shout');
}
}
class Shout extends Eloquent {
public function users()
{
return $this->belongsTo('User');
}
}
This seem to work fine.
BUT, How do I get this to return the users object nested in the shout objects?
Right now it only returns all my Shouts, but I have no access in the JSON to the belonging user model.
Route::get('api/shout', function() {
return Shout::with('users')->get();
});
This just returns this JSON, with no user object for every shout:
[{"id":"1","user_id":"1","message":"A little test shout!","location":"K","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"},{"id":"2","user_id":"1","message":"And here is an other shout that is a little bit longer...","location":"S","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"}]
I was having the same trouble using Laravel 5. Just wanted to add that I got it to work by using the Model::with("relationship")->get() method on the model.
I figured it out.
The method needs to be named user() not users() when working with "belongsTo" relationship.
Makes sense.
And seems to work.
If you are using:
protected $visible = ['user'];
Don't forget to add there relationship, to be visible in JSON
u can use protected $with = ['users']; on Class Shout and use protected $with = ['shouts'];.
and Give Full namespace model name
class Shout extends Eloquent {
protected $with = ['users'];
public function users()
{
return $this->belongsTo('App\User');
}
}
and
class User extends ConfideUser {
protected $with = ['shouts'];
public function shouts()
{
return $this->hasMany('App\Shout');
}
}
Receive It
Route::get('api/shout', function() {
return Shout::all()->toJson;
});