Laravel where clause not returning expected result - php

While making a request to my Laravel database something goes wrong. I'm trying to get different recipes on user input but Postman is returning 'No recipes found'.
My Laravel controller code:
public function search(Request $request) {
$fields = $request->validate([
'search' => 'required|string'
]);
// return response($request);
$recipes = Recipe::where('title', 'LIKE', '%'.$request.'%')->get();
if (count($recipes) > 0 ) {
return response($recipes);
} else {
return response('No recipes found');
}
}
if I return the response it returns "search": "maken" with the request http://127.0.0.1:8000/api/search?search=maken.
When I however hardcode the where clause to $recipes = Recipe::where('title', 'LIKE', 'maken')->get(); it returns some recipes and the search function works. Now I'm not sure whether the error is in my Postman request or in my search function in Laravel. Any help would be greatly appreciated!

You have to use $request->INPUT_NAME or $request->input('name') to get the value, so your code should be:
$recipes = Recipe::where('title', 'LIKE', '%'.$request->search.'%')->get();

Try this way
$recipes = Recipe::where('title', 'like', '%' . request('search') . '%')->get();
if ($recipes->count() > 0 ) {
return response($recipes);
} else {
return response('No recipes found');
}

Related

Multiline Eloquent query

I'm trying to filter my products based on selected filters and possibly a search term/word. My filters have a relationship with categories, which in their turn have a relation ship with my products. My code below only works (without the if statement checking for a search term/word) when everything is chained together, but when I try to break the query into multiple lines (which I've read is possible, right?) it returns an empty array.
Here's a my code:
// Create array from selected categories/filters
$filter_ids = explode(',', $request->get('cats'));
// Query for active products
$products = Product::where('active', '=', 1);
$products->with(['categories' => function($query) use ($filter_ids) {
// Query for active categories
$query->where('active', 1)->whereHas('filters', function ($query) use ($filter_ids) {
// Query for the selected filters from the request
$query->whereIn('id', $filter_ids);
});
}]);
// Check for search term/word
if ($request->get('q')) {
$q = $request->get('q') ? urldecode($request->get('q')) : null;
$products->where('title', 'LIKE', "%{$q}%");
}
// Limit to 10 items and get results
$products->limit(10)->get();
return response()->json([
'status' => 'success',
'response' => $products
], 200);
I think you could but don't need to query all products with title first, before adding the relationships. But whats wrong here is that you must store the result of get() in a variable before adding it to your json response body:
Try to do something like:
if ($request->get('q')) {
$q = $request->get('q') ? urldecode($request->get('q')) : null;
$products->where('title', 'LIKE', "%{$q}%");
}
$products->with(['categories' => function($query) use ($filter_ids) {
// Query for active categories
$query->where('active', 1)->whereHas('filters', function ($query) use ($filter_ids) {
// Query for the selected filters from the request
$query->whereIn('id', $filter_ids);
});
}]);
$response = $products->limit(10)->get();
return response()->json([
'status' => 'success',
'response' => $response
], 200);
Lukas' answer led me to do some more debugging and eventually solving my problem, though it was not the position of the if statement checking if there's a search term/word.
The problem lies in the following line:
$products->limit(10)->get();
I needed to store the retrieved results from the get(); method in another variable, in my case:
$response = $products->limit(10)->get();
I eventually ended up with the following working code:
// Create array from selected categories/filters
$filter_ids = explode(',', $request->get('cats'));
// Query for active products
$products = Product::where('active', '=', 1);
$products->with(['categories' => function($query) use ($filter_ids) {
// Query for active categories
$query->where('active', 1)->whereHas('filters', function ($query) use ($filter_ids) {
// Query for the selected filters from the request
$query->whereIn('id', $filter_ids);
});
}]);
// Check for search term/word
if ($request->get('q')) {
$q = $request->get('q') ? urldecode($request->get('q')) : null;
$products->where('title', 'LIKE', "%{$q}%");
}
// Limit to 10 items, get results and store in '$response'
$response = products->limit(10)->get();
return response()->json([
'status' => 'success',
'response' => $response
], 200);

Invalid entry in my search bar in Laravel

I created a search bar, it works well so far. I would like to improve my search bar.
When I enter a name which is not in my listing I will wish to stay on my page index with all the recordings.
For example: If I enter leonard as name
I have a page empty...
Is it possible to stay on my page index with my recordings ?
Here's my relevant code:
public function index(Request $req)
{
if ($req->has('search') && !empty($req->search)) {
$validated = $req->validate([
'search' => 'alpha',
]);
$students = Student::where('name', 'LIKE', '%' . $validated['search'] . '%')->orderBy('name', 'ASC')->paginate(5);
$students->appends($req->only('search'));
return view('admin.students.index', compact('students'));
}
$students = Student::orderBy('name', 'ASC')->paginate(5);
return view('admin.students.index', compact('students'));
}

