How to return paging cache in laravel? - laravel

I would like to know if there is any way to page this query that I do in Laravel and store it in the cache.
I've already put ->paginate() but it seems that the cache doesn't return in Eloquent but as an object. I checked the variable's type with gettype().
this is my role. Can anyone help me?
public function getProductsRecommendations($keywords)
{
$expiration = 10;
$keyName = 'productsRecommended';
$list = Cache::remember($keyName, $expiration, function () use ($keywords) {
return Product::query()->where(function ($productsAll) use ($keywords) {
if ($keywords) {
foreach ($keywords as $keyword)
$productsAll->orWhere('title', 'LIKE', '%' . $keyword . '%')->orWhere('description', 'LIKE', '%' . $keyword . '%')->orWhere('code', 'LIKE', '%' . $keyword . '%');
}
})->where('status', 'active')->get();
});
return $list;
}

You should cache your results per page, with a key that is the current page. Something like:
$currentPage = request()->get('page',1);
$category = Cache::remember('sellcategory-' . $currentPage, 10, function(){
return DB::table('elans')->orderBy('updated_at', 'desc')->where(['derc' => 1,'elaninnovu' => 'Satılır'])->paginate(10);
});

I managed to do what I needed. I'll leave it here in case someone goes through the same problem and finds this question.
Sometimes you might want to create an instance of paging manually, passing in an array of items. You can do this by creating an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance, depending on your needs.
To exemplify:
use Illuminate\Pagination\Paginator;
$paginator = new Paginator($array, $rowPerPage, $currentPage = null);

Related

Laravel dynamic query

I have a GET form with three filters.
make
Year
country
I need to get all posts from db. But filter the results based on these three filters.
If a country is selected, get posts for that country only or all countries.
if a make is selected, get posts for that make only or all makes
if a year is selected, get posts for that year only or all years
how to write one query that filters all these three options. What I have done is used if and else statements and written different queries for each scenario. That's 9 queries to get one information. Can we make it dynamic and just have one query?
My Example query:
public function search(Request $request)
{
$search=$request->input('search');
if($request->input('country') == "all")
{
$posts = Post::where('status','Published')->orderBy('status_change','DESC')
->where('status','Published')
->where(function($query) use ($search){
$query->where('title','LIKE','%'.$search.'%');
$query->orWhere('model','LIKE','%'.$search.'%');
$query->orWhere('notes','LIKE','%'.$search.'%');
$query->orWhere('description','LIKE','%'.$search.'%');
})
->paginate(25);
}
else
{
$posts = Country::where('country_name', $request->input('country'))->first()->posts()->orderBy('status_change','DESC')
->where('status','Published')
->where(function($query) use ($search){
$query->where('title','LIKE','%'.$search.'%');
$query->orWhere('model','LIKE','%'.$search.'%');
$query->orWhere('notes','LIKE','%'.$search.'%');
$query->orWhere('description','LIKE','%'.$search.'%');
})
->paginate(25);
}
return view('welcome')
->with('published_posts',$posts)
;
}
I think something like this would work:
/**
* #param Request $request
*/
function search(Request $request)
{
$postsQuery = Post::where('status', 'Published');
if ($request->has('country')) {
$country = $request->country;
// assuming relationships are setup correclty
$postsQuery->whereHas('country', function ($query) use ($country) {
$query->where('country_name', 'LIKE', $country);
});
}
if ($request->has('search')) {
$postsQuery->where(function ($query) use ($search) {
$query->where('title', 'LIKE', '%' . $request->search . '%');
$query->orWhere('model', 'LIKE', '%' . $request->search . '%');
$query->orWhere('notes', 'LIKE', '%' . $request->search . '%');
$query->orWhere('description', 'LIKE', '%' . $request->search . '%');
});
}
$postsQuery->orderBy('status_change', 'DESC')->paginate(25);
return view('welcome')->with('published_posts', $result);
}
I used 'when' method.
$make = null;
$year = null;
$country = null;
if($request->filled('make')){
$make = $request->query('make');
}
if($request->filled('year')){
$year = $request->query('year');
}
if($request->filled('country')){
$country = $request->query('country');
}
$posts = DB::table('posts')
->when($make, function($query, $make){
return $query->where("make", "=", $make);
})
->when($year, function($query, $year){
return $query->whereYear("year", "=", $year);
})
->when($country, function($query, $country){
return $query->where('country', "like", $country);
})
->get();
Check out the Laravel Docs:
Check out an article here

Laravel search with localization

I have a scope about searcing. Also using localization from mcamara
Right now, when i am search something, results are coming with different languages. But i can just search with my main language. After results are came translation happening. This is related with my blade.
{!! $news->translate($localeCode)->title !!}
But main question is before the search. How can i search something with selected language. I can switch language easily. This is my search scope.
public function scopeSearch($query, $search) {
$localeCode = LaravelLocalization::getCurrentLocale();
return $query->translate($localeCode)->where('title', 'LIKE', '%' .$search. '%')
->orWhere('sub_body', 'like', '%' .$search. '%')
->orWhere('body', 'like', '%' .$search. '%');
}
Also this is my controller
public function index (Request $request){
$localeCode = LaravelLocalization::getCurrentLocale();
$updates = Update::latest()->take(3)->get();
$query = $request->get('q');
$new = $request->filled('q') ? News::search($query) : News::query();
$new = $new->orderBy('id', 'desc')->paginate(10);
return view('frontend.news', compact('localeCode', 'updates', 'new', 'query'));
}
I'll be glad if anyone help. Thanks advance.

Laravel 5 Search and pagination url's together

