whereBetween doesnt exist and i cant apply paginate - laravel

I've this method:
public function indexGuest($idAzienda, Request $request){
$companyId = $idAzienda;
$ddts = Ddt::where('company_id',$companyId);
$ddt_urls= Ddt_file_url::all();
if($request->start_date || $request->end_date){
$ddts->whereBetween('created_at',[new Carbon($request->start_date),new Carbon($request->end_date)]);
}
$ddts->paginate(10);
return view('guest.ddt-management')->with('ddts', $ddts)->with('ddt_urls',$ddt_urls)
->with('companyId',$companyId);
}
My start_date and end_date comes in strings like "yyyy-mm-dd".
I've tried to pass it straight to the query and like in the example like a carbon object with no hope!
After executing the query (now only the one without the wherebeeteween clause) i cant apply the method "paginate" to the collection, no error are raised but when i pass it to the view, the "link()" method not work and raise an error again.
where I wrong?
Laravel 5.4

Structure your wheres like this.
public function indexGuest($idAzienda, Request $request) {
[...]
$ddts = Ddt::where('company_id', $companyId)
->where(function($query) use ($request) {
if($s = $request->get("start_date") {
$s_date = Carbon::parse($s)->format("Y-m-d");
$query->whereDate("created_at", ">=", $s_date);
}
if($e = $request->get("end_date") {
$e_date = Carbon::parse($e)->format("Y-m-d");
$query->whereDate("created_at", "<=", $e_date);
}
})
->paginate(10);
[...]
}

Related

Query builder didn't find data when using %

I'm trying to use query builder in controller using laravel, and i don't understand but the query didn't find the data.
Here's the code:
public function index()
{
$data = downloads::all();
if(request('searchName')){
$data = $data->where('fileName','like','%'.request('searchName').'%'); //Here's the problem
return view('download', compact('data'));
}
else{
return view('download', compact('data'));
}
}
i already tried dd(request('searchName')) and it display the input that i give, so there's no problem here
when I'm using $data->where('fileName','like','%'.request('searchName').'%') there's no data shown
i don't think that i misspell the fileName because when I'm using $data->where('fileName','like',request('searchName')) and it worked and display the file, but the fileName must be exactly the same as the inputed searchName, and of course what i wanted is not this
even when I'm using dd('%'.request('searchName').'%'); it will display "%*searchName*%" that's why i so confused when it didn't work when I'm using $data->where('fileName','like','%'.request('searchName').'%');
I even using SELECT * FROM *tables* WHERE fileName LIKE '%p%'; in SQL Workbench and it worked perfectly fine
Any suggestion of what should i do? Thank you
This looks odd. Why are you filtering the collection instead of adding the where conditional in your query?
Imagine you have thousands of download records but the where condition just match with a few ones, you will be fetching everything just for showing some of them.
IMO, a better approach should be
public function index(Request $request)
{
$data = downloads::
when($request->has('searchName'), function($query) use ($request){
$query->where('fileName','like','%'.$request->searchName.'%');
})
->get();
return view('download', compact('data'));
}
all() is static method not query builder.If you see internal of all() code then its calling get method
/**
* Get all of the models from the database.
*
* #param array|mixed $columns
* #return \Illuminate\Database\Eloquent\Collection|static[]
*/
public static function all($columns = ['*'])
{
return static::query()->get(
is_array($columns) ? $columns : func_get_args()
);
}
There are few ways to solve this .
public function index()
{
$downloads = downloads::query();
if(!empty(request('searchName'))){
$downloads->where('fileName','like','%'.request('searchName').'%');
}
$data=$downloads->get();
return view('download', compact('data'));
}
or
public function index()
{
$data = downloads::when(!empty(request('searchName')),function($query){
$query->where('fileName','like','%'.request('searchName').'%');
})->get();
return view('download', compact('data'));
}
You are trying to apply your querystring with like in a collection. In a collection, you can use the filter($callback_function) method to select elements in the collection. Pass a callback function that returns true for each element to be returned.
In your case, you can use the stristr() function to emulate a LIKE operator, something like this:
collect($data)->filter(function ($item) use ($searchName) {
return false !== stristr($item->fileName, $searchName);
});

Orwhere has method does not allow null

enter image description hereI am trying to implement a many to many relationship search with 2 models.
i get input from multiple checkbox values and want to search for items that match A or B when there is an input of data.
I read this url and wrote the same logic.
https://laracasts.com/discuss/channels/laravel/many-to-many-relationship-with-2-pivot-table-data-search
public function search(Request $request)
{
$languages = $request->lang;
$fields = $request->field;
$agencies = Agency::with('languages')->with('specialized_fields')
->orWhereHas('languages', function($query) use ($languages) {
$query->whereIn('language_id', $languages);
})
->orWhereHas('specialized_fields', function($query) use ($fields) {
$query->whereIn('specialized_field_id', $fields);
})
->get();
dd($agencies);
}
i expected to achieve A or B search but instead I got this error.
Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given, called in /var/www/jtf/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 907
it seems that it causes this error if either A or B is null, but why??? Does the OrWhereHas method work only when theres an input??
/added info/
my error message
my agency model
class Agency extends Model {
protected $guarded = [
'id'
];
public function languages(){
return $this->belongsToMany('App\Language');
}
public function specialized_fields(){
return $this->belongsToMany('App\SpecializedField');
}
public function region(){
return $this->hasOne('App\Region');
} }
I believe it's because either $languages or $fields is null.
Since ->whereIn() is expecting an array, but you're passing null.
You just need to make sure you're passing an array.
$languages = array_filter((array) $request->lang); // cast to array & remove null value
$fields = array_filter((array) $request->field);
$agencies = Agency::with('languages', 'specialized_fields')
->orWhereHas('languages', function($query) use ($languages) {
$query->whereIn('language_id', $languages);
})
->orWhereHas('specialized_fields', function($query) use ($fields) {
$query->whereIn('specialized_field_id', $fields);
})
->get();
I'm speculating that you started your where query chain with an orWhereHas() which may have caused the problem, try starting with whereHas() instead.
public function search(Request $request){
$languages = $request->lang;
$fields = $request->field;
$agencies = Agency::with('languages', 'specialized_fields') // you can get away by just using one with(), not needed but its cleaner this way
->whereHas('languages', function($query) use ($languages) { // previously orwherehas
$query->whereIn('language_id', $languages);
}) ->orWhereHas('specialized_fields', function($query) use ($fields) {
$query->whereIn('specialized_field_id', $fields);
})
->get();
dd($agencies);
}

Laravel Eloquent Accessor Strange Issue

Laravel Version: 5.6.39
PHP Version: 7.1.19
Database Driver & Version: mysql 5.6.43
Description:
When I chain where and orWhere in a model accessor to count related model , I get wrong result and here is my query. the count is returned strange result without filtering by the calling event id,
class Event extends Model
{
protected $table = 'events';
public function registrations()
{
return $this->hasMany('App\Components\Event\Models\Registration','event_id','id');
}
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where('reg_status','=','Confirmed')
->orWhere('reg_status','=','Reserved')
->count();
}
}
Steps To Reproduce:
the following queries return me the expected results, however In my knowledge the first query should return the same result if i am not wrong, so i think this is a potential bug.
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->whereIn('reg_status', ['Confirmed', 'Reserved'])
->count();
}
}
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where(function($query){
$query->where('reg_status','Confirmed')
->orWhere('reg_status','Reserved');
})
->count();
}
}
and here is the query dump,
here is the query when I donot explicit group it.
"select count(*) as aggregate from events_registration where (events_registration.event_id = ? and events_registration.event_id is not null and reg_status = ? or reg_status = ?) and events_registration.deleted_at is null "
and here is the query when i group it explicitly,
select count(*) as aggregate from events_registration where events_registration.event_id = ? and events_registration.event_id is not null and (reg_status = ? or reg_status = ?) and events_registration.deleted_at is null
The reason this happens is because you're chaining where() and orWhere(). What you don't see behind the scenes is a where event_id = :event_id applying to your query. You end up with a query that looks something like this:
select * from registrations where event_id = :event_id and reg_status = 'Confirmed' or reg_status = 'Reserved'
In normal SQL you'd want to put the last 2 conditions in parentheses. For Eloquent, you'd need to do something like this:
return $this->registrations()->where(function ($query) {
$query->where('reg_status', 'Confirmed')
->orWhere('reg_status', 'Reserved');
});
You can chain the toSql() method on these chains to see the difference. Note, that in this case, I believe whereIn() is the semantically correct thing to do.
Eloquent can handle this for you, though; scroll down to "Counting Related Models" in the Querying Relations part of the Eloquent Relationships docs:
$posts = App\Event::withCount([
'registrations as seats_booked_count' => function ($query) {
$query->where('reg_status','Confirmed')
->orWhere('reg_status','Reserved');
}
])->get();

