Filters in laravel5.4 - laravel

In case I have filter users with location and date,I have written query like below
public function searchConsultants()
{
$location = $request->get('location');
$fromDate = $request->get('from_date');
$toDate = $request->get('to_date');
$data = DB::table('consultants')
->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location')
->where('location','LIKE','%'.$location.'%')
->whereBetween('date',[$fromDate,$toDate])
->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id')
->groupBy('consultants.id')
->orderBy('avg_rating', 'DESC')
->get();
}
With above query I can get data but sometimes I dont want to search with date I want search only with location,
The problem in above query I must enter location and date to filter users,So How can I filter with only location or date.

Use orWhere read it at https://laravel.com/docs/5.4/queries#where-clauses
public function searchConsultants()
{
$location = $request->get('location');
$fromDate = $request->get('from_date');
$toDate = $request->get('to_date');
$data = DB::table('consultants')
->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location')
->where('location','LIKE','%'.$location.'%')
->orwhereBetween('date',[$fromDate,$toDate])
->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id')
->groupBy('consultants.id')
->orderBy('avg_rating', 'DESC')
->get();
}

You should try this:
public function searchConsultants()
{
$location = $request->get('location');
$fromDate = $request->get('from_date');
$toDate = $request->get('to_date');
$data = DB::table('consultants')
->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location')
->whereBetween('date',[$fromDate,$toDate])
->orWhere('location','LIKE','%'.$location.'%')
->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id')
->groupBy('consultants.id')
->orderBy('avg_rating', 'DESC')
->get();
}

Related

multiple search option in laravel model with join

i want to create a multiple search option but it gives me error when i try to search
this is my code by the way
Controller
$leaves = DB::table('leaves_admin')
->join('users','users.rec_id', '=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.role_name','users.avatar')
->get();
$userList = DB::table('users')->get();
// search by name
$search = request('name');
$leaves = LeaveAdmin::join('users','users.rec_id','=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.avatar')
-> where('leaves_admin.name','LIKE','%'.$search.'%')
->get();
// search by status
$search = request('status');
$leaves = LeaveAdmin::join('users','users.rec_id','=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.avatar')
-> where('leaves_admin.status','LIKE','%'.$search.'%')
->get();
return view('Leave.leaves', compact('leaves'));
As per my understanding of your code that you are looking for a solution for multiple filters and I am assuming that all columns are present in the same Query, so I will promote that solution for you.
$name = (request('name')) ? request('name') :'';
$status = (request('status')) ? request('status') :'';
$query = DB::table('leaves_admin')
->join('users','users.rec_id', '=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.role_name','users.avatar');
if(!empty($name) && !empty($status) ) {
$query->where('leaves_admin.name','LIKE','%'.$name.'%');
$query->where('leaves_admin.status','LIKE','%'.$status.'%');
}elseif (!empty($name)) {
$query->where('leaves_admin.name','LIKE','%'.$name.'%');
}elseif (!empty($status)) {
$query->where('leaves_admin.status','LIKE','%'.$status.'%');
}
$leaves = $query->get()->toArray();
return view('Leave.leaves', compact('leaves'));

Laravel groupBy date get total column

I want to report before the selected date and the entered day. Dates that are not before the selected date and the number of days are also coming. I don't want empty dates to appear and I want to show the total column data in the database for that date. Where am I doing wrong?
I want to make a comparison between incoming values to change the table background-color
Database Structure
Table Structure
public function listByDaily(Request $request)
{
$endDate = $request->date('date') ?? today();
$startDate = $endDate
->copy()
->subDays($numberofdays);
$dates = CarbonPeriod::create($startDate, $endDate);
$transactions = Transactions::whereBetween('date', [$startDate, $endDate])
->select('product_id', 'supplier_id', 'total', 'date')
->latest('date')
->get();
$productIds = $transactions
->pluck('product_id')
->unique()
->values()
->toArray();
$supplierIds = $transactions
->pluck('supplier_id')
->unique()
->values()
->toArray();
$productselect = Product::whereIn('id', $productIds)
->select('id', 'product_name')
->pluck('product_name', 'id');
$suppliers = Supplier::whereIn('id', $supplierIds)
->select('id', 'supplier_name')
->get();
$columns = collect($transactions)
->whereNotNull('date')
->groupBy('date','DESC')
->map(function($items) {
return $items
->groupBy('product_id','total');
})
->pluck('total');
//dd($columns);
/*->toArray();*/
$products = Transactions::join('products', 'products.id', '=', 'transaction.product_id')->get()->unique();
return view('transactions.reportbydates', compact('products', 'productIds', 'dates', 'suppliers', 'columns'));
}

