Laravel 4 paginate on GET request - php

I have a form that is used to filter results for a categories page. So, the URL will be localhost/public/search?keyword=blue however when I attempt to paginate() them the URL shows up as localhost/public/search?page=2 and so on. If I manually add the page=2 part to the end of the url it works fine but it's not adding it to the URL with the get request as needed. It needs to show up as localhost/search?keyword=blue&page=2
Not sure if needed but here is my method that handles the paginate()
$category = Inventory::select('inventory_images.image', 'inventory.id' , 'inventory.sku', 'inventory.name', 'inventory.price', 'inventory_categories.category')
->join('inventory_categories', 'inventory.sku', '=', 'inventory_categories.sku')
->leftJoin('inventory_images', 'inventory.sku', '=', 'inventory_images.sku')
->where('inventory.active', '=', 1)
->where('inventory.stock_quantity', '>', 2)
->where('inventory.description', 'LIKE', '%'. Input::get('keyword') . '%')
->orWhere('inventory.name', 'LIKE', '%'. Input::get('keyword') . '%')
->groupby('inventory.id')
->take(1000)
->paginate(16);

The problem is in your view file, where pagination is printed.
You need to append query parameters to links generated by Eloquent's paginator - which is pretty simple!
<div class="pagination">
{{ $model->appends(Input::except('page'))->links() }}
</div>
Note: you must append everything except the page query parameter. If you don't, it would be included twice in the URL.

Related

implement exact filters by passing multiple data

