Laravel eloquent multi relations search column - laravel

Trying to figure out how to make a search on a specific table from the below Laravel Eloquent query:
$user = \App\User::with('profile', 'languages', 'contacts', 'photos', 'jobs', 'offices', 'socials')->get();
What I'm trying to filter is a user where in the profile table the 'full_name_slug', '=', 'john-doe'
I've tried forming the where clause like 'profile.full_name_slug', '=', 'john-doe' but without success.
Probably this is quite simple but couldn't figure it out from all the Laravel 5 documentation.
Thanks in advance for any help
Cheers

The right syntax to do
User::whereHas('profile', function ($query) {
$query->where('full_name_slug', '=', 'john-doe');
})->get();

Related

How to do search in eloquent for inner tables in laravel

I want to do filter in laravel eloquent for the inner tables, i have 3 tables, discover, category and subcategory, discover have category and subcategory id, if someone try to filter with any text name, i want to filter from all that 3 tables, i am not able to find, how to filter from category and subcategory table, here is my code, can anyone please help me to resolve this issue ?
$discover = Discover::with(['category','subcategory'])->where('status','1')->where('name','like',"%{$searchString}%")->orWhere('description','like',"%{$searchString}%")->orderBy('created_at', 'DESC')->get()->toArray();
You can do this If you want to filter from child table also
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
$discover = Discover::where('status', '1')
->where('name', 'LIKE', "%$searchString%")
->orWhereHas('category', function ($query) use ($searchString) {
return $query->where('name','LIKE', "%$searchString%");
})
->orderBy('created_at', 'DESC')
->get();
you can constrain eager loading in this way:
Discover::with([
'category' => function($query){
return $query->where('name','your-category-name');
}
])->whereHas('category', function($query) {
return $query->where('name','your-category-name');
});
the same applies for other relationships. Further info can be found on the laravel docs.
has whereHas Or WhereRelation relation
if you need OrderBY on relation tables
then you need to do join

Trouble converting an SQL query to Eloquent

Trying to get this query to work in eloquent
A user can be in multiple teams however I want to generate a list of users NOT in a specific team. The following SQL query works if executed directly but would like to make it cleaner by converting it to eloquent
SELECT * FROM users LEFT JOIN team_members ON team_members.member_id = users.id WHERE NOT EXISTS ( SELECT * FROM team_members WHERE team_members.member_id = users.id AND team_members.team_id = $team_id )
This should provide a list of all the users that are not members of team $team_id
This is a guess ad you do not give much info on your Eloqent models but here is a hint of where to go:
User::doesnthave('teamMembers', function($builder) use($team_id){
return $builder->where('team_members.team_id');
});
That is assuming you have a "User" model with a "teamMembers" relationship setup on it
You may have a closer look in the Laravel docs for doesntHave
Laravel 5.8
Let's assume you have model name "User.php"
& there is method name "teamMembers" in it.
Basic
$users = User::doesntHave('teamMembers')->get();
Advance
use Illuminate\Database\Eloquent\Builder;
$users = User::whereDoesntHave('teamMembers', function (Builder $query) {
$query->where('id', '=', {your_value});
})->get();
You can find details description in this link >>
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-absence
Laravel 5.2
Example:
DB::table('users')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
Check this link for advance where clause:
https://laravel.com/docs/5.2/queries#advanced-where-clauses
You can use below example
$list = User::leftJoin('users', 'users.id', '=', 'team_members.member_id')
->whereNotExists(function ($query) use ($team_id) {
$query->from('team_members')
->whereRaw('team_members.member_id = users.id')
->where('team_members.team_id', '=', $team_id);
})
->get();

How to fetch latest posts and specific post id at first in laravel eloquent

Is there way to fetch latest posts with pagination And I also want a specific post to first position in returned collection.
I tried this...
Post::where(function ($query) {
$query->where('status', 'draft')->orWhere('status', 'published');
})
->orWhere('id', 21)
->with(['author.profile'])
->orderBy('created_at', 'desc')
->paginate(3);
In this query I do get the 21 post id but it is on 3rd page. I want to get it on first place. Please guide How can I do this.
Thanks
You can achieve this by using a raw statement in your orderBy
Post::orderBy(DB::raw('id = 5'), 'DESC')
->orderBy('created_at', 'desc')
This is because mysql can use boolean expressions in order by statements
By using eloquent you do like this
Post::where('id', '=', 21)->orderBy('created_at','desc')->first();

Where clause inside whereHas being ignored in Eloquent

Im trying to make a query using whereHas with eloquent. The query is like this:
$projects = Project::whereHas('investments', function($q) {
$q->where('status','=','paid');
})
->with('investments')
->get();
Im using Laravel 5.2 using a Postgres driver.
The Project model is:
public function investments()
{
return $this->hasMany('App\Investment');
}
The investments model has:
public function project() {
return $this->belongsTo('App\Project');
}
The projects table has fields id,fields...
The investments table has the fields id,project_id,status,created_at
My issue is that the query runs and returns a collection of the projects which have at least one investment, however the where clause inside the whereHas is ignored, because the resulting collection includes investments with status values different than paid.
Does anyone has any idea of what is going on?
I believe this is what you need
$projects = Project::whereHas('investments', function($q) {
$q->where('status','=','paid');
})->with(['investments' => function($q) {
$q->where('status','=','paid');
}])->get();
whereHas wil check all projects that have paid investments, with will eagerload all those investments.
You're confusing whereHas and with.
The with method will let you load the relationship only if the query returns true.
The whereHas method will let you get only the models which have the relationship which returns true to the query.
So you need to only use with and not mix with with whereHas:
$projects = Project::with(['investments' =>
function($query){ $query->where('status','=','paid'); }])
->get();
Try like this:
$projects = Project::with('investments')->whereHas('investments', function($q) {
$q->where('status','like','paid'); //strings are compared with wildcards.
})
->get();
Change the order. Use with() before the whereHas(). I had a similar problem few weeks ago. Btw, is the only real difference between the problem and the functional example that you made.

Paginate based on conditional with relationship

I'm trying to paginate based on a conditional on a relationship. Thought this would work but it does not..
Product::with(['manufacturer' => function($query){
$query->where('name', '=', 'Maker');
}])->paginate(10)->toArray();
for some reason It only works on the first model. I can tell because its the only one loading the manufacturer data.
Anyone have any idea how to do this?
thanks!
Laravel offers convenient way to query relationships (docs)
I think, this is what you want
$products = Product::whereHas('manufacturer', function($q)
{
$q->where('name', '=', 'Maker');
})->get();
You may add pagination and other things as you wish.

Resources