Laravel Scout, search with where clausure - laravel

I just discovered Laravel Scout and I wanted to make a search with where clausure. The code shown below
$notes = Note::search($request->lecturer_search)->where([
['course_id','=',$course_id],
['course_code_number', '=', $request->course_code_number_search]
])->orderBy('created_at','desc')->paginate(5);
But I'm getting this error:
Type error: Too few arguments to function Laravel\Scout\Builder::where(), 1 passed in /home/vagrant/www/Bee/app/Http/Controllers/SearchController.php on line 36 and exactly 2 expected
When I remove where clausure, there is no problem.

Scout has it's own where() method which accepts just two parameters: field and value. So do this:
->where('course_id', $course_id)
->where('course_code_number', $request->course_code_number_search)
Instead of this:
->where([
['course_id','=',$course_id],
['course_code_number', '=', $request->course_code_number_search]
])
You can look at the source code of the where() method here.
   

I generate to queries.
One via relational search. And on with scout.
Then I reduce the relational results with the results of the scout search.
In your case:
$notes = Note::where([
['course_id','=',$course_id],
['course_code_number', '=', $request->course_code_number_search]
]);
$notesSearchResults = Note::search($request->lecturer_search);
$searchResultIds = $notesSearchResults->map(function ($item, $key) {
return $item['id'];
});
$notes = $notes->whereIn('notes.id', $searchResultIds)->get();

Related

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

How to use count in Query builder Laravel5.6

This is my query builder. But an error is shown
ERROR => count(): Parameter must be an array or an object that implements
Countable
Route::get('project', function () {
$project = DB::table('pams_project')
->join('pams_developer', 'pams_project.dev_id', '=', 'pams_developer.id')
->select(array('pams_developer.developer_name',DB::raw(count('pams_project'.'dev_id'))))
->get();
return view('projectByDeveloper', ['project' => $project]);
});
can anyone figure out my problems ?
use DB::raw("count(pams_project.dev_id) as count")
$project = DB::table('pams_project')
->join('pams_developer', 'pams_project.dev_id', '=', 'pams_developer.id')
->select(array('pams_developer.developer_name',DB::raw("count(pams_project.dev_id) as count")))
->get();
But also make sure to use GroupBy() with this.
If you want to get the count of collection u can simply use $project->count()
Hope this helps

Conditional Join Eloquent

I have been looking through multiple question on stack overflow and also in the eloquent documents and I cannot seem to find how to join a table only if a variable is true.
I have my eloquent query.
$test = false;
$orderBy = 'name'; // Default order by
$sortBy = 'asc'; // Default sort by
$wheres[] = ['is_deleted', '=', $is_deleted];
Comm::where($wheres)
->select($selects)
->join('div', function($join) use($test) {
if($test) {
$join->on('Comm.div_id', '=', 'div.div_id')
}
}
->orderBy($orderBy, $sortBy)
->paginate($per_page, '*', 'page', $page);
Now I know you can join using the document join methods like
->join('div', 'comm.div_id', '=', 'div.div_id')
Is there anyway to accomplish the conditional add I am trying to do? This is for an api and I want the user to be able to specify if they want certain tables included in the returns results. I havent been able to find a post about this type of functionality. When I run my example code with the test if statement i get an error of:
Parse error: syntax error, unexpected '}'
So after a while of trial and error, I found you can use conditional clauses to help with joining tables.
$comm = Comm::select($selects)
->when($useJoins, function($query) use ($withs) {
return $query->with($withs);
})
->orderBy($orderBy, $sortBy)
->paginate($per_page, '*', 'page', $page);
I'm leaving this here for future reference since there is not a very large amount of data for this type of joining. I have also tried it with the eloquent join methods and those also work I just left it in an array for the with for display purposes.

Where clause in With() laravel doesn't work

Hello I have a little problem with eloquent in Laravel 5.
I have this function:
$lists = Model::with(array('relation_with_registered_in_model'=>function($query){
$query->where("name","cccc");
}))->get();
My poblem is that return always all results, ignoring where clause.
I tried to print my query (generated with function) and if I execute the query in my phpmyadmin it return correct filtered results.
What I'm wrong?
You could try with single qoute
$lists = Model::with(array('relation_with_registered_in_model'=>function($query){
$query->where('name','cccc');
}))->get();
I have resolved and Understand my error:
In this posts it is explained https://laracasts.com/discuss/channels/general-discussion/problem-with-the-eager-loading-of-laravel-eloquent-orm?page=1
// gets only models that have relation matching the closure constraint
// no eager loading of the relation!
Model::whereHas('relation', function ($q) { ...} );
// gets ALL models
// and eager loads the relation, but only rows matching the constraint
Model::with(['relation' => function ($q) { ...} ]);

Laravel 4 500 Internal Server Error when query database

I am using code below
$users = DB::table('users')->find(1);
And I got 500 Internal Server Error
but when I use
$users = DB::table('users')->get();
It works, what is the issue with first code snippet?
Using find() with query builder, e.g. DB::table(...)->find() only works if you have primary key (or a column) named "id". Do you have an "id" column?
If not you'll need to use:
$users = DB::table(...)->where('your_primary_key', '=', 1)->first();
Reference: framework/src/Illuminate/Database/Query/Builder.php:
public function find($id, $columns = array('*'))
{
return $this->where('id', '=', $id)->first($columns);
}

Resources