Laravel apply pagination based on condition in query - laravel

I am using laravel eloquent for db operation. I create a done function in that I want to apply my pagination if the variable has value if the variable value is not found then it should use laravel get() method. Here is my code
$query = DB::table('mytable')
->when($searchBy != null, function ($query) use ($searchBy) {
return $query->where('mytable.id', '=', $searchBy)
->orWhere('orders.id', '=', $searchBy)
})
->orderBy('mytable.id', 'desc')
->paginate($recordsPerPage, ['*'], 'page', $pageNub);
I want to add pagination if $recordsPerPage variable is > 0, otherwise it should be use get() method

You would assign the builder to a variable and use some type of conditional here:
$query = DB::table('mytable')
->when($searchBy, function ($query, $searchBy) {
return $query->where('mytable.id', '=', $searchBy)
->orWhere('orders.id', '=', $searchBy)
})->orderBy('mytable.id', 'desc');
$result = ($recordsPerPage > 0) ?
$query->paginate(...) :
$query->get();

Related

Laravel 8 - How to use where conditions for relation's column

hello friends can you help me to get the contents of $filter? I want to run where which is where the target column is in the relation array
$filter = $request->get('Biogear');
$data = DetailBarang::with(['barang' => function ($q) use ($filter) {
$q->where('brand', '=', $filter);
}])->get();
return response()->json($data);
you can try this
$filter = $request->get('Biogear');
$data = DetailBarang::with('barang')->whereHas('barang',function (Illuminate\Database\Eloquent\Builder $q) use ($filter) {
$q->where('brand', '=', $filter);
})->get();
return response()->json($data);

Laravel when clause is throwing undefined variable

I am trying to make a conditional where, inside a select statement. It is throwing undefined variable 'class_id'. What is going wrong here. The variable class_id got some value but is throwing 'Undefined variable: class_id'.
$class_id = isset($searchData[1]) ? $searchData[1] : '';
\Log::info($class_id);
$students = \User::where('role', 'student')
->where('fullName', 'like', '%'.$student_name.'%')
->orWhere('username', 'like', '%'.$student_name.'%')
->orWhere('email', 'like','%'.$student_name.'%')
->when($class_id != '',
function ($q) {
return $q->where('studentClass', '=', $class_id);
})
->get();
You are using the wrong syntax for when(). You are using it in the perfect scenario, and you can omit initializing the variable above.
Laravel 5.2 -> 5.5
$class_id = isset($searchData[1]) ? $searchData[1] : '';
$students = \User::where('role','student')
->where('fullName','like','%'.$student_name.'%')
->orWhere('username','like','%'.$student_name.'%')
->orWhere('email','like','%'.$student_name.'%')
->when($class_id, function ($query) use ($class_id) {
return $query->where('studentClass','=', $class_id);
})->get();
Laravel 5.6+
$students = \User::where('role','student')
->where('fullName','like','%'.$student_name.'%')
->orWhere('username','like','%'.$student_name.'%')
->orWhere('email','like','%'.$student_name.'%')
->when($searchData[1], function ($query, $class_id) {
return $query->where('studentClass','=', $class_id);
})->get();

How to add and exclude where() clause in laravel query builder

How to add and exclude where() clause in laravel query builder so that in one case it will be added in other one no
$orders = DB::table('orders')->select(
'orders.id as id',
'orders.created_at as created',
'u.email as email',
'ud.id as data_id',
'ud.firstName as firstName',
'ud.lastName as lastName',
'ud.phone as phone',
's.name as service',
's.id as service_id',
'pt.id as payment_type_id',
'pt.name as payment_name')
->join('users as u', 'orders.user_id', '=', 'u.id')
->join('user_data as ud', 'u.id', '=' ,'ud.user_id')
->join('payment_types as pt', 'orders.payment_type_id', '=', 'pt.id')
->join('services as s', 'orders.service_id', '=', 's.id')
->where('u.id', $user->id)->orderBy($sortBy, $type)->get();
I want to do this
$order = DB::table()....
if(true){
$order->where('id', '=', 1);
}
$order->orderBy('fieldname', 'asc')->get();
But the example above return no results
For conditional clauses you can make use of when().
$order = DB::table()
->yourQuery(...)
->when($var, function ($query, $var) { // <----
return $query->where('id', '=', 1); // <----
} // <----
->orderBy('fieldname', 'asc')
->get();
You can read more about this in the docs:
Conditional Queries
Sometimes you may want clauses to apply to a query only when something
else is true. For instance you may only want to apply a where
statement if a given input value is present on the incoming request.
You may accomplish this using the when method:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();
The when method only executes the given Closure when the first
parameter is true. If the first parameter is false, the Closure will
not be executed.
...

Laravel OrWhere having two conditions is not so obvious

Why in Eloquent a simple query as this one is not working?
$matches = DB::table("matches")
->where(["team_a"=> $request->tid, "match_tipo"=>3])
->orWhere(["team_a"=> $request->tid, "match_tipo"=>3])
->first();
According to with other examples here on Stackoverflow, I should use a query in Where like:
$matches = DB::table("matches")
->where(["match_tipo"=>3])
->where(function($query, $request) {
$query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
But I should pass a second parameter ($request).
How is the simplest way to do this query?
You can make this as like this.
->where(["match_tipo"=>3]) this will be ->where("match_tipo",3) and use($tid) after query.
$tid = $request->tid;
$matches = DB::table("matches")
->where("match_tipo",3)
->where(function($query) use($tid) {
$query->where('team_h',$tid)
->orWhere('team_a',$tid);
})
->get();
while using the Callback or Closure as the where function Parameter you will only the one argument which is Current Object
Methods Can used to Pass the $request
Method One
$matches = DB::table("matches")
->where(["match_tipo"=>3])
->where(function($query) use ($request) {
$query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
Method Two
$matches = DB::table("matches")
->where('match_tipo','=',3)
->when($request->tid,function($query) use ($request) {
return $query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
Try this query :
$matches = DB::table("matches")
->where('match_tipo',3)
->whereRaw('team_a = "'.$request->tid.'" OR team_h = "'.$request->tid.'"')
->first();

Laravel remove parent if related collection

I have a model with a related collection
now im doing this query
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get();
Now i am wondering. If the orders returns empty is it posible to remove this parent from the collection?
I Know i can do this after the eloquent query with a loop. But is it possible to do this in the query?
we cant completely remove that parent ( with index ) BUT you can set those to null using transform() like this;
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get()->transform(function($item){
if(!$item->orders->count() ){
return;
}
return $item;
});
Note: this will not completely remove those parents but it will set them to empty.

Resources