Laravel Condition Query Not Working - php

My Requirements : I select baseleads table with Random Order using following conditions
beaseleads currentstatus column value have New Lead Status or
beaseleads currentstatus column value have Call Not Picking status and updated_at date is not Equal to Today Date.
My Laravel Query is below
$baseleadsData=Baseleads::inRandomOrder()->Where('process_status',0)->where(function ($query) {
$query->where('current_status','New Lead');
$query->Orwhere('current_status','Call Not Picking');
$query->OrwhereDate('updated_at', '!=', date('Y-m-d'));
})->first();
Its not Working Properly. What is my Mistake.

->where(function ($query) {
$query->where('current_status','New Lead')
->orWhere('current_status','Call Not Picking')
->orWhere('updated_at', '!=', date('Y-m-d').' 00:00:00');})->first();

It's been a while since I used Laravel, but have you tried
$query->where('current_status', '=', 'New Lead');
$query->Orwhere('current_status', '=', 'Call Not Picking');
instead of
$query->where('current_status','New Lead');
$query->Orwhere('current_status','Call Not Picking');
I'm not sure this will work as it looks like Laravel automatically makes the comparison. What is the error code youre getting? (You can turn debug mode on in your settings file)

you need to use method names in camelCase
use orWhere and orWhereDate

You did mistake of method name, use Orwhere to orWhere, OrwhereDate to orWhereDate and Where to where. and orWhereDate outside of where query.
$baseleadsData=Baseleads::inRandomOrder()
->where('process_status',0)
->where(function ($query) {
$query->where('current_status','New Lead');
$query->orWhere('current_status','Call Not Picking');
})
->orWhereDate('updated_at', '!=', date('Y-m-d'))
->first();

Related

How to add a where clause when using "with" on an Eloquent query in Laravel

I have a query built where I'm using "with" to include related models. However, I'm not sure how to filter those related models in a where clause.
return \App\Project::with("projectLeaders")->join('companies', 'company_id', '=', 'companies.id')
->join('project_status', 'project_status.id', '=', 'projects.status_id')
->select('companies.*', 'project_status.name AS statusName', 'projects.*');
Please note the with("projectLeaders") in the query. So, ProjectLeaders is a relation that brings objects of kind Employee, how can I filter in that query those "Employees" whose attribute "Lastname" is like "Smith" ?
You can implement where class both tables. Please check following code and comments.
return \App\Proyecto::with(["projectLeaders" => function($query){
$query->where() //if condition with inner table.
}])->join('empresas', 'id_empresa', '=', 'empresas.id')
->join('tipo_estado_proyecto', 'tipo_estado_proyecto.id', '=', 'proyectos.id_tipo_estado_proyecto')
->where() //if condition with main table column.
->select('empresas.*', 'tipo_estado_proyecto.nombre AS nombreEstadoProyecto', 'proyectos.*');
You can use Closure when accessing relation using with. Check below code for more details:
return \App\Project::with(["projectLeaders" => function($query){
$query->where('Lastname', 'Smith') //check lastname
}])->join('companies', 'company_id', '=', 'companies.id')
->join('project_status', 'project_status.id', '=', 'projects.status_id')
->select('companies.*', 'project_status.name AS statusName', 'projects.*');
You may use the where method on a query builder instance to add where clauses to the query. The most basic call to where requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. Finally, the third argument is the value to evaluate against the column.
return \App\Project::with("projectLeaders")->join('companies', 'company_id', '=', 'companies.id')
->join('project_status', 'project_status.id', '=', 'projects.status_id')
->where('lastname','=','Smith')
->select('companies.*', 'project_status.name AS statusName', 'projects.*');
Don't forget to return results with a get();
The query you have written is correct. But after building the query you need to fetch the data from database.
METHOD ONE
So adding get() method to your query:
return App\Project::with('projectLeaders')
->leftJoin('companies', 'company_id', '=', 'companies.id')
->leftJoin('project_status', 'project_status.id', '=', 'projects.status_id')
->select('companies.*', 'project_status.name AS statusName', 'projects.*')
->get();
METHOD TWO (with pagination)
return App\Project::with('projectLeaders')
->leftJoin('companies', 'company_id', '=', 'companies.id')
->leftJoin('project_status', 'project_status.id', '=', 'projects.status_id')
->select('companies.*', 'project_status.name AS statusName', 'projects.*')
->paginate(3);

