Trying to count record by user id - laravel

I am trying to get record by user id.This is working for login user .
But I am Trying to get details for all users .Not only.
Here is model
public function referrer()
{
return $this->belongsTo('App\User', 'referred_by');
}
public function referrals()
{
return $this->hasMany('App\User', 'referred_by');
}
Now I am Getting refferals no from this code.
$referrals=auth()->user()->referrals()->count();
BUt I am Nedd to get same result for every user listing ..
means I need to change this query.by user_id.

This case you must be use withCount() method
$users = User::withCount('referrals')->get();
foreach ($users as $user) {
dd($user->referrals_count);
}

Pass the user_id to an eloquent query
$user_id = request()->get('id'); // Your user_id here
$referrals_count = \App\User::find($user_id)->referrals()->count();
Hope this helps

Related

Laravel Eloquent is there a better way to write this query?

I have a typical pivot table structure like this:
Users
id [...]
Locations
id [...]
User_Location
id | user_id | location_id
I need to get the locations the current authorized user has access to, and then I need to get all the users who also have access to all of those locations.
I tried to figure out an "eloquent" way to do this, but I'm not familiar enough with it. This works, but I'm wondering if it's the best way to do it?
$locations = auth()->user()->locations(); //returns the user_location records
$locationIds = $locations->pluck('location_id');
$locationUsers = new UserLocation();
$userIds = $locationUsers->whereIn('location_id', $locationIds)->groupBy('user_id')->pluck('user_id');
$users = User::withTrashed()
->whereIn('id', $userIds)
->get();
return view('users.index')->with('users', $users);
here's the locations() relationship referenced in the code:
public function locations()
{
return $this->belongsToMany(Location::class, 'user_location')->withPivot('primary');
}
You must create a new method in the Locations model.
public function users()
{
return $this->belongsToMany(User::class, 'user_location');
}
Then your query could look like this.
$locations = auth()->user()->locations()->with('users')->get();
$users = $locations->pluck('users');
If you need to get all users withTrashed then you should modify the first line for this.
$locations = auth()->user()->locations()->with(['users' => function ($user) {
$user->withTrashed();
}])->get();

get user from belongsToMany relationships

I have a service model in October CMS.
In this model, I need to get postman's users (postman is user group) but I am receiving this error:
Trying to get property of non-object
This is my code
public function getPostmanIdOptions()
{
$groups = UserGroup::where('id','4')->lists('name', 'id');
$groups->users;
$list = [' ' => 'choose'] + $groups;
return $list;
}
At the moment, your lists() function will only return the name and the id of each user group. This is used to return thelselect options for the backend select (I am assuming).
What you need to do in this case is return the record based on its id which can be done using the find() eloquent method.
By doing this, the full UserGroup model will be returned, with it's relationships etc.
You're new code should look something like this:
...
$group = UserGroup::find(4);
$users = $group->users;
...
After retrieving the users, you can then using the lists() method if required to:
$list = $group->users->lists('name', 'id');

Relationship with user condition

I have a follow system that works like Twitter's follow (you follow other people and get updates from them).
I have this relationship set in my User.php model:
public function follows()
{
return $this->hasMany('App\Follow');
}
This obviously gets all records of users who follow this person.
However, when displaying the person's profile page, I want to get a relationship that checks if a follow record exists given the user ID.
Something like:
public function userFollow()
{
return $this->hasOne('App\Follow')->where('user_id', Auth::user()->id);
}
So now my profile page query looks like this:
$user = User::where('username', $username)
->with('userFollow')
->first();
This works as long as the user is logged in. If the user isn't logged in, the page gives me this error:
ErrorException in User.php line 28: Trying to get property of
non-object
How do I fix this? What is the proper way of using conditions in relationships?
This is because if user is logged out then Auth::user() is null, because user session has ended. Auth::user() is no more object, so you can't get the id from a null object.
Here you can do something like that
public function userFollow()
{
$userId = Auth::user() ? Auth::user()->id : $this->id;
return $this->hasOne('App\Follow')->where('user_id', $userId);
}
then it will not look for authenticated user, it will just get the particular user table's id.
The proper way of using conditions in relationships is using Constraining eager loads
public function userFollow()
{
return $this->hasOne('App\Follow');
}
And,
if(Auth::check())
{
$user = User::where('username', $username)
->with(['userFollow'=>function($query)
{
$query->where('user_id', Auth::user()->id);
}]);
->first();
}

Filter on related table with Laravel and eloquent

My method is:
public function show(Tag $tag)
{
$posts = $tag->posts;
return view('posts.index',compact('posts'));
}
It works fine but i want to get the posts where posts->user_id is the authenticated user.
public function show(Tag $tag)
{
$posts = $tag->posts()->where('user_id',Auth::user()->id);
return view('posts.index',compact('posts'));
}
How do i filter on the related posts table?
this is a many to many relationship with a pivot table present
What you have should work, but don't forget to get() the results after adding your where:
$posts = $tag->posts()->where('user_id',Auth::user()->id)->get();

How to get related collection in model in Laravel4

Suppose I have a model called User where several relations are defined (role and permissions). How can I get directly in my User model related role collection or related permissions collection ?
What I am trying to do :
controller:
if (Auth::user()->hasPermission('test'))
{ // code goes here}
and my model:
public function hasPermission($name)
{
$permission = \Permission::where('name', '=', $name)->get();
$list = ($this->overwrite_permission) ? $this->permissions : $this->role->permissions;
//here I want to have a collection to use contains()
if ($list->contains($permission))
{
return true;
}
return false;
}
You can do this instead of checking collection:
public function hasPermission($name)
{
return ($this->overwrite_permission)
? (bool) $this->permissions()->whereName($name)->first()
: (bool) $this->role->permissions()->whereName($name)->first();
}
First() will fetch the permission model if it's in the related permissions (to the user or the role appropriately) or return null, thus casting to boolean will do the job.
If you want to use your code anyway, this is the line to change:
// it returns Collection, while you need Model (or its id) for contains() method
$permission = \Permission::where('name', '=', $name)->get();
// change to:
$permission = \Permission::where('name', '=', $name)->first();
Rest of the code is ok, $list is indeed a Collection (unless you have not setup relations to permissions correctly)

Resources