Laravel 5 Eloquent count many to many relationship - laravel-5

Let's say I have table user and roles with many to many relationships using pivot table role_user table.
I'm using belongstomany relationships on my model
How do I make an eloquent query to count how many user has role admin and staff

solved.
add this to Role.php model
public function userCount() {
return $this->belongsToMany(Role::class)
->selectRaw('count(role_user.user_id) as total_user')
->groupBy('role_id');
}
and this
public function getUserCountAttribute()
{
if ( ! array_key_exists('userCount', $this->relations)) $this->load('customerCount');
$related = $this->getRelation('userCount')->first();
return ($related) ? $related->total_user : 0;
}
after that, to make an eloquent query...
$roleUsers = Role::with('userCount')->orderBy('id', 'asc')->get();

Related

How to use where in laravel relationships?

I have a relationship on Orders and Customers.
a row from customers table :
customer_id
customer_name
customer_state
customer_city
1
Amin
Yazd
Yazd
a row from orders table :
order_id
customer_id
product_id
factor_id
1
1
3
4
Now I want order rows where customer_state is yazd.
Order.php
public function customer()
{
return $this->belongsToMany(Customer::class, 'orders', 'order_id', 'customer_id');
}
OrdersController.php
$state = "Yazd";
$reportItem = Order::whereHas("customer", function ($query) use ($state) {
$query->where('customer_state', $state)->get();
});
It doesn't work. How I can handle this?
What I understand from the given input you're not using the proper relation here:
The belongsToMany relation is used for many-to-many relations using an allocation table. But you are actually using a one-to-many relation => one customer can have many orders.
In this case you should use a belongsTo relation on Order Model or/and a hasMany relation on Customer Model:
// Order.php
public function customer() {
return $this->belongsTo(Customer::class)
}
// Customer.php
public function orders() {
return $this->hasMany(Order::class)
}
You have put get() at the wrong place. Change this
$reportItem = Order::whereHas("customer", function ($query) use ($state) {
$query->where('customer_state', $state)->get();
});
To
$reportItem = Order::whereHas("customer", function ($query) use ($state) {
$query->where('customer_state', $state);
})->get();
Learn more about laravel relations

Laravel Eloquent ORM hasMany where other pivoted relationship exists

I would like to query all models of a hasMany relationship that also have a pivoted relationship with a specified other model.
Example:
Customer:
belongsToMany -> Entry
EntryGroup:
hasMany -> Entry
Entry:
belongsToMany -> Customer
belongsTo -> EntryGroup
The belongsToMany relationship between Customer and Entry is stored in a pivot table.
I now want to collect the relationship to all Entries that belong to a specified Customer on an EntryGroup. Without this filtering restriction, I would have a function like
class EntryGroup extends Model
{
...
public function entries()
{
return $this->hasMany(Entry::class);
}
}
Thanks in advance for any suggestions you might have.
try this one
$customers->entries()->with('entryGroup')->get();
Try This:
<?PHP
$customerId = 5;
Entry::whereHas('customer', function ($query) use ($customerId) {
$query->where('id', $customerId);
})->has("EntryGroup")->get();
This return all the entry has a entrygroup and belong to customer id 5
Try this:
$entryGroup->entries()->whereHas('customer', function ($query) use ($customerId) {
$query->where('customers.id', $customerId);
})->get();

A department can belongsToMany, but a user can only belongTo department? How to pivot this correctly?

So im trying to figure out how to use pivot tables in Laravel. And I have tried to read and understand the documentation. And I cannot understand why a user just can't balongTo a "department". I don't want a user to belongToMany "departments".
Departments model
public function users()
{
return $this->belongsToMany(User::class, 'department_user', 'user_id', 'department_id');
}
And for the user model, I want something like
public function department()
{
return $this->belongsTo(Department::class);
}
But Laravel reports null. Because department_id doesn't exist in the users row? How can I reverse this pivot table lookup, with belongsToMany and belongsTo?
I think you're getting confused with your relationship types. If I understand you correctly:
A Department hasMany Users.
A User belongsTo a Department.
This one-to-many relationship type does not need a pivot table and can be written as such:
class Department extend Eloquent
{
public function users()
{
return $this->hasMany(User::class);
}
}
class User extend Eloquent
{
public function department()
{
return $this->belongsTo(Department::class);
}
}
This would require that the users table have a department_id foreign key.

How to fetch data from multiple table using eloquent in laravel 5.3?

I want to build query like this in laravel 5.3
SELECT p.post_text, p.bbcode_uid, u.username, t.forum_id, t.topic_title, t.topic_time, t.topic_id, t.topic_poster
FROM phpbb_topics t, phpbb_posts p, phpbb_users u
WHERE t.forum_id = 9
AND p.post_id = t.topic_first_post_id
AND u.user_id = t.topic_poster
ORDER BY t.topic_time
DESC LIMIT 10
Consider for example there are two tables one is users and the other is posts
while creating migration add user_id foreign key to your posts table as
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
create User and Post model, and in your User model define relationship to Post as
public function post(){
return $this->hasMany(Post::class);
}
and in your Post model define a relationship to User model as
public function user(){
return $this->belongsTo(User::class);
}
now you can get the user from Post model
$post = Post::findOrFail(1);
return $post->user;

Laravel 5.1 - Querying pivot table using eloquent

I am using laravel 5.1 for a CMS development. I have a simple structure of posts, users and users can like posts.
Posts and Users have many-to many relationship and use a pivot table for relationship.
Posts Model has
public function likedby()
{
return $this->belongsToMany('App\Models\User','user_like_post')
->withTimestamps();
}
User Model has
public function likes(){
return $this->belongsToMany('App\Models\Post','user_like_post')
->withTimestamps();
}
I want to list the latest activity of the users. For e.g.
Username1 likes Post2
Username5 likes Post9
Username30 likes Post25
I know I have to write an sql query like this -
mysql > select users.name, posts.heading from user_like_post as ulp
> join users on ulp.user_id=users.id
> join posts on ulp.post_id=posts.id
> order by ulp.created_at desc limit 10;
The above query works fine but is there a way to do it using laravel eloquent?
If you want pure eloquent solution, then you need additional model for the pivot table:
class PostUser extends Model {
protected $table = 'user_like_post';
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
// then something like this
$activity = PostUser::latest()->take(10)->get();
#foreach ($activity as $action)
{{ $action->user->name }} likes {{ $action->post->title }}
#endforeach
Other than that you would need joins in order to sort the results by pivot table.

Resources