Inverse relation returns null using Eloquent - laravel

I have a simple one-to-many relationship, where one authentication type has many client:
class Client extends Model {
protected $table = 'client';
protected $primaryKey = 'client_id';
protected $fillable = [
'client_id',
'auth_type_id',
];
public function auth()
{
return $this->belongsTo('App\AuthType', 'foreign_key', 'id');
}
}
class AuthType extends Model {
protected $table = 'authType';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'name'
];
public function users()
{
return $this->hasMany('App\User', 'foreign_key', 'auth_type_id');
}
}
So what I want is, to access the name of the authentication, when the $client is known.
$authType = $client->auth();
$authType->name;
And I get:
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
How can I access the name property of Auth, if I have a Client ?

If you want to get the relation result you have to use
$authType = $client->auth;
If you use $client->auth() you'll get back a BelongsTo relation.

Related

One to Many Relationship with Pivot Table and fetch related data using the with method

In Laravel 5.5 application, I have a model called Meeting and a model called Room.
Both models have a many-to-many relationship through a pivot table called MeetingSchedule.
The MeetingSchedule table has a column called schedule_by which is a foreign key to the user_id column in the User table.
I want to get the email address of the user who scheduled the meeting, when I fetch the meeting details with schedules() function of Meeting model.
I have tried the following code but it does not work:
class Meeting extends Model {
protected $table = 'Meetings';
protected $primaryKey = 'meeting_id';
protected $fillable = ['topic', 'description', 'participants_count'];
public function schedules() {
return $this->belongsToMany('App\Room', 'MeetingSchedule', 'meeting_id', 'room_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class Room extends Model {
protected $table = 'Rooms';
protected $primaryKey = 'room_id';
protected $fillable = ['name', 'location', 'capacity'];
public function schedules() {
return $this->belongsToMany('App\Meeting', 'MeetingSchedule', 'room_id', 'meeting_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class MeetingSchedule extends Pivot {
protected $table = 'MeetingSchedule';
protected $primaryKey = 'schedule_id';
public function scheduledBy() {
return $this->belongsTo('App\User', 'scheduled_by', 'user_id');
}
}
class User extends Authenticatable {
protected $table = 'User';
protected $primaryKey = 'user_id';
protected $fillable = ['username', 'email'];
public function meetingScheduledBy()
{
return $this->hasMany('App\MeetingSchedule', 'scheduled_by', 'user_id');
}
}
function getMeetingWithRelatedData($meetingId) {
return Meeting::where('meeting_id', $meetingId)
->with(['schedules'])
->first();
}

How To DYnamic Menu with Laravel Relation

I'm trying to create a nestable dynamic menu with Laravel. I have a hasMany relationship and I'm trying to get categories->subcategory->menu
this is my categories model
class KategoriModel extends Model
{
protected $table = "sys_kategori";
protected $fillable = [
'Kategori',
'Ikon',
'Slug',
];
public function subcategories()
{
return $this->hasMany(SubKategoriModel::class, 'idKategori','id');
}
}
this is my subcategory model
class SubKategoriModel extends Model
{
use HasFactory;
protected $table = "sys_subkategori";
protected $fillable = [
'subKategori',
'idKategori',
'ikon',
'slug',
];
public function kategori()
{
return $this->belongsTo(KategoriModel::class, 'idSubkategori', 'id');
}
public function subsubmenu()
{
return $this->hasMany(MenuModel::class, 'idSubkategori', 'id');
}
}
this is my subsubmenu model
class MenuModel extends Model
{
use HasFactory;
protected $table = "sys_menu";
protected $fillable = [
'Menu',
'idSubkategori',
'Ikon',
'Slug',
];
public function subKategori()
{
return $this->belongsTo(SubKategoriModel::class, 'id', 'idSubkategori');
}
}
this is my controller
'kategori' => KategoriModel::with('subMenu.subsubmenu')->get(),
when id dd the variable its only show
my dd
and there is no relation from subcategory and submenu
thank in advnace

How to get the company ID of the Logged in user from a related table

I am trying to get the logged in user's company_id, In my Laravel 8 Job Portal application. I have these models:
Department
User
Company
CompanyProfile
A User can only appear once on the users table with unique email. But he can have more than one CompanyProfile, since he can work remotely for more than one Company:
These are the models:
class Department extends Model
{
protected $table = 'departments';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'company_id',
'name',
];
public function company()
{
return $this->belongsTo('App\Models\Company','company_id');
}
}
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'name',
'org_image',
];
public function users()
{
return $this->hasMany('App\Models\User');
}
public function departments()
{
return $this->hasMany('App\Models\Department');
}
}
class User extends Authenticatable
{
protected $hidden = [
'password',
'remember_token',
];
protected $fillable = [
'name',
'first_name',
'other_name',
'last_name',
'username',
'email',
'password',
];
public function profile(){
return $this->hasMany('App\Models\CompanyProfile', 'employee_id');
}
public function company(){
return $this->hasMany('App\Models\CompanyProfile', 'company_id');
}
}
class CompanyProfile extends Model
{
protected $table = 'company_profiles';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'user_id',
'company_id',
'department_id',
'employment_date',
];
}
Having in mind that the company_id is not in the User model, How do I get the company_id of the Logged in User in the DepartmentController?
public function index()
{
$departments = Department::where('company_id', ...)->get();
return view('departments.index')->with('departments', $departments);
}
Thanks
Here, you can use "hasManyThrough" relationship
change company relationship in user model as below
public function company(){
return $this->hasManyThrough('App\Models\Company', 'App\Models\CompanyProfile');
}
https://laravel.com/docs/8.x/eloquent-relationships#has-many-through
I am not sure about this but as per scenario i will do it like this
public function index()
{
$user_id = Auth::user()->id;
$users_data = User::where('id',$user_id)->with('company')->first();
$company_id = $users_data->company->company_id;
$departments = Department::where('company_id', $company_id)->get();
return view('departments.index')->with('departments', $departments);
}