Laravel if request not empty add orWhere

public function index(Request $request) {
if ($request->has('deleted')) {
$assistants = Assistant::onlyTrashed()->where(1);
if ($request->has('firstName'))
$assistants = $assistants->orWhere('firstname', 'LIKE', $request->firstName.'%');
if ($request->has('lastName'))
$assistants = $assistants->orWhere('lastname', 'LIKE', $request->lastName.'%');
if ($request->has('email'))
$assistants = $assistants->orWhere('email', 'LIKE', $request->email.'%');
} else {
$assistants = Assistant::all()->where(1);
if ($request->has('firstName'))
$assistants = $assistants->orWhere('firstname', 'LIKE', $request->firstName.'%');
if ($request->has('lastName'))
$assistants = $assistants->orWhere('lastname', 'LIKE', $request->lastName.'%');
if ($request->has('email'))
$assistants = $assistants->orWhere('email', 'LIKE', $request->email.'%');
}
return $this->showAll($assistants);
}
I am trying to check if firstName, lastName or email is not empty, add to query with LIKE command.
But it returns an error :
Type error: Too few arguments to function
Illuminate\Support\Collection::where(), 1 passed
in Laravel 5.6.
You have multiple problems.
where(1) is not a valid Query Builder call. You also don't seem to need this.
You don't need to repeat all of these request->has() calls, put them below the if ... else ...
Assistants::all() will actually run a query and return all rows in a collection. Use Assistants::query() to return a Query Builder instance.

Search all method missing where argument in Laravel 5

I'm trying to write a method in my controller to allow searching the results of my query on my view page. The query selects all results from the "ads" table and this method should allow filtering results by the ad's name inputting keywords in the search bar.
The controller code goes like this:
public function index(Request $request)
{
$title = trans('ad.title');
$ads = Ad::paginate(10);
if (!empty($request->input('search_all'))) {
$search_all = urldecode($request->input('search_all'));
$ads->where(function ($query) use ($search_all) {
$query->where('name', 'like', '%'.$search_all.'%')->get();
});
}else {
// Returning to view
return view('admin.ad.list')
->with('ads', $ads)
->with('title', $title);
}
}
However, when I run a search I get the following error: "Missing argument 2 for Illuminate\Support\Collection::where()".
What am I doing wrong?
At the top, when doing $ads = Ad::paginate(10); you have already pulled the results from the database so no more filtering can be done at DB level.
I'd do something like this instead:
public function index(Request $request)
{
$title = trans('ad.title');
$ads = Ad::select();
if ($request->input('search_all')) {
$search_all = urldecode($request->input('search_all'));
$ads->where('name', 'like', '%'.$search_all.'%');
}
// Returning to view
return view('admin.ad.list')
->with('ads', $ads->paginate(10))
->with('title', $title);
}

How to combine multiple methods without repeating queries in Controller?

I have a method index
protected function index(Request $request)
{
$articles = Article::published()->paginate(8);
return view('pages.blog', [
'articles' => $articles,
'orientation' => $this->getOrientation(),
$this->getCategory($request)
]);
}
And a method getCategory()
public function getCategory($request)
{
if ($request->has('category')){
$search = $request->get('category');
$articles = Article::published()
->where('orientation', 'LIKE', '%' . $search . '%')
->paginate(8);
return view('pages.blog', [
'articles' => $articles,
'orientation' => $this->getOrientation()
]);
}
}
As you can see, I try to get my getCategory function outside of my index function.
It works, only, with my debug bar, I have all the SQL queries (those of index and those of getCategory).
Is it possible to optimize my code? Can you help me ?
Thank you
If you need both results add cache for query in index and get full result from cache.
Or if you have all results maybe use collections filter for same your collection from index and provide display data what you need.
For example getCategory add param where you set your collection from index. In article add filter to get only data what you are interest in.
I'm nowhere near an editor to chekc this, but here goes. First function:
public function index(Request $request)
{
$articles = Article::published()->paginate(8);
return view('pages.blog', [
'articles' => $articles,
'orientation' => $this->getOrientation(),
//$this->getCategory($request) - this i don't think can work like this. You are calling
//a function that does not return a value, but instead loads a view, insted:
'categories' => $this->getCategory($request)//the idea here is you call a function and
//get a return as an array
]);
}
Second function:
public function getCategory($request)
{
if ($request->has('category')){
$search = $request->get('category');
$articles = Article::published()
->where('orientation', 'LIKE', '%' . $search . '%')
->paginate(8);
$result = [
'articles' => $articles,
'orientation' => $this->getOrientation()
];
}
else $result = null;
return $result;
}
This might work, once again, im a noob. But i don't see why you need 2 methods for this since there is a if ($request->has('category')){ which will yield a null. Idk, give it a try...

Categories