Eloquent relationship for multiple table - laravel

I am working in laravel5.4. I have created four table as ticket, users, and company. Here, I have stored users id in ticket table. And stored company id in users table.
Here, I want to show ticket's user name with that users company name.
Here, I have create relation for it that looks like below.
Ticket model :
public function requesters(){
return $this->belongsTo('App\User','requester_id');
}
Here requester_id is who create ticket.
Users model :
public function company()
{
return $this->belongsTo('App\Models\Admin\Company');
}
Company model :
public function Users()
{
return $this->hasOne('App\Users');
}
Here, I have written query to get users information that looks like below.
Ticket::with('requesters')->orderBy('subject','asc')->paginate(10);
Now, I want to fetch company information or request_id So what changes should I have to do in this query to fetch company info along with ticket and users ?

If you want to to Eager load multiple relationship you can put them all in single with like this:
Ticket::with('requesters','requesters.company')->orderBy('subject','asc')->paginate(10);
but if you load nested relationship you can use shorter notation - you can omit parent relationship, so it's enough to use here:
Ticket::with('requesters.company')->orderBy('subject','asc')->paginate(10);

Try this, it should work for this case:
Ticket::with('requesters')
->with('requesters.company')
->orderBy('subject','asc')->paginate(10);

Related

How to search for all associations in a relationship tree in Laravel?

I'm having a problem. I have tables that relate:
internal_clients->subsidiaries->departments->job_titles->users
I also have their respective models.
My doubt is:
How do I get all the data associated with users from the top of the tree (internal_clients)
?
I'm trying to follow the Laravel documentation using hasManyThrough.
However, in the documentation it explains only how to do it in a chain of three tables. They teach how to place an intermediate table (model) as the second parameter of the hasManyThrough method (BaseClasse::class, IntermediaryClass::class).
However, in my case that has several tables between users and internal_clients, how would I do this? What would be the intermediate table?
I would like to make a query that returns the user's internal_client, subsidiary, department and jobTitle (associated with users).
I'm trying to do it this way:
Model InternalClient
public function users()
{
return $this->hasManyThrough(User::class, InternalClient::class);
}
Controller UserController
public function allRelations($internalClientId)
{
$internalClient = InternalClient::find($internalClientId);
$users = $internalClient->users;
return response()->json($users, 201);
}
The InternalClient id arrives at the controller above.
When I access the route, the error below is returned:
In short: I would like to know if there is a way to get all the data (from all tables that are in this hierarchical tree) that are associated with the User.
I couldn't find an answer on the Stackoverflow PT-BR.
Thank you!

Laravel: Pull data from multiple tables

I am new to Laravel but I dont think Im writing optimised code. I am looking at getting all overdue invoices separated by clients. Invoices table and clients table. client_id is within the invoices table. I have the following below but I wanted to know if there is a better way. I would also want to grab the client name from the clients table. I have created an array so I can loop throgh accordingly on the view file, but again im not sure this is the correct way?:
$overdueClients = Invoice::where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"))->pluck('client_id');
foreach($overdueClients as $overdueClient)
{
$invoices = Invoice::select("title","total","on_account","date","date_due")->where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"))->where('client_id',$overdueClient)->get();
$return[$overdueClient][] = $invoices;
}
return $return;
yes luckily there is a better way for which term is called relations and can use eager loading so what you can do is to make relation is models first :
so in you Invoice model you write something like below :
public function users(){
return $this->belongsTo('App/Users');
}
you should fix the above relation according to the name and path of your model and in your users model :
public function invoices(){
return $this->hasmany('App/Invoices');
}
so now an invoice belongs to a user and a user can Have many Invoices . and when you need to get the users which has invoices and overdue invoices you do like below :
$users = Invoices::with('users')->where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"));
this is the better way to act because of preventing n+1 problems this way you only load users if they have overdue invoices if not they are not being loaded at all take a look at documentation below :
https://laravel.com/docs/7.x/eloquent-relationships#introduction
i strongly recommand to take time and read this and practice it as you would need it more that you think when you want to work with laravel . hope this helps

How to limit access from pivot table? Laravel

I have tables:
user
id
name
companies
id
name
company_user
company_id
user_id
Tables has Many To Many relationships.
As it complicated relationship for me, I can't find way how to make this limit, when user can see companies that was created by this user. (probably not well experienced)
Now I have this, but user can see any company
CompanyController:
public function show($company_id)
{
$company = Company::where('id', $company_id)->firstOrFail();
return view('company.settings', compact('company'));
}
So tip me please how to make user can see only companies created by this user.
You can do this:
public function show($company_id)
{
$company = auth()->user()->companies()->findOrFail($company_id);
return view('company.settings', compact('company'));
}
It will scope the company to the currently logged in user (through the many-to-many relationship on the User model). If none is found, it will return 404.
Since it many to many relation, you can map one company to many users, also map one user to many companies. Check if you have not mistakenly assign the company to many user
Also the above code can be written the way
public function show($company_id)
{
$company = Company::findOrFail($company_id);
return view('company.settings', compact('company'));
}

Laravel relationship between two tables

I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.

User Relationships, Many to Many

I need to create relationships between users. As you might expect, they exist in the users table. My approach is a relationships table linking user_a_id to user_b_id.
Then, in the User model, I added:
public function relationships()
{
return $this->belongsToMany('User', 'relationships', 'user_a_id', 'user_id');
}
Unfortunately, I get an error when trying to find the relationships;
dd($user->relationships);
Output: Whoops, looks like something went wrong.
I would consider something like a "user" model, and a "group" model. The users table can have a many-to-many relationship with the groups table, and this could be defined with a "user_group" table, containing a column "user_id" and another "group_id". Then you can have a function in your User model called groups, which does return $this->belongsToMany('Group');, and a function in your Group model called Users, which goes return $this->belongsToMany('User');
Refer to this section of the Eloquent docs for further direction.

Resources