Two foreign keys pointing to the same table / model

I have two models:
TRUCK
DRIVER
TRUCK has two fields which are FKs. Driver (FK) and Driver2 (FK).
When I try to get the truck with driver and driver2, I get two same records.
$truck = $this->instance->truck()->where('id', $id)
->with(['driver', 'driver2',])
->firstOrFail();
My Truck Model:
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver');
}
My Driver Model:
class Driver extends Model
{
use SoftDeletes;
protected $table = 'drivers';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function truck()
{
return $this->belongsTo('App\Models\Truck');
}
I am still new to laravel and something I get stuck. Should I create another model instead maybe?
By default laravel will use default foreign key,
Eloquent assumes the foreign key of the relationship based on the
model name #Further reading
So both relation are pointing to the same FK, So you need to specify the foreign key as below
return $this->hasOne('App\Models\Driver', 'Driver');
return $this->hasOne('App\Models\Driver', 'Driver2');
Full code
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver', 'Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver', 'Driver2');
}

Eloquent firstOrCreate documentation or usage

I'm attempting to seek a table to see if a column named "name" exists if so return the value and if not create that row with a null value i saw firstOrCreate but i cannot figure out how to use it for the life of me.
This is what i currently have, can someone lend a hand?
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return self::firstOrCreate(array('name' => $settingName));
// return self::select(array('value'))->where('name', '=', $settingName)->first()->value;
}
}
The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:
Set the fillable columns of your model:
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Or set only the ones you want to keep guarded:
class User extends Eloquent {
protected $guarded = array('password');
}
You may, at your own risk also do:
class User extends Eloquent {
protected $guarded = array();
}
And everything will be unguarded.
Take a look a the docs: http://laravel.com/docs/eloquent#mass-assignment
You also could use your Facade to call it:
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return Settings::firstOrCreate(array('name' => $settingName));
}
}

Resources