I have following ORM
$trucksobj = DB::Table('trucks')
->orderBy('trucks.id','desc')
->join('trucktypes', 'trucks.trucktype_id', '=', 'trucktypes.id');
if($overweight=="on")
$trucksobj->where('trucktypes.max_weight', '>', 'trucks.weight');
$trucks=$trucksobj->get();
It work like a charm, but when i replace get() with paginate() it is not responding i.e
$trucks=$trucksobj->paginate(5);
is not working?
any thing i have missed?
Please follow this :http://culttt.com/2014/02/24/working-pagination-laravel-4/
Please us paginator function when you use manual query:
$trucksobj = DB::Table('trucks')
->orderBy('trucks.id','desc')
->join('trucktypes', 'trucks.trucktype_id', '=', 'trucktypes.id');
if($overweight=="on")
$trucksobj->where('trucktypes.max_weight', '>', 'trucks.weight');
$trucks=$trucksobj->get();
//$paginator = Paginator::make($items, $totalItems, $perPage);
$paginator = Paginator::make($trucks, count($trucks), 5);
public function pagination()
{
$users = DB::table('img')
->join('category', 'category.id', '=', 'img.category_id')
->select('img.category_id', 'category.name', 'img.img_url')
->paginate(2);
return view('page', compact('users'));
}
Related
I am using Laravel Framework 8.62.0 and PHP 7.4.20.
I get the following error:
Call to undefined method Illuminate\Database\Eloquent\Builder::links() (View: /home//Code/test_project/resources/views/index.blade.php)
I have a view that has uses 3 simple filters. To display the view via get I use the following:
public function getSearchView()
{
try {
$con = 'mysql_prod';
// search results
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id')
->limit(500)
->paginate(10);
// filter field
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
To filter the view I use:
public function postFilter(Request $request)
{
try {
$con = 'mysql_prod';
//##################################
// QUERY - SEARCH RESULTS
//##################################
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id');
// collection
if(!is_null($request->select_collection_field)) $items->where('collections.id', '=', intval($request->select_collection_field));
// FILTER field
if(!is_null($request->select_filter_field)) {
if($request->select_filter_field === "select_all") $items->orderBy('item_name', 'desc');
if($request->select_filter_field === "publishing_year") $items->orderBy('collections_year', 'desc');
}
// query database
$items->limit(500)->paginate(10);
//##################################
// FILTERS
//##################################
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items', 'condition', 'collection'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
In my web.php I have the two endpoints:
Route::get('/', [SearchController::class, 'getSearchView'])->name('/');
Route::post('postFilter', [SearchController::class, 'postFilter']);
In my view I use the pagination of laravel:
{!! $items->links('vendor.pagination.default') !!}
Any suggestions why I get the above error and how to fix it?
I appreciate your replies!
$items is currently a Query Builder instance. This object wont change, it will continue to be a Query Builder instance. When you execute a query from a Query Builder you get a returned result, and that is what you need to be passing to your view. You could reassign $items to this result easily:
$items = $items->limit(500)->paginate(10);
Now $items is the Paginator instance because you reassigned that variable to the result of the paginate call.
public function boot()
{
Paginator::defaultView('view-name');
Paginator::defaultSimpleView('view-name');
}
add this code to AppServiceProvider. I hope it will work.
Just wondering where to position the Laravel's pagination() here in my query() in order for it to work. I tried adding it at the end of $all_procedures:
public function fetchprocedure(Request $search_procedure) {
$filter_procedure = $search_procedure->input('search_procedure');
$all_procedures = HmsBbrKnowledgebaseProcedure::query()
->when(is_null($filter_procedure), function ($query) {
$query->where('bbr_procedure_id', '>=', 1);
})
//iLike is case insensitive
->when(!empty($filter_procedure), function ($query) use ($filter_procedure) {
$query->where('procedure_name', 'iLIKE', "%$filter_procedure%");
})
->orderBy('bbr_procedure_id', 'ASC')
->get()
->paginate(10);
return response()->json([
'all_procedures' => $all_procedures,
]);
}
UPDATE:
tried a solution given by an answer. Got rid of get(); but my error this time is:
Just instead of having:
->get()
->paginate(10);
Do
->paginate(10);
That will automatically get 10 results and paginate it taking into account the current page.
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.
I'm trying to do pagination 6 maximum result to the each page.
Here is my code in controller:
public function brand_new(Request $request)
{
$current_page = $request->get('page', 1);
$find_vehicles = $this->filterAll();//retrieving all the vehicles by calling a method
$total = $find_vehicles->count();
$paginator = new LengthAwarePaginator($find_vehicles, $total, 6, $current_page);
$paginator->setPath($request->getBasePath());
return view('pages.massSearch',compact('paginator'));
Here is my code in *.blade.php:
#foreach($paginator->getCollection()->all() as $pg)
{{ $pg->ImagePath }} {{--ImagePath is the php name of a table column--}}
#endforeach
But I'm getting error :Trying to get property of non-object
Any Suggestions will be helpful...
filterAll method:
public function filterAll($val)
{
$filter_avl = VehicleQuery::create()
->filterByAvailability(true)
->find();
$filter_modelAvl = VehicleQuery::create()
->useVModelQuery()
->filterByAvailability(true)
->endUse()
->find();
$filter_bndAvl = VehicleQuery::create()
->useVBrandQuery()
->filterByAvailability(true)
->endUse()
->find();
$filter_cStatus = VehicleQuery::create()
->useCurrrentStatusQuery()
->endUse()
->find();
$filter_mode = VehicleQuery::create()
->useVehicleModeQuery()
->filterByModeName($val)
->endUse()
->find();
$find_vehicles = VehicleImagesQuery::create()
->joinWith('VehicleImages.Vehicle')
->joinWith('Vehicle.VModel')
->joinWith('Vehicle.VBrand')
->joinWith('Vehicle.CurrrentStatus')
->joinWith('Vehicle.VehicleMode')
->filterByVehicle($filter_avl)
->filterByVehicle($filter_modelAvl)
->filterByVehicle($filter_bndAvl)
->filterByVehicle($filter_cStatus)
->filterByVehicle($filter_mode)
->find();
return $find_vehicles;
}//no errors with this code retrieve data perfectly.. Pagination part is the problem.
Instead of using propel I used Illuminate\Support\Facades\DB for this case
$find_vehicles = DB::table('vehicle_images')
->join('vehicle', 'vehicle_images.vehicle_id', '=', 'vehicle.id')
->join('V_model', function ($join1) {
$join1->on('vehicle.V_model_id', '=', 'V_model.id')->where('V_model.availability', '=', true);
})
->join('V_brand', function ($join2) {
$join2->on('vehicle.V_brand_id', '=', 'V_brand.id')->where('V_brand.availability', '=', true);
})
->join('Currrent_status', 'vehicle.Currrent_status_id', '=', 'Currrent_status.id')
->join('vehicle_transmission', 'vehicle.vehicle_transmission_id', '=', 'vehicle_transmission.id')
->join('vehicle_mode', function ($join3) use($val) {
$join3->on('vehicle.vehicle_mode_id', '=', 'vehicle_mode.id')->where('vehicle_mode.mode_name', '=',$val);
})
->paginate(6);
If any one find a way through with propel Please post the answer..Anyway Thank u people, appreciate your help...
I'm trying to search two optional tables using eloquent:
$users = User::where('ProfileType', '=', 2)
->where(function($query) {
$query->where('BandName', 'LIKE', "%$artist%");
$query->or_where('Genre', 'LIKE', "%$genre%");
})->get();
This works fine for return all results when a user does an empty search, but I am not sure how to adjust this for to search for bandname when that is present and vise versa.
Just to explain what happens on answer below:
Eloquent does a tricky thing here: When you call User::where(...) it returns a Database\ Query object. This is basically the same thing as DB::table('users')->where(...), a chainable object for constructing SQL queries.
So having:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
$query->where(function($query) {
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where_nested('BandName', 'LIKE', "%$artist%", 'OR');
}
// And another
if ($genre = Input::get('genre')) {
$query->where_nested('Genre', 'LIKE', "%$genre%", 'OR');
}
});
// Executes the query and fetches it's results
$users = $query->get();
Building on Vinicius' answer here's what worked:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where('BandName', 'LIKE', "%$artist%");
// Temp Usernamesearch
$query->or_where('NickName', 'LIKE', "%$artist%");
}
// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
$func = ($artist) ? 'or_where' : 'where';
$query->$func('Genre', 'LIKE', "%$genre%");
}
// Executes the query and fetches it's results
$users = $query->get();
Turns out that the second optional field must use or_where only if $artist is not set.
Thanks for your help
I think this is what youre after. Your view would have a form to search artist/genre one or the other can be set, or both, or none.
$users = User::where('ProfileType', '=', 2);
if (Input::has('artist')) {
$users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%');
}
if (Input::has('genre')) {
$users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%');
}
$users = $users->get();
$query = FormEntry::with('form')->where('domain_id', $id);
$query->where(function($query) use ($search, $start, $limit, $order, $dir) {
$query->where('first_name', 'LIKE', "%{$search}%")
->orWhere('last_name', 'LIKE', "%{$search}%")
->orWhere('email', 'LIKE', "%{$search}%")
->offset($start)
->limit($limit)
->orderBy($order, $dir);
});
$entries = $query->get();
$totalFiltered = $query->count();