Accessing 3 tables in Laravel using foreign key (laravel 6) - laravel

I want to show data from a database(sql) that is from a specific user.
I have 3 tables:
Users
Stores
Areas
These are the following relationship between tables:
User hasOne Area
Area hasMany Stores
Basically what I wanted to show is that every user has their own area that has many stores.
User model
function area() {
return $this->hasOne('App\Area');
}
Area model
function user() {
return $this->belongsTo('App\User');
}
function stores() {
return $this->hasMany('App\Store');
}
Store Model
function area() {
return $this->belongsTo('App\Area');
}
My database looks like this:
user table
id name role_id area_id
area table
id name user_id
store table
id name area_id
How can I access user->area->store?
This is what I got so far
function show() {
$id= Auth::user()->id;
$user = User::find($id);
echo($user->area->stores);
}
Thank you

you can use the hasManyThrough for get sotres of an area:
define stores function in User model
public function stores()
{
return $this->hasManyThrough(Store::class, Area::class);
}
and use it :
$stores = auth()->user()->stores;
I hope be useful.

Related

Laravel 5.8 Eloquent Model Relationship error

I have a relationship between two models, User and Follower.
User hasMany Follower, and Follower belongsTo User.
In my followers table in the database I have two columns, follower_id and following_id. Both these columns refer to the id column in the users table.
My follower and users table
followers
id
follower_id
following_id
users
id
name
username
User Model
public function followers(){
return $this->hasMany('App\Follower', 'follower_id');
}
public function followings(){
return $this->hasMany('App\Follower', 'following_id');
}
Follower Model
public function user(){
return $this->belongsTo('App\User');
}
In a test controller I am doing this:
$followed = Follower::find(2);
From here, I would like to select one of the columns, follower_id or following_id, and access the user that this particular row belongs to by using $followed->user->name. How would I go about that? Since I need to select a column before accessing, I am a little bit confused.
What can I do to access the data I need?
Your table should be :
followers
id
follower_id
following_id
user_id
users
id
name
username
In your Follower model :
public function user()
{
return $this->hasMany(Follower::class, 'user_id');
}
In your User model :
public function follower()
{
return $this->belongsTo(User::class, 'user_id');
}
Then you can query like this :
$follower = Follower::with('user')->findorFail(2);
$user_name = $follower->user->name;

How to setup relationship between 2 table which has both one-to-many and many-to-many relationship?

I have a Users table and an Events table.
It's has one-to-many relationship.
Each user can create many event.
Each event belongs to one user.
Also, it has many-to-many relationship.
Each user can join as many event as they want.
Each event can be joined by many user.
This needs pivot table.
Now, I'm stuck.
This is event model.
public function user(){
return $this->belongsTo('App\User');
}
public function users(){
return $this->belongsToMany('App\User')
->withTimestamps();
}
This is user model.
public function events(){
return $this->hasMany('App\Event');
}
public function events(){
return $this->belongsToMany('App\Event');
}
The problem is in the user model where I can't define multiple function with the same name.
So, is there a way to do this correctly?
Quick answer
Of course you can't have two functions with the same name. In your case, try to use more specific names for each function:
public function createdEvents()
{
return $this->hasMany('App\Event');
}
public function joinedEvents()
{
return $this->belongsToMany('App\Event');
}
Recommendation
You can use a single many-to-many relationship to manage both relations with Pivot information:
users table
id
username
...
events table
id
name
...
event_user table
user_id
event_id
is_creator (default FALSE, unsigned integer)
...
Then when creating an event, relate the user and event objects and set the is_creator field to TRUE.
So in your User model:
app/User.php
public function events()
{
return $this->belongsToMany('App\Event')->withPivot('is_creator');
}
Then in your controller when you want to create an event:
app/Http/Controllers/SomeCoolController.php
public function store(CreateEventRequest $request)
{
// Get your event data
$data = $request->only(['your', 'event', 'fields']);
// create your object
$newEvent = Event::create($data);
// create the relationship with the additional pivot flag.
auth()->user()->events()->attach($newEvent, ['is_creator' => true]);
// the rest of your code.
}
And when a user want to 'join' an event:
app/Http/Controllers/SomeCoolController.php
public function join(JoinEventRequest $request)
{
// Get the event
$event = Event::find($request->event_id);
// relate the ev
auth()->user()->events()->attach($newEvent, ['is_creator' => false]);
// or just this, because its already set to false by default:
// auth()->user()->events()->attach($newEvent);
// the rest of your code.
}
It seems like it's many to many relationships between User and Event so there will be pivot name like user_event
user model
public function events() {
return $this->belongsToMany('App\Event')->using('App\UserEvent');
}
Reference: https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7