I have a question about how to show the exact data in a filter, I am making a filter that passes 5 data to filter it, which I want the first 3 data that I pass to be exact, the problem is that if I pass a data with the value of id 1 It brings me the data that has id: 1-10-11-111 I only want it to bring me the 1.
This is my controller where I do the query
public function getProcess(Request $request){
if($request){
$entity = trim($request->get('entity_id'));
$process = trim($request->get('process_id'));
$proveed = trim($request->get('proveed_id'));
$queryord_compra = trim($request->get('ord_compra'));
$querydescrip = trim($request->get('descrpcion'));
$ord_compra =Order_com::where('entity_id','=',$entity )//where('entity_id','LIKE', '%'. $entity .'%')
->where('process_id','=',$process)//where('process_id','LIKE', '%'. $process .'%')
->where('proveed_id','=',$proveed )//where('proveed_id','LIKE', '%'. $proveed .'%')
->where('ord_compra','LIKE', '%'. $queryord_compra .'%')
->where('descrpcion','LIKE', '%'. $querydescrip .'%')
->get();
}
$data = ['ord_compra' => $ord_compra,'proveedores' => $proveedores];
return view('admin.order_compra,$data);
}
I made a query with the first 3 data but when filtering nothing is shown
You can use dd(\DB::getQueryLog()); on the line right after your query to see what the SQL query is, this might help you investigate the problem.
With what you describe, your approach is correct - however I do see some potential issues.
The main issue I see is you are not doing any server side validation on your request, therefore some of these values can be empty or null, which could explain the lack of results.
You should also do a dd($request); to ensure the data being passed to the eloquent model is what you're expecting.

Laravel withQueryString does not exist after calling paginate method on query builder

Method Illuminate\Database\Eloquent\Collection::withQueryString does
not exist.
when i write this code it gives this error
blade;
<div class="float-right">{{ $modeller->withQueryString()->links()}}</div>
controller;
public function index(){
$modeller = Modeller::query();
$koleksiyonlar = Koleksiyon::all();
$modelistler = Modelist::all();
$uretim_sorumlulari = Uretim_sorumlusu::all();
if(request('model_kodu')){
$modeller = $modeller->where('ModelKodu', 'LIKE', "%".request('model_kodu')."%");
}
if(request('koleksiyon_id')){
$modeller = $modeller->where('koleksiyon_id', 'LIKE', "%".request('koleksiyon_id')."%");
}
if(request('uretim_sorumlusu_id')){
$modeller = $modeller->where('UretimSor', 'LIKE', "%".request('uretim_sorumlusu_id')."%");
}if(request('modelist_id')){
$modeller = $modeller->where('modelist_id', 'LIKE', "%".request('modelist_id')."%");
}
$modeller = $modeller->paginate(18);
return view('kumas.index',compact('modeller','koleksiyonlar','modelistler','uretim_sorumlulari'));
}
The paginate method, runs an implicit get on your query result.
try to use withQueryString instead of paginate.
example:
$modeller->withQueryString()->paginate(18);
but from your use case I suggest to use this in your view, instead of query string, this will add everything came from query string to your links:
{{ $users->appends($_GET)->links() }}
More Details on the pagination & Query String params
the page, offset, ... and everything paginate needs, would append automatically to paginate function without any effort.
you only need to explicitly ->appends($_GET) when you have some filtering parameters in your $_GET and want to preserve them in the following requests, when user clicks the next page or previous page
to expand on #Abilogos answer, I think it is better to use Request::except('page') method, which return an array of query parameter except the page parameter
in your blade view:
{{ $users->appends(\Request::except('page')->links() }}

Laravel Pagination with Get request

I've followed the instructions on the Laravel documentation for pagination with appends([]) however I'm having a little trouble with the persistence of these parameters.
Say for example, I pass home?category=Cars&make=Tesla to my view. What is the best way to paginate with them Get requests?
Right now I've passed the category as a parameter to the view as (where category is the model i've grabbed findOrFail with the request('category');)
$category_name = $category_model->name;
And then in my view it's like so:
{{ $vehicles->appends(['category' => $category_name])->links() }}
But when I go between pages in the pagination, this $category_name value doesn't seem to persist. Whats the recommended way to achieve what I want?
Thanks.
You can append the query string in your controller when you paginate the result. I'm not sure if that was your only question or even regarding applying the query string as a condition. So here is a sample showing you how to do both. This should give you an idea of how to do it. I just assumed the column names in this example.
$category = request('category');
$make = request('make');
$vehicles = Vehicle::when($category, function ($query) use ($category) {
return $query->where('category', $category);
})
->when($make, function ($query) use ($make) {
return $query->where('make', $make);
})
->paginate(10);
$vehicles->appends(request()->query());
return view('someview', compact('vehicles'));

Routing with parameters in laravel 5

I've got a results page for my website that outputs a list of users.
#extends('templates.default')
#section('content')
<h3>Results for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No results found, sorry.</p>
#else
<div class="resultRow">
<div class="">
#foreach ($users as $user)
#include('user/partials/userblock')
#endforeach
{!! $users->appends(Request::except('page'))->render() !!}
</div>
</div>
#endif
#stop
with a fairly standard search controller:
class SearchController extends Controller {
public function getResults(Request $request) {
$query = $request->input('query');
$users = User::where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'LIKE', "%{$query}%")->where('role', '=', 2)
->orWhere('username', 'LIKE', "%{$query}%")->where('role', '=', 2)
->orWhere('profile_text', 'LIKE', "%{$query}%")->where('role', '=', 2)
->orWhere('keywords', 'LIKE', "%{$query}%")->where('role', '=', 2)
->orWhere('tagline', 'LIKE', "%{$query}%")->where('role', '=', 2)
->simplePaginate(1);
return view('search.results')->with('users', $users);
}
}
Now, this works fine and well. If I search for "Jack", I get all the Jacks.
What I want to know now is, would it be possible to have a route with a predefined parameter or query string?
For example, say, on my front page I had a link to all the plumbers in my users.
<a id="plumbers" href="{{ route('search.results')->withQueryOfPlumbers }}">Plumbers</a></li>
Would this be possible? Or should I be outputting my data another way?
If you are just using GET parameters, the route() helper allows you to pass parameters as a second parameter such as: route('search.results', ['user-type, => 'plumbers'])
This will output: http://www.example.com/search/results?user-type=plumbers
You can add a column to your User called profession, then you'd do something like this:
$plumbers = User::where(['profession'=>'plumber', /*other WHERE options*/])->get();
This will return all of the users that are plumbers.
If you're hard coding the id and text of the a link, then you could just do
<a id="plumbers" href="{{ route('search.results') }}/plumbers">Plumbers</a>
And then match the keyword of plumbers in your routing table, see Laravel docs on routing parameters for more info.
Your route would look something like this:
Route::get('/search/{trade?}', ['uses' =>'SearchController#getResults', 'as' => 'search.results']);
You should be able to then inject the $trade variable into your controller. A small aside, I would avoid using raw queries in controllers as much as possible from a design and maintenance perspective and make a "search" helper function in your Eloquent model for users (See Eloquent query scopes).

Laravel - Query Model if values contain a certain string (taken from search input)

I am implementing a search using Laravel and Ajax. So I have a Product which belongs to a Tag and a Subcategory. On the other hand the Subcategory belongs to a Category. I want to check all of their properties (field values) and check if they contain the given string. With some searching I found out that I have to use LIKE. Here is what I tried:
$products = Product::where('name_en', 'LIKE', $search)->get();
However this will get the products if the search string matches exactly the value. I want to match if it contains it. How can I proceed with the belongsTo relationships? How can I check the propreties of Tag and Subcategory as well? How to chain everything together so I achieve the desired result? Thanks in advance.
you are doing one thing wrong, your query returns you exact matches because you given the exact string. But your query should be like this.
$products = Product::where('name_en', 'LIKE', '%'.$search.'%')->get();
Above query will gives your products which contains the searched string.
And if you want to search in relational tables then you can user laravel method join(). But there are one more method whereHas but I always avoiding this method, because it creates very complex query. which is very heavy. So you can use join() method which will add inner join with relational table.
Here is the example of join:
$products = Product::join('tags', function($builder) {
$builder->on('tags.id', '=', 'products.tag_id');
// here you can add more conditions on tags table.
})
join('sub_categories', function($builder) {
$builder->on('sub_categories.id', '=', 'products.tag_id');
// here you can add more conditions on subcategories table.
})
->where('name_en', 'LIKE', '%'.$search.'%')
->get();
This is the basic example, you can use this according to your requirement.
To add to Lakhwinder Singh’s answer, it might be worth wrapping it up in a scope that you can apply to your model:
class Product extends Model
{
public function scopeSearch($query, $keywords)
{
return $query->where('name_en', 'LIKE', '%'.$keywords.'%');
}
}
You can then use this scope like this:
$products = Product::search($keywords)->get();
Which means you don’t have to keep manually adding “LIKE” conditions throughout your application.
As an aside, Laravel’s introducing Scout, a driver-based full text search extension for Eloquent, in version 5.3.
What you want is to write an advanced query to search product based on related models too, so as previous suggestion by others, you have to write join statements.
Check my example code below, which is written to search members, the search string also will bring members if the string matches, members skills or positions, so this will surely help you.
$users = User::select('app_users.*')
->distinct()
->join('app_members', 'app_users.id', '=', 'app_members.app_users_id')
->leftJoin('app_members_jobtitles', 'app_members.id', '=', 'app_members_jobtitles.app_members_id')
->leftJoin('app_jobtitles', 'app_members_jobtitles.app_jobtitles_id', '=', 'app_jobtitles.id')
->leftJoin('app_members_tags', 'app_members.id', '=', 'app_members_tags.app_members_id')
->leftJoin('app_technologies', 'app_members_tags.app_technologies_id', '=', 'app_technologies.id')
->whereNull('app_users.activation')
->where('app_users.block','=',0)
->where(function ($query)use ($search) {
$query->orWhere('app_users.first_name', 'like', '%'.$search.'%')
->orWhere('app_users.last_name', 'like', '%'.$search.'%')
->orWhere('app_members.company', 'like', '%'.$search.'%')
->orWhere('app_members.job_title', 'like', '%'.$search.'%')
->orWhere('app_jobtitles.title', 'like', '%'.$search.'%')
->orWhere('app_technologies.title', 'like', '%'.$search.'%')
->orWhere('app_members.summary', 'like', '%'.$search.'%');
})
->get();
Note the following join in the above code, which is in your case category and sub category
->leftJoin('app_members_jobtitles', 'app_members.id', '=', 'app_members_jobtitles.app_members_id')
->leftJoin('app_jobtitles', 'app_members_jobtitles.app_jobtitles_id', '=', 'app_jobtitles.id')

Categories