Laravel: where condition based on db field

How to make a whereclause that is based on an existing field in the database, and not on an input parameter?
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
});
This works well because the where clause is based on an input parameter.
What I need is a Where clause that is based on a field that is already in the database:
Something like this:
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
//If db field of record: recurrent == 0 then
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
/* If db field of record: "recurrent" == "1" then
$join->where //another query
*/
});
Is this achievable with the laravel ORM, or should I write a native SQL query?
Haven't found a suitable answer in the docs or in existing posts.
You need to use...
where('column1', '=', DB::raw('column2'));
...to use the field value instead of the string "column2".
In this answer I further explained why.

Call to undefined method Illuminate\Database\Query\Builder

I am new to laravel 4 and keep getting the same error trying to learn about some methods in DB class.
Call to undefined method Illuminate\Database\Query\Builder
I get same erros trying to use "->or_where", "->order_by".
another problem is parsing the dynamic methods:
->where_name("test")
turns into
`users` where `_name` = test)
but if i try to do
->wherename("test")
then everything is fine.
You're using an incorrect syntax for orWhere and orderBy.
This is the correct syntax for orWhere:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
And this for orderBy:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
Query Builder - Advanced Wheres - Laravel
All methods in Laravel 3 have changed from snake case
->where_name("test")
to camel case in Laravel 4
->whereName("test")

laravel multiple where clauses within a loop

Pretty much I want the query to select all records of users that are 25 years old AND are either between 150-170cm OR 190-200cm.
I have this query written down below. However the problem is it keeps getting 25 year olds OR people who are 190-200cm instead of 25 year olds that are 150-170 OR 25 year olds that 190-200cm tall. How can I fix this? thanks
$heightarray=array(array(150,170),array(190,200));
$user->where('age',25);
for($i=0;$i<count($heightarray);i++){
if($i==0){
$user->whereBetween('height',$heightarray[$i])
}else{
$user->orWhereBetween('height',$heightarray[$i])
}
}
$user->get();
Edit: I tried advanced wheres (http://laravel.com/docs/queries#advanced-wheres) and it doesn't work for me as I cannot pass the $heightarray parameter into the closure.
from laravel documentation
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
Like Jeemusu and the OP stated, you need to use advance wheres.
But if you want to pass a variable to the closure function you need to make use of the "use" approach:
$heightarray = array(array(150,170),array(190,200));
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query) use ($heightarray){
//...
})
->get();
I found the answer. I need to include "use" in the closure to pass my $heightarray variable in. Once $heightarray is in then laravel's advance wheres work.
$heightarray=array(array(150,170),array(190,200));
$user->where('age',25);
$userprofile->Where(function($query) use ($heightarray) {
for($i=0;$i<count($heightarray);i++){
if($i==0){
$user->whereBetween('height',$heightarray[$i])
}else{
$user->orWhereBetween('height',$heightarray[$i])
}
}
});
$user->get();
This is completely untested, but looking at the documentation for advance wheres, it would seem you want to try something like this:
DB::table('users')
->where('age',25)
->Where(function($query)
{
for($i=0;$i<count($heightarray);i++){
if($i==0){
$query->whereBetween('height', $heightarray[$i]);
}else{
$query->orWhereBetween('height', $heightarray[$i]);
}
}
})->get();

Using Distinct in Laravel Fluent

I have this join:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->where('is_published', '=', 1)
But it unsurprisingly returns duplicate records, so I try to use distinct():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
but I want to use distinct() on a specific single field which I'd easily be able to do in SQL. It seems distinct() does not take parameters, i.e. I can't say distinct('volunteer.id').
Can anyone point me to how can I remove my duplicate records? I bet this is another forehead slapper for me.
In my project I tried distinct() and groupby() too and both of them worked:
//Distinct version.
Company_Customer_Product::where('Company_id', '=', $companyid)->distinct()->get(array('Customer_id'));
//Goup by version.
Company_Customer_Product::where('Company_id', '=', $companyid)->groupby('Customer_id')->get(array('Customer_id'));
According to this, distinct() should work in your case too, just use it with get():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
->get(array('volunteer.id'));
Otherwise you don't need distinct() when you use groupby() so you could just use:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->group_by('volunteer.id')
->where('is_published', '=', 1)
->get(array('volunteer.id'));

Categories