Laravel 4 Eloquent table join and where clause on multiple tables - php

Hi I'm using Laravel and Eloquent in order to store users, there profile and there assigned roles. My table structure is as follows;
users
id | username | email | password | created_at | updated_at
profiles
id | user_id | firstname | created_at | updated_at
roles
id | name
assigned_roles
id | user_id | role_id
I'm trying to select all users where there role name is equal to admin. But when I do the following I get an empty array:
return \User::with('profile')->join('assigned_roles', function ($join) {
$join->where('assigned_roles.user_id', '=', 'users.id');
})->get();
Any ideas what I'm doing wrong?
Also I am using Zizaco Entrust and Confide https://github.com/Zizaco/entrust/tree/1.0

In order to fetch users that have admin role you need to use Eloquent's whereHas() method:
$admins = \User::with('profile')
->whereHas('assigned_roles', function($query) {
$query->whereName('admin');
})
->get();
I assume you have assigned_roles relation defined. If not, add many-to-many relation between your users and roles:
public function assigned_roles() {
return $this->belongsToMany('\Your\Model\Namespace\Role', 'assigned_roles', 'user_id', 'role_id');
}

Related

How I get users which are created by Auth::user

I have two table users and customer_details. I want to get users which are created by Auth::user(). The created_by column is in customer_details table.
User Table
| id | name | email | status |
|-----------------------------------------------|
| 1 | Admin | admin#email.com | Active |
| 2 | Customer | user#email.com | Active |
CustomerDetails Table
| id | user_id | added_by | address |
|-------------------------------------------|
| 1 | 2 | 1 | NY City |
This is my query
$customers = User::role('Customer')->whereIn('status', ['Active'])->get();
Want to get records where added_by is current auth user
$customers = User::role('Customer')->whereIn('added_by', Auth::id())->get();
I think this should help
here we are using Auth::id() to get the id of the current user and then using eloquent to search for it.
I am considering that here added_by column contains the ID;
Create a relation in your CustomerDetail model:
public function addedBy()
{
return $this->belongsTo(User::class, 'added_by');
}
Then, you can query using this relation:
CustomerDetail::whereHas('addedBy', function($query) {
return $query->where('id', auth()->id());
})->get();
This query returns all customer created by the user current logged in.
To get all users with it's customers created by the current logged in user, add a new relation, now to the user model:
public function customerDetail()
{
return $this->hasOne(CustomerDetail::class, 'added_by');
}
and query users with customers created byt the logged in user:
User::role('Customer')->whereHas('customerDetail', function($query) {
return $query->where('added_by', auth()->id());
})
->whereIn('status', ['Active'])
->get();

How to get all rows from database by a foreign key value with Eloquent?

I use Laravel on my website and Eloquent to manage my database. I have users with roles. This looks like this in my database :
|USERS |
|----------------------------------|
| ID | EMAIL | ... | ROLE_ID | ... |
|ROLES |
|------------|
| ID | LABEL |
I would like to select user by their role label.
I tried to use joins and where functions but I don't know why the returned users have their ID set with their ROLE_ID.
$admins = DB::table('users')
->leftJoin('roles', 'users.role_id', '=', 'roles.id')
->where('roles.label','=', 'admin')
->get();
Here is one of the user returned :
object(stdClass)[285]
public 'id' => int 3
...
public 'role_id' => int 3
...
The ID of this user is 2 in the database. If I change it's ROLE_ID to 1, it's ID also change to 1.
I looked for solutions on the internet but I don't really know what to look for so I did not find anything.
I am sure this is quite simple but I am stuck anyway.

Laravel 5: How to do a join query on a pivot table using Eloquent?

