Adding secondary query to query based on parameter in laravel - laravel

I am trying to do a complex query based on the input fields of the form.
public function search(Request $request){
$borrado =
$activo = 0;
$models = array();
$escandallos = Scandal::all();
foreach ($escandallos as $escandallo){
if (in_array($escandallo->modelo, $models)) {
}else{
array_push($models, $escandallo->modelo);
}
}
$query = Model::where('modelo', 'like', '%' . $request['modelo'] . '%')
->where('prototipo', 'like', '%' . $request['prototipo'] . '%')
->where('oficial', 'like', '%' . $request['modofi'] . '%')
->where('usuario_realiza', 'like', '%' . $request['usuario'] . '%')
->where('tipo', 'like', '%' . $request['tipo'] . '%')
->where('activa', 'like', '%' . $activo . '%');
if($request['referencia'] || $request['proveedor']){
/** Here i want to do this DB:raw where in clause if reference or provider is in request and need to search in other table*/
$query->DB::raw("where (id_escandallo,id_version) in (select id_escandallo,id_version from escandallo_p where referencia ='".$request['referencia']. "' and proveedor ='".$request['proveedor']."'");
}
$query->orderBy('modelo','desc');
$query->orderBy('id_version','asc');
$scandals = $query->paginate(100);
dd($scandals);
return view('designdoc.escandallos',['scandals'=> $scandals],['models'=>$models]);
}
This return this error:
Property [DB] does not exist on the Eloquent builder instance.
Thank you in advance, any help would be appreciated.
Best regards.

Use ->whereRaw()
$query->whereRaw(...);
also, you can simplify this part
if($request['referencia'] || $request['proveedor']){
$query->whereRaw(...); // but dont use 'where' in the string, its already prepended
}
to this
$query->when($request['referencia'] || $request['proveedor'], function ($q) use ($request) {
$q->whereRaw(...)
});
it is good so that you can chain it with previous command

Related

How to get foreign key data in main field Laravel

I have a problem connecting to the data for searching the customer's name because I only identify the id as a foreign key. How can I get data from the customer table? I tried using a join table but no got no result.
public function render()
{
$search = $this->searchTerm;
$data = Order::with('customer')->where('user_id', Auth::id())
->where(function ($query) use ($search) {
$query->where('customer_id', 'like', '%' . $search . '%') // <- this field linked in customers table to get name of customer
->orWhere('orderNumber', 'like', '%' . $search . '%');
})->orderBy('id', $this->sortDirection)->paginate(9);
return view('livewire.dashboard.orders.list-order', compact('data'));
}
If I am right I think you are trying to search for customer name through customer relationship
You can do it like this:
$search = $this->searchTerm;
$data = Order::where('user_id', Auth::id())->with(['customer' =>
function($query) use($search){
$query->where('name','like', '%' . $search . '%')
->orWhere('orderNumber', 'like', '%' . $search . '%');
}])->orderBy('id', $this->sortDirection)->paginate(9);

searching on name instead of id on sql

