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

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);
}

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 fix when using EmailAddress as column name

I am using the default auth in Laravel 5.8 (using make:auth) but cannot get the Reset Password functionality to work. I have an existing Users table (yes Uppercase U!) which has EmailAddress as the username column name and I suspect this is part of the problem. How may I fix this?
I have modified the Users model and ForgotPasswordController as follows:
class User extends Authenticatable implements MustVerifyEmail
{
// use Notifiable, HasRoles, UsesUuid; // Traits
use Notifiable, UsesUuid;
protected $table = 'Users';
protected $primaryKey = 'Id';
protected $username = 'EmailAddress';
protected $guarded = [];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getEmailAttribute()
{
return $this->attributes['EmailAddress'];
}
}
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
protected $username = 'EmailAddress';
public function __construct()
{
$this->middleware('guest');
}
public function username()
{
return 'EmailAddress';
}
protected function validateEmail(Request $request)
{
$request->validate(['EmailAddress' => 'required|email']);
}
protected function credentials(Request $request)
{
return $request->only('EmailAddress');
}
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return back()
->withInput($request->only('EmailAddress'))
->withErrors(['EmailAddress' => trans($response)]);
}
}
I expect to receive an email with the reset link but this never gets sent. The /password/reset page does not redirect, just reloads.

eloquent relation not working on live server

I have two tables one is user and other is profile. one user can have one profile. This relation works perfectly on local server but when i upload it on live server the relations are not working not just user and profile but other relations also.
here is my laravel model code for profile and user.
class Profile extends Model
{
protected $fillable = ['user_id','fname','mname','lname',
'birthdate','country','address','phone', 'image'];
protected $hidden = ['user_id'];
public $timestamps = false;
public function users() {
return $this->belongsTo('App\User', 'id');
}
}
User model
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'email_token'
];
protected $hidden = [
'password', 'remember_token', 'email_token'
];
public function users(){
return $this->hasOne('App\Profile', 'user_id');
}
}
Here how i am trying to get profile data from login user in controller
Auth::user()->users->image
I found the solution the problem was
public function users() {
return $this->belongsTo('App\User', 'id');
}
this should have been
public function user() {
return $this->belongsTo('App\User', 'id');
}
changed from plural to singular.

Laravel 5.1 Eloquent Relationship

Is there anyone can suggest from the eloquent relationship that I have based on the screenshot and model setup?
Model setup:
class Leaves extends Model
{
protected $table = 'leaves';
protected $fillable = [
'leave_type',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
class LeaveType extends Model
{
protected $table = 'leave_type';
protected $fillable = ['type_name'];
}
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function leave()
{
return $this->hasMany('App\Leaves');
}
}
Currently I only able to get the leaves detail but need to retrieve the leave_type's type_name based on
$user = User::oldest('name')->get();
foreach ($users as $user) {
$user->leave()-get();
}
in your Leave model you would have
function type() {
return $this->hasOne(App\LeaveType);
}
in your LeaveType you should reciprocate
function leave() {
return $this->belongsToMany(App\LeaveType);
}
and in your controller:
$user = User::oldest('name')->with('leave', 'leave.type')->get();
dd($user->leave->type);
Leaves model:
class Leaves extends Model {
protected $table = 'leaves';
protected $fillable = [
'leave_type',
'user_id'
];
public function User()
{
return $this->belongsTo('App\User');
}
public function LeaveType()
{
return $this->belongsTo('App\LeaveType');
}
}
LeavesType model:
class LeaveType extends Model {
protected $table = 'leave_type';
protected $fillable = ['type_name'];
public function Leaves()
{
return $this->hasMany('App\Leaves');
}
}
User model:
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function Leaves()
{
return $this->hasMany('App\Leaves');
}
}

Resources