Laravel 5 get name based on ID - laravel

I have a users and departments table. So my departments table might have a row like so
id | departmentName
----------------------
2 | Marketing
----------------------
And the users table might have something like
id | name | email | departmentId
-------------------------------------------------------
18 | Nick | nick#email.com | 2
-------------------------------------------------------
So the users table links to the departments table via the id.
So now onto my UserController, in the index function, I do
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
Now that will display everything within my users table.
My problem is, I do not want to display the departmentId. I want to display the departmentName which is linked to that departmentID. So in the above example, my users index page for that one row should show Marketing, not 2.
How would I go about doing this?
Thanks

You can use Eloquent Relationships. What you described in your question is a One-to-Many Relation, meaning a department can have many users, and each user belongs to a department. So you'll need to setup a model for your departments table (if you haven't done so already) and then define the relationship in your User model like so:
class User extends Model
{
public function department()
{
return $this->belongsTo('App\Department', 'departmentId');
}
}
You can then access the department details in your view via that relationship:
#foreach ($users as $user)
{{ $user->department->departmentName }}
#endforeach

Related

How to organize Laravel ORM for relationships table

I have two table Users and Relationships. The table Relationships contains next fields:
id | user_one_id (fk to users) | user_two_id (fk to users) | status | action_user_id
The status field can be one of 4 values. 0 - pending, 1 - accepted, 2 - rejected, 3 - blocked.
Action user is those user who created or updated request. For example, user with id 1 want to be a friend with user with id 2. action_user_id will 1.
I can't organize relationships in my User model.
For example my method friends
public function friends()
{
return $this->belongsToMany(User::class, 'relationships', 'id', 'user_one_id')
->orWhere('user_two_id', $this->id);
}
creates next sql query:
select * from "users" inner join "relationships" on "users"."id" = "relationships"."user_one_id" where "relationships"."user_one_id" = ? or "user_two_id" = ?
but I understand that it is not i need.
What i need? I need 3 methods "friends", "requested" and "blackList".
The "friends" method must return all friends of current user. The "requested" method must return all friend requests to current user. And the "blackList" must return all users who are in the blocked status of current user.
Try using a where clause, based on the status to retrieve the particular data. I recreated the problem in a fresh laravel install, and I used the user class and a relationships table to reffer to two users in a relationship
//Model User: $user->friends gets the list of friends of the user
public function friends()
{
return $this->belongsToMany('App\User', 'relationships','friend_2','friend_1')->where('friendship_status','friends');
}
At the blade.php view:
#foreach(\App\User::all() as $user)
<h5>{{$user->name}}</h5>
#foreach($user->friends as $friends)
<div>
<small>Is friends with {{$friends->name}}</small>
</div>
#endforeach
#endforeach
Relationships table migration:
Schema::create('relationships', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('friend_1');
$table->unsignedbigInteger('friend_2');
$table->string('friendship_status')->default('request pending');
$table->timestamps();
});
Manually added relationships:

Getting data from pivot table using eloquent

I have two tables with a pivot table
Table user
id | name | email
Table drinks
id | name
Pivot Table user_drinks
id | user_id | drink_id | quantity | price | status
I want to get all users and drinks with status set to 1 and their latest details from the pivot table, that is use the user_Id to get the username and drink_Id to get the drink name then the price and quantity from the pivot table.
In your User Model put this //App\User.php
public function drinks()
{
return $this->belongsToMany(Drink::class)->where('status',1);
}
In your DrinkModel put this //App\Drink.php
public function users()
{
return $this->belongsToMany(Drink::class)->where('status',1);
}
Then in your controller you can use this like
$users = User::has('drinks')->get(); //to get all the user that has drinks column status set to 1
foreach ($users as $user) {
//you rest of code
}

I have a laravel project with 2 tables (users and roles). In a roles view, I am trying to display a count of users who are using that specific role

My tables areas follows
roles table (id, roleName, roleDesc)
users table (id, name, role, email)
When adding a new user, I insert a role eg "Admin" into the role column of the user.
My problem is that I want to show the number of users who have that role in a view data table that displays list of roles. Eg would simply be an integer of number of members who share that role, eg 5.
In my roleController, I am fetching records using
$roles = Role::all();
$users = User::all();
I have managed to display a count of users with role "Admin", but this ofcourse just duplicated all down the datatable with eg "1"
$RoleCount = User::where('role', '=', 'Admin')->count();
So, I think I need to use a join or something to replace the 'Admin' above, with current roleName.
I hope that makes sense and I hope someone can help me find a solution. I know this is pretty elementary, but trying to rap my head around joins and having a bit of trouble.
Thanks in advance.
First it will be great to use Relationships (Laravel docs)
With relationships it will be super easy.
Change Users table, so you have there NO the name of role, but ID of role = columns id, name, role_id, email
In Role model add relationship to User, and in User model add relationship to Role:
Model User.php - add method
public function role(){
return $this->belongsTo('App\Role'); //use your correct namespace
}
Model Role.php - add method
public function users(){
return $this->hasMany('App\User'); //use your correct namespace
}
And then just select all roles with count of users:
$roles = Role::withCount('users')->get();
In your view:
#foreach($roles as $role)
{{ $role->roleName }} - {{ $role->users_count }}<br>
#endforeach

foreach the data of relationship

I have two tables media_user and users
media_user table like [ id | user_id | media_id | link ]
I need to bring all user from media_user by relationship, so I created relation in user model:
/**
* that users belong to the media_user table.
*/
public function media()
{
return $this->hasMany('App\Models\Social_Media','user_id','id');
}
And in the view, I did this
#foreach ($user->media as $m)
// my data
#endforeach
I got the empty array when I dump the result as dd($user->media)
What is the problem pls?
The relation looks fine, please check
there are some media items for the user with a correct foreign key.
there is an attribute in the user table called media.
there is no global scope.
the $user is a valid object and belongs to the ORM model
I suggest installing debug bar and view executed query on the media table

Laravel Eloquent - many to many with where for the pivot table

I'm trying to see what the best way to do the following.
I have 3 tables: users, items and item_user.
users and items table are pretty generic, id and a few columns to hold whatever data.
item_user table has the following structure
id
item_id
user_id
user_type [ 1 - Owner | 2 - Follower | 3 - Something else ]
Relationships:
Each Item has 1 Owner (user type)
Each Item has many followers
Each User can own many Items
Each User can follow many Items
I would like to have the Owner and Followers be the Users table so I don't need to replicate user data. I created a pivot table of item_id, user_id and user_type to hold these relationships.
So the question is how to I do this in Laravel Eloquent?
Item Model looks like:
public function user() {
return $this->belongsToMany('Users');
// This isn't actually correct since it belongs to only one User but not sure how to specify a where user_type = 1;
// return $this->belongsTo('User');
}
User Model looks like:
public function item() {
return $this->hasMany('Item');
}
Thanks!
You can just append the condition to your belongsToMany declaration:
public function user() {
return $this->belongsToMany('Users')->where('user_type', 1);
}
This will return only the User entries that have user_type = 1 in your pivot table. And just to make it more clear you could name the method owner() instead of user() to reflect the added condition.

Resources