I have search input in my products page. I can search on name on description and on category if I type the id but that's not really practical how i change this sql so i can search on the name of the category instead of the id.
DB i have Products | name,description,category_id
Categories | id,name
public function scopeFilter($query,array $filters){
if ($filters['search'] ?? false){
$query
->where('name', 'like', '%' . request('search') . '%')
->orWhere('description', 'like', '%' . request('search') . '%')
->orWhere('category_id', 'like', '%' . request('search'). '%');
}
}
Since the category is a related model search on the relationship:
public function scopeFilter($query,array $filters){
if ($filters['search'] ?? false){
$query
->where('name', 'like', '%' . request('search') . '%')
->orWhere('description', 'like', '%' . request('search') . '%')
->orWhereHas('category', function ($q) {
$q->where('name','like', '%' . request('search'). '%'
});
}
}
This is assuming you have defined your relationship in your model.
Since the category is a related model search on the relationship AND I suggest using this code: ‌
public function scopeFilter($query,array $filters) {
if ($filters['search'] ?? false){
return $query->where('name', 'like', '%' . request('search') . '%')
->orWhere('description', 'like', '%' . request('search') . '%')
->orWhereHas('category', function ($q) {
$q->where('name','like', '%' . request('search'). '%');
});
}
return $query;
}

How To Get Search Query From Multiple Columns in Database

I have search form to get information from table named books.
Right now i'm using this controller
public function search(Request $request)
{
$keyword = $request->input('keyword');
$query = Book::where('judul', 'LIKE', '%' . $keyword . '%');
$book_list = $query->paginate(5);
$pagination = $book_list->appends($request->except('page'));
$total_book = $book_list->total();
return view('dashboards.index', compact('book_list', 'keyword', 'pagination', 'total_book'));
}
The problem is the data that i get from the request only available for judul. it just show empty result if the input keyword search addressed to search writter or publisher
I want the search form able to get data from other columns named writters and publisher
Is there any method to get data from multiple column?
You can use orwhere to fullfill this, like this
Book::where(function ($query) use($keyword) {
$query->where('judul', 'like', '%' . $keyword . '%')
->orWhere('writters', 'like', '%' . $keyword . '%');
})
->get();
I hope it helps you.
You can execute conditional queries in many ways.
1. You can use when():
Book::when($keyword, function ($q) use ($keyword) {
return $q->where('judul', 'LIKE', '%' . $keyword . '%');;
})
->get();
2. Use the where closure:
Book::where(function($q) use ($keyword, $request) {
if ($request) {
$q->where('judul', 'LIKE', '%' . $keyword . '%');
}
})
->get();
3. Do this:
$books = Book::query();
if ($request) {
$books = $books->where('judul', 'LIKE', '%' . $keyword . '%');
}
$books = $books->get();

laravel search multiple keywords

I have a problem with search form on my website. Basically, when user will type multiple keywords to search form (e.g. business card ) then search result will show all images from keyword 1 (e.g. business) and all images from keyword2 (e.g. card). This is bad, the search form is not relevant at all. Can you please look at the code down bellow and help me fix it so the search form will show only images with both keywords together (keyword1 + AND + keyword2).
public function search($search, $category = null, $timeframe = null)
{
$extends = explode(' ', $search);
if ($category) {
$categoryId = $this->category->whereSlug($category)->first();
}
$images = $this->posts($category, $timeframe)->where('title', 'LIKE', '%' . $search . '%')
->orWhere('tags', 'LIKE', '%' . $search . '%')
->whereNull('deleted_at')->whereNotNull('approved_at')->orderBy('approved_at', 'desc');
foreach ($extends as $extend) {
if (isset($categoryId)) {
$images->whereCategoryId($categoryId)->Where('tags', 'LIKE', '%' . $extend . '%')->whereNotNull('approved_at')->whereNull('deleted_at')
->whereCategoryId($categoryId)->orWhere('title', 'LIKE', '%' . $search . '%')->whereNotNull('approved_at')->whereNull('deleted_at')
->whereCategoryId($categoryId)->orWhere('image_description', 'LIKE', '%' . $search . '%')->whereNotNull('approved_at')->whereNull('deleted_at');
} else {
$images->orWhere('tags', 'LIKE', '%' . $extend . '%')->whereNotNull('approved_at')->whereNull('deleted_at')
->orWhere('title', 'LIKE', '%' . $search . '%')->whereNotNull('approved_at')->whereNull('deleted_at')
->orWhere('image_description', 'LIKE', '%' . $search . '%')->whereNotNull('approved_at')->whereNull('deleted_at');
}
}
return $images = $images->with('user', 'comments', 'favorites')->whereNotNull('approved_at')->whereNull('deleted_at')->paginate(perPage());
}
When you use the % sign before and after the search query, you say "give me anything with that items", if you want your system to search and give results exactly as per what the user has entered, you should use only the key phrase. try the code below.
public function search($search, $category = null, $timeframe = null)
{
$extends = explode(' ', $search);
if ($category) {
$categoryId = $this->category->whereSlug($category)->first();
}
$images = $this->posts($category, $timeframe)
->where('title', 'LIKE', "$search")
->orWhere('tags', 'LIKE', "$search")
->whereNull('deleted_at')
->whereNotNull('approved_at')
->orderBy('approved_at', 'desc');
foreach ($extends as $extend) {
if (isset($categoryId)) {
$images->whereCategoryId($categoryId)->Where('tags', 'LIKE', "$search")
->whereNotNull('approved_at')->whereNull('deleted_at')
->whereCategoryId($categoryId)->orWhere('title', 'LIKE', "$search")
->whereNotNull('approved_at')->whereNull('deleted_at')
->whereCategoryId($categoryId)
->orWhere('image_description', 'LIKE', "$search")
->whereNotNull('approved_at')->whereNull('deleted_at');
}
else {
$images->orWhere('tags', 'LIKE', "$extend")
->whereNotNull('approved_at')->whereNull('deleted_at')
->orWhere('title', 'LIKE', "$search")
->whereNotNull('approved_at')->whereNull('deleted_at')
->orWhere('image_description', 'LIKE', "$search")
->whereNotNull('approved_at')->whereNull('deleted_at');
}
}
return $images = $images->with('user', 'comments', 'favorites')
->whereNotNull('approved_at')
->whereNull('deleted_at')
->paginate(perPage());
}

Laravel sort model by one to many relationship

I have two models Location and Danger
Danger has two fields location_id and user_id it simply save users report about locations
btw Danger has a one to many relation with Location
the question is
how can I sort locations with count of it's danger in a search form
here is my form:
$locations = Location::latest();
if ($request->get('q')) {
$q = $request->get('q');
$locations->where('desc', 'like', '%' . $q . '%')
->orWhere('name', 'like', '%' . $q . '%');
}
$locations=$locations->paginate(12);
return view('list')->with(compact('locations'));
If your location has many danger and your relation is named dangers then you can use withCount() for sorting as:
$locations = Location::withCount('dangers');
if ($request->get('q')) {
$q = $request->get('q');
$locations->where('desc', 'like', '%' . $q . '%')
->orWhere('name', 'like', '%' . $q . '%');
}
$locations->orderBy('dangers_count', 'desc')
$locations=$locations->paginate(12);
this might work.
$locations = Location::latest();
if ($request->get('q')) {
$q = $request->get('q');
$locations->where('desc', 'like', '%' . $q . '%')
->orWhere('name', 'like', '%' . $q . '%');
$locations->sortBy(function($item, $key){
return $location->danger()->count();
})
}
$locations=$locations->paginate(12);
return view('list')->with(compact('locations'));

Resources