I would like to make an alphabetical sort in my function index().
I think I should use the Order By clause?
I am stuck in my code below:
public function index(Request $req)
{
if ($req->has('search') && !empty($req->search)) {
$validated = $req->validate([
'search' => 'alpha',
]);
$auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->paginate(5);
$auteurs->appends($req->only('search'));
return view('admin.auteurs.index', compact('auteurs'));
}
$auteurs = Auteur::paginate(5);
return view('admin.auteurs.index', compact('auteurs'));
}
Yes use orderBy like this:
public function index(Request $req)
{
if ($req->has('search') && !empty($req->search)) {
$validated = $req->validate([
'search' => 'alpha',
]);
$auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->orderBy('nom', 'ASC')->paginate(5);
$auteurs->appends($req->only('search'));
return view('admin.auteurs.index', compact('auteurs'));
}
$auteurs = Auteur::orderBy('nom', 'ASC')->paginate(5);
return view('admin.auteurs.index', compact('auteurs'));
}
Related
I am trying to merge several builders to paginate search results of them, but this code returning me an error
My SearchController.php
public function index(Request $request)
{
$string = mb_strtolower($request->input('q'), "UTF-8");
if ($string != "") {
// $query = explode(" ", $string);
$query = $string;
} else {
$query = null;
}
if ($query != null) {
$news = $this->searchQuery(new News(), 'title', 'content', $query, false);
$last = $this->searchQuery(new Last(), 'title', 'description', $query, false);
$author = $this->searchQuery(new AuthorNews(), 'title', 'description', $query, false);
$tv = $this->searchQuery(new TvBroadcast(), 'name', 'description', $query, false);
$program = $this->searchQuery(new TvProgram(), 'name', 'description', $query, false);
$project = $this->searchQuery(new SpecProject(), 'title', 'description', $query, false);
$appointments = $this->searchQuery(new Appointment(), 'fio', 'position', $query, false);
//Новости по авторам
// $authors = $this->searchAuthor($query);
// dd($authors);
// 21520
$item = $news->merge($last);
$item = $item->merge($author);
$item = $item->merge($tv);
$item = $item->merge($program);
$item = $item->merge($project);
$item = $item->merge($appointments);
$items = $item->paginate(21);
$items_c = $items->total();
} else {
$items = null;
$items_c = 0;
$string = null;
}
$method = 'index';
return view('front.search.index', array('items' => $items, 'count' => $items_c, 'q' => $string, 'method' => $method));
}
public function searchQuery($model, $attr1, $attr2, $query, $stat, $author = false)
{
$items = $model->with('nodes')->whereHas('nodes', function ($q) use ($query, $attr1, $attr2) {
$q->where('language_id', '=', app()->getLocale())->where(function ($q) use ($query, $attr1, $attr2) {
$q->where(\DB::raw('lower(' . $attr1 . ')'), 'like', '%' . $query . '%')
->orWhere(\DB::raw('lower(' . $attr2 . ')'), 'like', '%' . $query . '%');
});
})->orderBy('created_at', 'desc');
if ($stat == true) {
$items = $items->where('stat', '=', 1);
}
if ($author) {
$items = $items->with(['author', 'author.nodes'])->orWhereHas('author.nodes', function ($q) use ($query) {
// foreach ($query as $elem) {
// $q->where(\DB::raw('lower(title)'), 'like', '%' . $elem . '%');
// }
$q->where(\DB::raw('lower(title)'), 'like', '%' . $query . '%');
});
}
return $items;
}
I have 7 Builders like this and I want to merge them
But when I am running my code I get an error like this
I also tried union() method and it doesn't work too
I am trying to filter data using when query in Laravel, where it should filter data using the filter $sortBy or $categoryId. Please note the all 3 fields like $id $sortBy $categoryId are optional and will not be presented in all queries
public function Products(Request $request)
{
$page = $request->has('page') ? $request->get('page') : 1;
$limit = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
$sortBy = (($request->sortBy == "popularity") ? "viewCount" : "created_at");
$categoryId= $request->get('categoryId');
$sellerId = $request->header('id')?SellersBranding::findOrFail($request->header('id')):"Null";
$productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
->when($sellerId=="Null", function($query) use ($page, $limit){
return $query->where('status', 'active')
->limit($limit)->offset(($page - 1) * $limit);
})
->when($sortBy, function ($query) use ($sortBy, $sellerId, $page, $limit){
return $query->orderBy($sortBy, 'DESC')
->where('Sid', $sellerId->id)
->where('status','active')
->limit($limit)->offset(($page - 1) * $limit);
})
->when($categoryId, function ($query) use ($categoryId, $sellerId, $page, $limit) {
->where('Sid', $sellerId->id)
->where(['category_id' => $categoryId, 'status' => 'active'])
->limit($limit)->offset(($page - 1) * $limit)
->inRandomOrder();
})->get();
}
i am new in php and also in laravel please help how to get filtered data
i cleanup your code you can check this
public function Products(Request $request)
{
$page = $request->has('page') ? $request->get('page') : 1;
$limit = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
$sortBy = (($request->sortBy == "popularity") ? "viewCount" : "created_at");
$categoryId= $request->filled('categoryId');
$seller = $request->header('id') ? SellersBranding::findOrFail($request->header('id')): null;
$productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
->when($seller ,function ($query) use ($seller){
$query->where('Sid', $seller->id);
})
->when($categoryId ,function ($query)){
$query->where('category_id', request('categoryId'))
->inRandomOrder();
})
->where('status','active')
->orderBy($sortBy, 'DESC')
->limit($limit)->offset(($page - 1) * $limit);
return $productLive;
}
here when() something filter is coming we are only applying condition.
Not returning each filter as you did
When trying to filter with only username or email code works fine.But when i am trying to filter with both email and username it returns empty.what i am missing
User model
public function scopeEmail($query, $email)
{
$query->where('email','=', $email);
}
public function scopeUsername($query, $username)
{
$query->where('username','=', $username);
}
Controller:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q->Email($request->input('email'));
}
if (isset($username))
{
$q->Username($request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use When to make filter easy:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
$q->when($email,function ($query){
$query->where('email',$email);
});
$q->when($username,function ($query){
$query->where('username',$username);
});
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use simple where in if statements
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q = $q->where('email', $request->input('email'));
}
if (isset($username))
{
$q = $q->where('username', $request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Try this
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (!is_null($email))
{
$q = $q->where('email', $email);
}
if (!is_null($username))
{
$q = $q->where('username', $username));
}
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
How to create api for search in lumen/laravel .. I tried using keyword but not working.
public function index(){
$Employees = Employees::all();
$page = Input::get('page', 1);
$keyword = Input::get('keyword', '');
if ($keyword!='') {
$keyword = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%");
}
$itemPerPage=5;
$count = Employees::count();
$offSet = ($page * $itemPerPage) - $itemPerPage;
$itemsForCurrentPage = array_slice($Employees->toArray(), $offSet, $itemPerPage);
return new LengthAwarePaginator($itemsForCurrentPage, count($Employees), $itemPerPage, $page,$keyword);
}
You should change this line :
if ($keyword!='') {
$Employees = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%")
->get();
}
Also i think You should the pagination within the model query, not on the returned result.
you can also do this
define your logic in a scope created in you model and consume it in your controller.here is what i mean
This should be in your model
public function scopeFilter($query, $params)
{
if ( isset($params['name']) && trim($params['name'] !== '') )
{
$query->where('name', 'LIKE', trim($params['name']) . '%');
}
if ( isset($params['state']) && trim($params['state'] !== '') )
{
$query->where('state', 'LIKE', trim($params['state']) . '%');
}
return $query;
}
and in your controller have something like
public function filter_property(Request $request)
{
$params = $request->except('_token');
$product = Product::filter($params)->get();
return response($product);
}
you can get more by reading scope on laravel doc and this blog post here
I am calling URL with search params which are dynamic. How could I form proper Eloquent query?
In theory:
query
query where(someParam1)
query where(someParam2)
query orderby(someParam3)
query get
I need this kind of structure so I can use where clause if param exists.
If there is some other way in Laravel, please let me know.
It's easy with Laravel. Just do something like this:
$query = User::query();
if ($this == $that) {
$query = $query->where('this', 'that');
}
if ($this == $another_thing) {
$query = $query->where('this', 'another_thing');
}
if ($this == $yet_another_thing) {
$query = $query->orderBy('this');
}
$results = $query->get();
You can just use the where statement.
For ex: on users table or User model, you want dynamic search on name, id. You can do this
$where = [];
$firstName = $request->get('first_name');
if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
$id = $request->get('id');
if ($id) $where[] = ['id', $id];
$users = User::where($where)->get();
By default, it will return all the users, if anything exists in $where array, it will apply the where condition on that.
You can use like this
$validateUserDetail = User::query();
if (!empty($userDetails['email'])) {
$validateUserDetail->whereemail($userDetails['email']);
}if (!empty($userDetails['cellphone'])) {
$validateUserDetail->wherecellphone($userDetails['cellphone']);
}
$validateUserDetail->select('username');
$validateUserDetail->get()
You can pass dynamic value by below example
$user_auctions = $this->with('userAuctions')
->where('users.id', '=', $id)
->get();
I came here from Google. If you are going to be iterating over more then 5 if statements, its more effective to use a switch statement
if(empty($request->except('_token')))
return 'false';
$models = Vehicle::query();
$request_query = $request->all();
$year_switch = false;
foreach ($request_query as $key => $field_value){
if($field_value != 'any'){
switch($field_value){
case 'X':
case 'Y':
$year_switch = true;
break;
case'Z':
//Dynamic
$models->where($key,'LIKE', $field_value);
break;
}
}
}
You can pass a callback to the where function.
So, you can do something like this:
class TestService {
TestRepository $testeRepository;
public function __construct(TesteRepository $teste) {
$this->testeRepository = $teste;
}
public function getAll(array $filters)
{
$where = function (Builder $query) use ($filters) {
collect($filters)
->each(function ($value, $param) use ($query) {
if ($param === 'test') {
$query->where($param, '=', $value);
} else if ($param === 'test2') {
$query->orWhere($param, '>', $value);
}
});
};
return $this->testRepository->gelAll($where);
}
class TestRepository
{
public function getAll(\Closure $where)
{
$query = TestModel::query();
$query->where($where);
//and put more stuff here, like:
//$query->limit(15)->offset(30)
...
return $query->get();
}
}
And in your controller you pass the filters:
class TestControler ...
{
public function $index()
{
$filters = request()->query();
return $this->testService->getAll($filters);
}
}