I'm trying to retrieve related models of the same type on from a pivot table.
I have 2 models, App\Models\User and App\Models\Group and a pivot model App\Pivots\GroupUser
My tables are have the following structure
users
id
groups
id
group_user
id
user_id
group_id
I have currently defined relationships as
In app/Models/User.php
public function groups()
{
return $this->belongsToMany(Group::class)->using(GroupUser::class);
}
In app/Models/Group.php
public function users()
{
return $this->belongsToMany(User::class)->using(GroupUser::class);
}
In app/Pivots/GroupUser.php
public function user()
{
return $this->belongsTo(User::class);
}
public function group()
{
return $this->belongsTo(Group::class);
}
I'm trying to define a relationship in my User class to access all other users that are related by being in the same group. Calling it friends. So far I've tried this:
app/Models/User.php
public function friends()
{
return $this->hasManyThrough(
User::class,
GroupUser::class,
'user_id',
'id'
);
}
But it just ends up returning a collection with only the user I called the relationship from. (same as running collect($this);
I have a solution that does work but is not ideal.
app/Models/User.php
public function friends()
{
$friends = collect();
foreach($this->groups as $group) {
foreach($group->users as $user) {
if($friends->where('id', $user->id)->count() === 0) {
$friends->push($user);
}
}
}
return $friends;
}
Is there a way I can accomplish this using hasManyThrough or some other Eloquent function?
Thanks.
You can't do that using hasManyThrough because there is no foreign key on the users table to relate it to the id of the group_user table. You could try going from the user to their groups to their friends using the existing belongsToMany relations:
app/Models/User.php:
// create a custom attribute accessor
public function getFriendsAttribute()
{
$friends = $this->groups() // query to groups
->with(['users' => function($query) { // eager-load users from groups
$query->where('users.id', '!=', $this->id); // filter out current user, specify users.id to prevent ambiguity
}])->get()
->pluck('users')->flatten(); // massage the collection to get just the users
return $friends;
}
Then when you call $user->friends you will get the collection of users who are in the same groups as the current user.

How to create relationship in Laravel 5 which will collect records of own model mentioned in pivot table?

I have 3 tables users, companies and pivot table with user_id, company_id.
I can't get users, which belongs to my company inside User model.
Tried like
belongsToMany('App\User','companies_users','company_id','user_id' );
but I get relation with wrong users.
Since you are having a belongsToMany relationship between the User and Company, the User belongs to more than one Company. To get users of the companies of a particular User will not be straight forward. If you are sure that is exactly what you want, then do this:
//inside the User model
public function companies()
{
return $this->belongsToMany('Company');
}
//inside the User model
public function companiesusers()
{
$users= new Illuminate\Database\Eloquent\Collection;
foreach($this->companies as $company)
{
$users = $users->merge($company->users->get());
}
return $users->unique();
}
//inside the Company model
public function users()
{
return $this->belongsToMany('User');
}
Then you can get a user's companiesusers like so:
User::first()->companiesusers();

User to User Model: One to Many Relationship on Laravel

I'm doing a project for one of my University courses. But I'm finding it difficult to make relationship between User to User model.
Table: users
id
name
email
type
password
On this table the column type is used for classifying user types.
For example: User can be either distributor or dealer type.
And a distributor may have many dealer
But a dealer may have only one distributor.
To implement this I've created another table and named as dealers_of_distributor.
Table: dealers_of_distributor
id
distributor_id (id of users table)
dealer_id (id of users table)
Although I've used an additional model DelaersOfDistributor, the exact relationship should be between user to user.
How can I make this relationship. I'm confused!
I've tried so far:
Model: User
public function dealersOfDistributor(){
$this->hasMany('App\DealersOfDistributor');
}
Model: DealersOfDistributor
public function user(){
return $this->belongsTo('App\User');
}
The DistributorsController
public function index()
{
$distributors=User::where('type', 'distributor')->get();
$dealers=User::where('type', 'dealer')->get();
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index')->withDistributors($distributors)->withDealers($dealers)->with('assignedDealers', $assignedDealers);
}
In blade file: I've tried $assignedDealer->dealer_id->user->name. But It's showing error.
Model DealersOfDistributor:
public function distributorUser()
{
return $this->belongsTo('App\User', 'distributor_id', 'id');
}
public function dealerUser()
{
return $this->belongsTo('App\User', 'dealer_id', 'id');
}
than you just get the user's data from DealersOfDistributor model, call function dealerUser if you want get user's data from dealer_id, and call function distributionUser if you want get user's data from distribution_id
Controller:
public function index()
{
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index',compact('assignedDealers'));
}
Blade get username:
#foreach($assignedDealers as $assign)
{{$assign->distributorUser->name}}
{{$assign->dealerUser->name}}
#endforeach

Resources