Laravel query groubBy condition

I have a dB query where I would like to groupBy() only when conditions are met without using union because of pagination.
Unfortunately groupBy() seems to only work when called on the entire query outside of the loop.
This was made for dynamic filtering from $filterArr. Depending on the array I need to select from different columns of the table.
When the $key=='pattern' I would need the distinct results from its column.
the query looks something like this
select `col_1`, `col_2`, `col_3`
from `mytable`
where (`color` LIKE ? or `pattern` LIKE ? or `style` LIKE ?)
group by `col_2` //<< i need this only for 'pattern' above and not the entire query
Heres the model:
// $filterArr example
// Array ( [color] => grey [pattern] => stripe )
$query = DB::table('mytable');
$query = $query->select(array('col_1', 'col_2', 'col_3'), DB::raw('count(*) as total'));
$query = $query->where(function($query) use ($filterArr){
$ii = 0;
foreach ($filterArr as $key => $value) {
if ($key=='color'){
$column = 'color';
}else if ($key=='style'){
$column = 'style';
}else if ($key=='pattern'){
$column = 'pattern';
$query = $query->groupBy('col_2'); // << !! does not work
}
if($ii==0){
$query = $query->where($column, 'LIKE', '%'.$value.'%');
}
else{
$query = $query->orWhere($column, 'LIKE', '%'.$value.'%');
}
$ii++;
}
});
$query = $query->orderBy('col_2', 'asc')->simplePaginate(30);
I think you can simplify your code a bit:
$query = DB::table('mytable');
$query = $query->select(array('col_1', 'col_2', 'col_3'), DB::raw('count(*) as total'));
$query = $query->where(
collect($filterArr)
->only(['color','style','pattern'])
->map(function ($value, $key) {
return [ $key, 'like', '%'.$value.'%', 'OR' ];
})->all()
)->when(array_key_exists('pattern', $filterArr), function ($query) {
return $query->groupBy('col_2');
});
$query = $query->orderBy('col_2', 'asc')->simplePaginate(30);

Laravel filter of multiple variables from multiple models

Goodmorning
I'm trying to make a filter with multiple variables for example I want to filter my products on category (for example 'fruit') and then I want to filter on tag (for example 'sale') so as a result I get all my fruits that are on sale. I managed to write seperate filters in laravel for both category and tag, but if I leave them both active in my productsController they go against eachother. I think I have to write one function with if/else-statement but I don't know where to start. Can somebody help me with this please?
These are my functions in my productsController:
public function productsPerTag($id){
$tags = Tag::all();
$products = Product::with(['category','tag','photo'])->where(['tag_id','category_id'] ,'=', $id)->get();
return view('admin.products.index',compact('products','tags'));
}
public function productsPerCategory($id){
$categories = Category::all(); //om het speciefieke id op te vangen heb ik alle categories nodig
$products = Product::with(['category','tag','photo'])->where('category_id', '=', $id)->get();
return view('admin.products.index',compact('products','categories'));
}
These are my routes in web.php. I guess this will also have to change:
Route::get('admin/products/tag/{id}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Route::get('admin/products/category/{id}','AdminProductsController#productsPerCategory')->name('admin.productsPerCategory');
For filter both
change your URL like
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Make your function into the controller like
public function productsPerTag($tagId = null, $categoryId = null){
$tags = Tag::all();
$categories = Category::all();
$query = Product::with(['category','tag','photo']);
if ($tagId) {
$query->where(['tag_id'] ,'=', $tagId);
}
if ($tagId) {
$query->where(['category_id'] ,'=', $categoryId);
}
$products = $query->get();
return view('admin.products.index',compact('products','tags', 'categories'));
}
You are trying to filter in your query but you pass only 1 parameter to your controller, which is not working.
1) You need to add your filters as query params in the URL, so your url will look like:
admin/products/tag/1?category_id=2
Query parameters are NOT to be put in the web.php. You use them like above when you use the URL and are optional.
2) Change your controller to accept filters:
public function productsPerTag(Request $request)
{
$categoryId = $request->input('category_id', '');
$tags = Tag::all();
$products = Product::with(['category', 'tag', 'photo'])
->where('tag_id', '=', $request->route()->parameter('id'))
->when((! empty($categoryId)), function (Builder $q) use ($categoryId) {
return $q->where('category_id', '=', $categoryId);
})
->get();
return view('admin.products.index', compact('products', 'tags'));
}
Keep in mind that while {id} is a $request->route()->parameter('id')
the query parameters are handled as $request->input('category_id') to retrieve them in controller.
Hope It will give you all you expected outcome if any modification needed let me know:
public function productList($tag_id = null , $category_id = null){
$tags = Tag::all();
$categories = Category::all();
if($tag_id && $category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->where('category_id' , $category_id)
->get();
} elseif($tag_id && !$category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->get();
} elseif($category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->where('category_id' , $category_id)
->get();
} elseif(!$category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->get();
}
return view('admin.products.index',compact(['products','tags','products']));
}
Route:
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');