I have 2 tables in my Laravel application namely customers and stores. Customers can belong to many stores and stores can have many customers. There's a pivot table between them to store that relation.
Question is, how do I extract the list of customers for a given store using Eloquent? Is it possible? I am currently able to extract that using Laravel's Query Builder. Here is my code:
| customers | stores | customer_store |
-------------------------------------------
| id | id | customer_id |
| name | name | store_id |
| created_at| created_at | created_at |
| updated_at| updated_at | updated_at |
Customer Model:
public function stores(){
return $this->belongsToMany(Store::class)
->withPivot('customer_store', 'store_id')
->withTimestamps();
}
Store Model:
public function customers(){
return $this->belongsToMany(Customer::class)
->withPivot('customer_store', 'customer_id')
->withTimestamps();
}
DB Query (using Query Builder):
$customer = DB::select(SELECT customers.id, customers.name, customers.phone, customers.email, customers.location FROM customers LEFT JOIN customer_store on customers.id = customer_store.customer_id WHERE customer_store.store_id = $storeID);
Try this one:
public function result(Request $request) {
$storeId = $request->get('storeId');
$customers = Customer::whereHas('stores', function($query) use($storeId) {
$query->where('stores.id', $storeId);
})->get();
}
Try executing this...
$result = Customer::with('stores')->get();
Hope this helps.
To know more about Eloquent Relationship refer: https://laravel.com/docs/5.1/eloquent-relationships
Try below:
Here Customers is your model and $storeID is your store id. $storeID is outside of the scope of your callback. So you must use the use statement to pass them.
Customers::leftJoin('customer_store', function($join) use($storeID){
$join->on('customers.id', '=', 'customer_store.customer_id')
->where('customer_store.store_id','=', $storeID);
})
->whereNotNull('customer_store.store_id')//Not Null Filter
->get();
Hope this help you!

Laravel join query using Laravel eloquent

i have two tables 'users' and 'projects'
Table users
-----------------------------------
user_id | name | email | password |
-----------------------------------
1 |name1 |email1 | password1|
-----------------------------------
2 |name2 |email2 | password2|
Table projects
project_id |user_id | name |
--------------------------------------
1 | 1 | project_name1 |
-----------------------------------
2 | 1 | project_name2 |
There is no relation between these two tables but user_id in projects are the id from user table.
Normal Query
SELECT a.user_id,a.name AS username,b.name AS project_name FROM users a LEFT JOIN projects b ON a.user_id=b.user_id;
I want the same query execution in laravel eloquent.
Have searched in google got some idea about "with" function but not able to get the output.
Thanks.
This is the way you should use Eloquent:
create User.php
<?php
class User extends Eloquent
{
public function projects()
{
return $this->hasMany('Project');
}
}
create Project.php
<?php
class Project extends Eloquent
{
}
On controller, write this to get all users, with related projects inserted inside each users:
$users = User::with('projects')->all();
foreach($users as $user)
{
$project_of_this_user = $user->projects;
}
You can simply do as following,
DB::table('users')
->join('projects =', 'users.id', '=', 'posts.user_id')
->select('*')
->get();
For more details you can refer laravel Docs
This should be what you need:
DB::table('users')
->join('projects', 'projects.user_id', '=', 'users.user_id')
->select('users.user_id', 'users.name as username', 'projects.name as project_name')
->get();
I think, this one helps you out
DB::table('users')
->leftJoin('projects', 'users.user_id', '=', 'projects.user_id')
->select('users.user_id', 'users.name as username', 'projects.name as project_name')
->get();

Get posts from following Laravel Eloquent

I am building a social network where the user will have a stream like Twitter of all the posts from the people that they follow.
What is the best way to query this with Laravel Eloquent?
I have 3 tables
users
id | username | etc...|
relationships
id | user_id |follows_id |
posts
id | user_id | post|
You may try something like this (Basic Idea):
users
id | username | etc...
posts
id | user_id | post_content
favorites (relationships)
id | user_id |post_id
Define the Post class something like this:
class Post extends Eloquent {
//...
public function favorites()
{
return $this->hasMany('Favorite');
}
}
Define the favorite class:
class Favorite extends Eloquent {
// ...
}
Query for the posts:
$posts = Post::whereHas('favorites', function($q) {
$q->where('user_id', Auth::user()->id);
})->get();

Categories