I have a search button and pagination system. They are working perfectly. But when i searched something and page was paginated with numbers. After clicking next page. Search query is gone. After that all values are coming into page2. Not searched values.
My search button changing url like this /en/news?q=foo
My pagination is changing url like this(default btw) /en/news?page=2
How can i add this side by side. Or how can i solve the problem. I am open any solution.
I am using scope for search.
public function scopeSearch($query, $search) {
return $query->where('title', 'LIKE', '%' .$search. '%')
->orWhere('sub_body', 'like', '%' .$search. '%')
->orWhere('body', 'like', '%' .$search. '%');
}
Also this is my controller:
public function index (Request $request){
$localeCode = LaravelLocalization::getCurrentLocale();
$updates = Update::latest()->take(3)->get();
$query = $request->get('q');
if ($query){
$new = $query ? News::search($query)->orderBy('id', 'desc')->paginate(10):News::all();
return view('frontend.news', compact('localeCode', 'updates', 'new', 'query'));
}
else
{
$new = News::orderBy('id', 'desc')->paginate(10);
return view('frontend.news', compact('localeCode', 'updates', 'new', 'query'));
}
}
I hope i can express my own.
{{ $users->appends($_GET)->links() }}
that append all your filter value in one line
It is explained in the documentation for displaying pagination results:
Appending To Pagination Links
You may append to the query string of pagination links using the appends method. For example, to append sort=votes to each pagination link, you should make the following call to appends:
{{ $users->appends(['sort' => 'votes'])->links() }}
I find your current code quite confusing. I think you can rewrite it like this
public function index (Request $request){
$localeCode = LaravelLocalization::getCurrentLocale();
$updates = Update::latest()->take(3)->get();
$query = $request->get('q');
$new = $request->filled('q') ? News::search($query) : News::query();
$new = $new->orderBy('id', 'desc')->paginate(10);
return view('frontend.news', compact('localeCode', 'updates', 'new', 'query'));
}
and in the view you'll have to use
{{ $new->appends(['q' => $query])->links() }}
Try to use {{ $collection->appends(request()->all())->links() }}

How to use Laravel Eloquent with LIKE statement in array list?

I have some conditions in array like
$category = Input::get('category');
$cuisine = Input::get('cuisine');
$veg = Input::get('veg');
$trending = Input::get('trending');
$time = Input::get('time');
if($category) $conditions['category'] = $category;
if($cuisine) $conditions['cuisine'] = $cuisine;
if($veg) $conditions['veg'] = $veg;
if($trending) $conditions['trending'] = $trending;
How can I make
$list = Data::where($conditions)->where('cuisine','LIKE','%'.$cuisine.'%')->get();
Is it possible to enter LIKE % in this statement
if($cuisine) $conditions['cuisine'] = $cuisine;
The problem is that if I want to add this where('cuisine','LIKE','%'.$cuisine.'%') several areas it needs to be updated. and in some cases, if cuisine is not present everything cannot be fetched
I want to perform LIKE statement for only cuisine data.
Sure, you can do that by creating an array with this format:
[['column1', 'like', '%' . $filter1 . '%'], ['column2', 'like', '%' . $filter2 . '%']]
For example:
$fields = ['category', 'cuisine', 'veg', 'trending', 'time'];
foreach ($fields as $field) {
if ($request->get($field)) {
$conditions[] = [$field, 'like', '%' . $request->get($field) . '%'];
}
}
$list = Data::where($conditions)->get();
Another example from the docs:
You may also pass an array of conditions to the where function:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
https://laravel.com/docs/5.5/queries#where-clauses
Update
You've just updated your question and said you want to use like only for $cuisine. In this case, you can use a closure:
->where(function($q) use($request) {
if ($request->cuisine) {
$q->where('cuisine', 'like', '%' . $request->cuisine . '%');
}
})
Or you could use when():
->when($request->cuisine, function ($q) use ($cuisine) {
return $q->where('cuisine', 'like', '%' . $request->cuisine . '%');
})
Well, you can do it in parts:
$query = Data::where($conditions);
if($cuisine) {
$query->where('cuisine','LIKE','%'.$cuisine.'%');
}
$list = $query->get();
You can do it like,
$query = DB::table('data');
$category = Input::get('category');
$cuisine = Input::get('cuisine');
$veg = Input::get('veg');
$trending = Input::get('trending');
$time = Input::get('time');
if($category) {
$query->where('category','LIKE','%'.$category.'%');
}
if($cuisine) {
$query->where('cuisine','LIKE','%'.$cuisine.'%');
}
if($veg) {
$query->where('veg','LIKE','%'.$veg.'%');
}
if($trending) {
$query->where('trending','LIKE','%'.$trending.'%');
}
if($time) {
$query->where('time','LIKE','%'.$time.'%');
}
$list = $query->get();
I hope you will understand.
Why not just assign as blank value as default as it will pass in LIKE for all cases
$conditions['cuisine']= (isset($cuisine)&&$cuisine)) ? $cuisine : '';
Well, you have to assign query to some variable:
$query = Data::where($conditions);
if($cuisine) {
$query = $query->where('cuisine','LIKE','%'.$cuisine.'%');
}
$list = $query->get();

Paginate search result laravel

After some help in a previous post Laravel - Search Facility on site using Eloquent I now need to some help on paginating the result using the built in laravel pagination class.
public function search() //no parameter now
{
$q = Input::get('term');
if($q && $q != ''){
$searchTerms = explode(' ', $q);
$query = DB::table('wc_program'); // it's DB::table(), not DB::tables
if(!empty($searchTerms)){
foreach($searchTerms as $term) {
$query->where('JobRef', 'LIKE', '%'. $term .'%');
}
}
$results = $query->get();
dd($results); // for debugging purpose. Use a View here
}
}
Simply change get to paginate and provide number of items per page.
$results = $query->paginate(10);

Resources