Eloquent where condition AND ( condition OR condition OR condition )

Can somebody tell me what am I doing wrong?
I want to get all projects with status 0 and if any of data matches in eloquent.
My code is like this
public function search(Request $request){
if($request->has('q')){
$search_query = $request->input('q');
$projects = Project::where(['status' => '0'])->get();
$projects = $projects->where(function($query) use ($search_query) {
$query->where('title','LIKE','%'.$search_query.'%')
->orWhere('shortDescription','LIKE','%'.$search_query.'%')
->orWhere('longDescription','LIKE','%'.$search_query.'%')
->orWhere('tags','LIKE','%'.$search_query.'%')
->orWhere('projectLink','LIKE','%'.$search_query.'%');
});
$projects->get();
dd($projects);
}
}
And I am getting this error
ErrorException
explode() expects parameter 2 to be string, object given
I solved the problem but changed the code a little bit... If you like, take it! I tested and it's working.
if($request->has('q')){
// Your $request->q Value
$term = $request->q;
$projects = DB::table('tbl_projects')->where('status', '=', 0)
->where(function ($query) use ($term) {
$query->where('title', 'LIKE', '%'.$term.'%')
->orWhere('shortDescription', 'LIKE', '%'.$term.'%')
->orWhere('longDescription', 'LIKE', '%'.$term.'%')
->orWhere('tags', 'LIKE', '%'.$term.'%')
->orWhere('projectLink', 'LIKE', '%'.$term.'%');
})
->get();
//dd($projects);
}
Raw query is:
select * from `tbl_projects` where `status` = 0 and (`title` LIKE %bla bla% or `shortDescription` LIKE %bla bla% or `longDescription` LIKE %bla bla% or `tags` LIKE %bla bla% or `projectLink` LIKE %bla bla%))
Regards!
Your error is
$projects = Project::where(['status' => '0'])->get();
(['status' => '0']) Where clause params required is different. You must use ('status', '0') or ('status', '=', '0')
When you use ->get(), you have a Collection or EloquentCollection object. You need a QueryBuilder
Try to implement a better programation logic.
A better implementation is
public function search(Request $request){
if($request->has('q')){
// Add array with field coincidences target. Is better if this array is a const static field in the Project model
$searchFields = ['title', 'shortDescription', 'longDescription', 'tags', 'projectLink' ];
// Now you can add 100 fields for search coincidences easily
$search_query = $request->input('q');
$projects = Project::where('status', '0');
foreach($searchFields as $searchField){
if ($searchField == 'title'){
$projects = $projects->where($searchField,'LIKE',"%$search_query%");
continue;
}
$projects = $projects->orWhere($searchField,'LIKE',"%$search_query%");
}
$projects = $projects->get();
dd($projects);
}
}

Resources