Use of where constraint in laravel eloquent ORM - php

I understood that Laravel's Eloquent ORM queries generally had the structure
The model
Query Constraints
Fetch methods.
However, can someone tell me what this code would do?
$user = User::where('username', '=', $username)->where('active', '=', 1);
It seems to have 2 constraints, but no fetch method,
for example I would expect the query to have
->first() or
->update(array('key' => 'value') or
->delete()
or similar on the end?

The code only sets up the query with the two mentioned where clauses. This is useful when you want to add clauses depending on different conditions:
$user = User::where('username', '=', $username)
->where('active', '=', 1);
if ($filterByAge) {
$user->where('age', '>', $age);
}
if ($filterByHeight) {
$user->where('height', '>', $height);
}
return $user->get();
Or when you're applying them from, let's say, an array:
$wheres = [
'username' => 'Raphael',
'active' => true,
'height' => '173'
];
$user = User::query();
foreach ($wheres as $field => $value) {
$user->where($field, '=', $value);
}
return $user->get();

Related

how to use Laravel 8 query builder like eloquent for searching

I'm developing a simple CRM with Laravel 8 that needs to search in query string.
My query string would be look like:
http://127.0.0.1:8000/admin/users/supervisor?q=john&gender=m
Now the problem is how can I search in controller?
I want to do like this:
public function index (Request $request)
{
$role = getRoleCode($request->role);
$roles = Role::where('role', '=', $role);
if ($request->q) {
$roles->where('name', 'like', "%$request->$q%");
}
if ($request->gender) {
$roles->where('gender', '=', $request->gender);
}
$role->orderBy('id', 'desc')->paginate(20);
return view('admin.users.index', [
'roles' => $roles,
'role_name' => config('settings.roles')[$role],
'role_en_name' => $request->role,
'q' => $request->q,
'gender' => $request->gender
]);
}
I wonder why its not working and what is the standard way to do this.
I've tried:
Role::query();
but that didn't work either.
I've also tried:
$roles = Role::where('role', '=', $role)
->where('name', 'like', "%$request->$q%")
->where('gender', '=', $request->gender)
->orderBy('id', 'desc')
->paginate(20);
This codes works perfectly but we may not be sending the "q" or "gender" URL params.
PS: Sorry for my bad English :)
If you want to conditionally add where statements to your query you can use the if statements like you are attempting to do or use the when method of the Eloquent/Query Builder:
$roles = Role::where('role', $role)
->when($request->input('q'), fn ($query, $search) => $query->where('name', 'like', '%'. $search .'%'))
->when($request->input('gender'), fn ($query, $gender) => $query->where('gender', $gender))
->orderBy('id', 'DESC')
->paginate(20);
Laravel 8.x Docs - Queries - Conditional Clauses when
work with when() it's better
->when(true, function($query){$query->where('x', x);})

Laravel Eloquent: How to add where condition from the with function model relation

Anyone can help me? How to add where condition from the with function model relation.
I tried ->where('driver.group_id',$group_id) but it does not work. please look my code below.
public function getDriversDailyEarnings()
{
$group_id = Auth::user()->group->id;
$today = Carbon::today();
$data = DailyEarnings::with(['payout_cost',
'status:id,name',
'driver' => function ($query) {
$query->with('user');
}])
->where('driver.group_id',$group_id)
->whereDate('created_at', $today)
->get();
return response()->json($data, 200);
}
You can try this. Haven't tested it yet.
DailyEarnings::with([
'payout_cost',
'status:id,name'
'driver' => function($query) {
$query->where('group_id', auth()->user()->group->id)->with('user');
}
])
->whereHas('driver', function($query) {
$query->where('group_id', auth()->user()->group->id);
})
->whereDate('created_at', now()->format('Y-m-d'))
->get();
To pass other clauses to a relation, just use it inside an array, where the key and the name of the relation and the value is a function that receives an instance of the query, something like this:
public function getDriversDailyEarnings()
{
$data = DailyEarnings::with([
'payout_cost' => function ($myWithQuery) {
$myWithQuery->where('column-of-relation-here', 'value-here')
->orWhere('name', 'LIKE', '%Steve%');;
}
])->get();
return response()->json($data, 200);
}
Perhaps something like this:
// ->where('driver.group_id',$group_id)
->whereHas('driver', fn($qry) => $qry->where('group_id', $group_id)) // if group_id a field on driver

How to include or exclude where statement in Laravel Eloquent