How to execute laravel WHERE along with EloquentFilter

I am using this EloquentFilter to filter Database on the frontend and the controller below works
public function indexArtisan(Request $request)
{
$workers = Worker::filter($request->all())->get();
$states = DB::table('states')->pluck("name", "id");
return view ('artisans', compact('states'))->with(['workers' => $workers]);
}
However, when i try to use the WHERE query to add conditions to the data been called with the controller, the WHERE condition is met and data returned but my filter no longer works. domain.com?name=xyz
public function indexArtisan(Request $request)
{
$work = DB::table('workers')->where('career', '=', 'artisan')->get();
$workers = Worker::filter($request->all())->get();
$states = DB::table('states')->pluck("name", "id");
return view ('artisans', compact('states','work'))->with(['workers' => $workers]);
}
Also tried
$work = DB::table('workers')->where('career', '=', 'artisan')->get();
$worker = $work->filter($request->all());
$states = DB::table('states')->pluck("name", "id");
return view ('artisans', compact('states'))->with(['worker' => $worker]);
I get
How do i execute the WHERE condition without breaking the filter
I've read https://laravel.com/docs/5.6/queries#conditional-clauses i still cant figure out what i'm doing wrong.
If you use $work->filter($request->all()); the filter() method is the method of collection class, because $work is a collection now.
So, you need to use filter() method of model class
DB::table('workers')->where('career', 'artisan')->filter($request->all())->get();
should work.

Return first element from relation with `Lazy Eager Loading` [Laravel 5.2]

I have relation like this:
public function message()
{
return $this->hasMany('Engine\Message');
}
inside my Conversation model.
and for each conversation I need to get last message.
Here is what I tried, but this will get only one message for first conversation but will not get message from other conversations...
$con = Conversation::all();
$con->load(['message' => function ($q) use ( &$mess ) {
$mess = $q->first();
}]);
return $con;
I don't wana query for each record... Anyone know how to solve this problem?
As suggested here!
Don't use first() or get() in eager loadings you should create a new relationship in the model.
The model would look something like this...
public function message()
{
return $this->hasOne('Engine\Message');
}
kudos to 'pmall'
Try
$con = Conversation::all();
$con->load(['message' => function ($q) use ( &$mess ) {
$q->orderBy('created_at', 'desc')->take(1);
// or if you don't use timestamps
// $q->orderBy('id', 'desc')->take(1)
}]);
return $con;

Resources