Laravel 4: A where and whereIn inside a whereHas using Eloquent - laravel-4

Laravel 4 - advanced Where
I'm trying to retrieve Posts that have a $keyword like a certain Companion and besides that I want to retrieve the Posts the have a linking title or content as the $keyword.
But when I try to use a where or whereIn inside a whereHas the query doesn't take these into account. When the state is 0 (not visible) or not inside the category 1 the Post item should not get selected.
$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id');
The code block below has to do two things:
Search for Post items with a title or content like the $keyword
and search for Post items that have Companions like the $keyword
code:
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id)
->where('state', '=', 1)
->whereIn('category_id', array(1));
})
->whereIn('category_id', array(1))
->orwhere('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' )
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();
The code above retrieves data succesfully except for the where and whereIn parts inside the whereHas.
Who can help me out?

wrap your orWhere clauses in (..)
you don't need where and whereIn in the whereHas closure, since it queries companions table
you don't need whereIn for category_id, unless you want to pass multiple ids there
.
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id);
})
->whereIn('category_id', array(1)) // why not where(..) ?
->where(function ($q) use ($keyword) {
$q->where('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' );
})
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();

Thanks to Jarek Tkaczyk.
His answer was almost correct. All I had to do was wrap the where inside a orWhere. Now I get the Posts that has a Companion like the $keyword and I get the Posts that has the $keyword inside the content or title.
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id)
->where('state', '=', '1');
})
->orWhere( function($q) use ( $keyword ) {
$q->where('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' );
})
->whereIn('category_id', array(1, 3))
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();

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);

How to search using session with multiple table with where caluse using Laravel?

How to do this?
**This code is working **
$posts = NewJob::with(['client_info','office_info'])
->orderBy('won', 'desc')
->where('progress' , 'forwarded')
->where('won', 'like', '%' . $request->session()->get('search') . '%')
->paginate(5);
========================================================================
But when I added more where clause then displaying the blank results.
$posts = NewJob::with(['client_info','office_info'])
->orderBy('won', 'desc')
->where('progress' , 'forwarded')
->where('won', 'like', '%' . $request->session()->get('search') . '%')
->where('proj_name', 'like', '%' . $request->session()->get('search') . '%')
->paginate(5);
This way you can do it.
You can also use one orWhere condition instead of two, according to your need.
$posts = NewJob::with('client_info','office_info')
->orderBy('won', 'desc')
->where('progress' , 'forwarded')
->where('won', 'like', '%' . $request->session()->get('search') . '%')
->orWhere('proj_name', 'like', '%' . $request->session()->get('search') . '%')
->paginate(5);
For joins mean to say relations you can do it something like this.
I have written the code for one of your model, you can do it for other models same like this, and also you can use the closure function in with() function as well. Also you can use orWhereHas on different models as well.
$posts = NewJob::whereHas('client_info', function($query){
$query->where('something','is_something'); //query conditions on other table
$query->orWhere('something','is_something');
})
->orderBy('won', 'desc')
->where('progress' , 'forwarded')
->where('won', 'like', '%' . $request->session()->get('search') . '%')
->orWhere('proj_name', 'like', '%' . $request->session()->get('search') . '%')
->paginate(5);

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();

How to force a where clause on a collection in laravel 5

I have a table that I am running a search on. Foo. I want to check if the search term is like a bunch of different fields in the table. But I want the results to be forced to be "active".
I am using Laravel 5.0
$foos = DB::table('foo')
->where('name', 'LIKE', '%' . $query . '%')
->orWhere('description', 'LIKE', '%' . $query . '%')
->orWhere('address_city', 'LIKE', '%' . $query . '%')
->orWhere('short_description', 'LIKE', '%' . $query . '%')
->orWhere('interview', 'LIKE', '%' . $query . '%')
->get();
$foos = $foos->where('active', true)->get();
Collection has a where method similar to query builder.
$activeFoos = $foos->where('active', true);
https://laravel.com/docs/5.4/collections#method-where
Edit :
I understand what you need from the comments now. Try the code below, and also note that i changed your original $query to $find. So keep that in mind.
$foos = DB::table('foo')
->where('active', true)
->where(function ($query) use ($find) {
$query->where('name', 'LIKE', "%{$find}%")
->orWhere('description', 'LIKE', "%{$find}%")
->orWhere('address_city', 'LIKE', "%{$find}%")
->orWhere('short_description', 'LIKE', "%{$find}%")
->orWhere('interview', 'LIKE', "%{$find}%");
})
->get();
Is the value of active actually true or just truthy (such as an integer of 1)?
For loose comparisons then you'll need to use whereLoose('active', true), otherwise Laravel's method where() on Collections will perform strict type comparisons.
Like Sandeesh said, you'll need to remove the get() since get() is a query builder method, Collections where() methods return a new collection not a builder instance.

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