I need the same query for two different user roles. Difference is only in one whereNotIn condition.
So for the Basic user it would be:
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->whereNotIn('ChannelName', $sky)
->get();
And for Premium:
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->get();
I know I can do it with simple if statement:
if($user->userRole == "Basic"){
//first $chart2
}
else{
//second $chart2}
but I have a lots of queries where I need just to add or remove this whereNotin condition and rewriting the queries (using if statement) is not a nice solution.
Try scope.
In your TVModel.php:
public function scopeConditionalWhereNotIn($query, $doesUse, $col, $val) {
if($doesUse)
$query->whereNotIn($col, $val);
}
Usage:
$condi = true;//or false.
$chart2 = TVModel::select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->conditionalWhereNotIn($condi, 'ChannelName', $sky)
->get();
Inside your model add this:
public function scopeBasicUser($query,$channel){
return $query->whereNotIn('ChannelName', $channel);
}
and in your controller:
$query = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid);
if($user->userRole == "Basic")
$query = $query->basicUser($channel);
return $query->get();
$userRole = $user->userRole;
$chart2 = DB::connection('mysql2')->table('tv')
->select('*')
->join('epgdata_channel', 'cid', '=', 'channelid')
->where('ReferenceDescription', $campaign->spotid)
->where(function ($query) use ($userRole){
if($userRole == "Basic"){
$query->whereNotIn('ChannelName', $sky)
}
})
->get();
This code worked for me.

Laravel two wherehas queries not working

I would like to assign a group to users which have a role student and have also a particular selected group. There is a users table, which has pivot tables: role_user and group_user with roles and groups tables. Below is the code for the controller where I am trying to execute the query:
$this->validate($request, [
'add-group' => 'required',
'where-group' => 'required'
]);
$selectedGroup = $request->input('add-group');
$whereGroupId = $request->input('where-group');
$users = User::whereHas('roles', function($q) {
$q->where('name', 'student');
})->whereHas('groups', function($q) {
$q->where('id', $whereGroupId);
})->get();
$selectedGroup = Group::whereId($selectedGroup)->first();
$users->assignGroup($selectedGroup);
You need to use the orWhereHas clause for the second half of the query.
Secondly, your $whereGroupId variable is not in the inner-function's scope, add a use($whereGroupId) statement to include it in the function's scope.
$users = User::whereHas('roles', function($q) {
$q->where('name', 'student');
})->orWhereHas('groups', function($q) use ($whereGroupId) { // <-- Change this
$q->where('id', $whereGroupId);
})->get();
You had syntax error and a missing use to pass whereGroupId. I have no clue what assignGroup does, but this should fix the code you have.
$this->validate($request, [
'add-group' => 'required',
'where-group' => 'required'
]);
$selectedGroup = $request->input('add-group');
$whereGroupId = $request->input('where-group');
$users = User::whereHas('roles', function ($q) {
$q->where('name', 'student');
})
->whereHas('groups', function ($q) use ($whereGroupId) {
$q->where('id', $whereGroupId);
})->get();
$selectedGroup = Group::whereId($selectedGroup)->first();
$users->assignGroup($selectedGroup);

Return a specific column from a many-many relationship using php in laravel

In my database I have two models, User and Role defined as many-many relationship, I'm trying to write a code in laravel that takes the id from the roles table and gets all the user fullnames from the users table.
I have defined a route that looks like this :
Route::get('roleUser/{role}', 'RoleController#RoleNames');
in which i pass the role name with it, as you see above
In my RoleController, I defined the method roleNames to do the job
public function RoleNames($role)
{
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->first()->id;
$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(array('id'));
$usersUnderRole = array();
foreach ($iduser as $idusers) {
$usersUnderRole = array_add($usersUnderRole, $idrole, $idusers);
$full_name = DB::table('users')->where('id', '=', $idusers)->get()->full_name;
}
return $this->respond([
'result' => $this -> roleTransformer->transform($full_name)
]);
}
This code is meant to take the role_id from the roles table and gets the appropriate user_ids by the pivot table assigned_roles, puts them in an array and fetches the correspondent full_names, but it says this error:
Object of class stdClass could not be converted to string
Any advice on how to get it to work?
This will give you all the users who belong to the given role:
$role_id = 3;
$result = DB::table('role_user')
->select('users.full_name')
->where('role_user.role_id', $role_id)
->leftJoin('users', 'users.id', '=', 'role_user.user_id')
->get();
var_dump($result);
$full_names = DB::table('users')->where('id', '=', $idusers)->lists('users.full_name');
Besides the solution #lamzazo provided, there is another way to go with the answer :
$role2 = Role::where('name', '=', $role)->first();
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole);
$user = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get();
// $user = DB::table('users')->where('id', '=', $iduser);
// return $this->respond($iduser[0]->user_id);
$userArray = array();
$i=0;
foreach ($user as $users) {
$iduser= $users->user_id;
$allusers = User::where('id', '=', $iduser)->get(array('id', 'full_name'));
$userArray = array_add($userArray, $i . '', $allusers);
$i++;
}
return $this->respond([
'result' => $this -> roleTransformer->testTransform($role2, $userArray)
]);

Categories