laravel query builder or inside where - sql

I have the following query and i want to know if this is possible in laravel's querybuilder:
SELECT * FROM table WHERE (column = value OR column = value2) AND column2 LIKE '%value3%'

Your query should look like this:
DB::table('table')
->where(function($q) use ($value, $value2) {
$q->where('column', $value)
->orWhere('column', $value2);
})
->where('column2', 'like', '%'.%value3.'%')
->get();
If you have multiple values, you can put them into a simple array and use whereIn():
DB::table('table')
->whereIn('column', $valuesArray)
->where('column2', 'like', '%'.%value3.'%')
->get();

you can use closure in where for ex.
\DB::table('table_name')
->where(function($q){
$q->where('column', 'value1')
->orWhere('column', 'value2');
})
->where('column2', 'LIKE', '%value3%');
check here https://laravel.com/docs/5.3/queries#parameter-grouping

You can do this according to make desired query
DB::table('table_name')
->where('column', 'value1')
->orWhere('column', 'value2')
->where('column2', 'like', '%value3%');

Related

How count by the first letters in Laravel Query Builder?

I want to make a count by the first letters... I have this column
I would like to count each OE rows and each GICS rows
I'm working with this query
$data4 = DB::table('incidencias')
->select(DB::raw('grupo_asig as grupo_asig'), DB::raw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
->orderBy('number', 'desc')
->get();
Use CASE WHEN and count the field like OE and ASIG
$data4 = DB::table('incidencias')
->select(DB::raw("(CASE WHEN grupo_asig LIKE 'OE%' THEN 'OE'
WHEN grupo_asig LIKE 'GICS%' THEN 'GICS'
END) AS grupo_asig_type"),
DB::raw('COUNT(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig_type')
->orderBy('number', 'desc')
->get();
You should try to use the [LIKE][1] function then and add it to your query:
->where('grupo_asig', 'like', 'OE%')
->where('grupo_asig', 'like', 'GICS%')
Edit:
I tried a lot around and came to this solution and made a SQL fiddle: http://sqlfiddle.com/#!9/06a39b/8
Does it help you?
You could use Collections. No real need to change your query much.
$data4 = DB::table('incidencias')
->select('grupo_asig')
->selectRaw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
// ->orderBy('number', 'desc') Unless you use this array somewhere, it's not needed.
->get();
use Illuminate\Support\Str;
...
// php >= 7.4.0
$oe_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'OE '))->count();
$gigs_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'GIGS '))->count();
// php < 7.4.0
$oe_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'OE ');
})->count();
$gigs_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'GIGS ');
})->count();
Starting with Laravel 6, you can also use cursor() instead of get() in your query to return a LazyCollection. It's faster for this scenario.
I would suggest using a query for that:
refer to this answer
SELECT
LEFT(grupo_asig, 1) AS first_letter,
COUNT(*) AS total
FROM incidencias
GROUP BY first_letter

whereHas is not working on NULL value

in laravel 5.5 whereHas() is not working on where value is NULL. my relationship with other model is one to many and and i want to pick the values from the model where value is equal to NULL . But instead of returning the specific values its returning all the value in result
plans = Plan::with('objectives')->with('objectives.keyResults')
->whereHas('objectives', function($query) {
$query->whereNull('entity_id');
$query->whereNull('quarter_id');
})->where('companyKey', Auth::user()->companyKey)->get();
You have to specify the constraint twice:
$plans = Plan::with(['objectives' => function($query) {
$query->whereNull('entity_id');
$query->whereNull('quarter_id');
}, 'objectives.keyResults'])
->whereHas('objectives', function($query) {
$query->whereNull('entity_id');
$query->whereNull('quarter_id');
})->where('companyKey', Auth::user()->companyKey)
->get();
No double constraints are needed, simplify it to:
$plans = Plan::whereHas('objectives', function($query) {
$query->whereNull('entity_id');
$query->whereNull('quarter_id');
})->with(['objectives'])
->where('companyKey', Auth::user()->companyKey)
->get();

Laravel 5 Eloquent where and or in Clauses

i try to get results from table with multiple where and/or clauses.
My SQL statement is:
SELECT * FROM tbl
WHERE m__Id = 46
AND
t_Id = 2
AND
(Cab = 2 OR Cab = 4)
How i can get this with Laravel Eloquent?
My Code in Laravel is:
$BType = CabRes::where('m_Id', '=', '46')
->where('t_Id', '=', '2')
->where('Cab', '2')
->orWhere('Cab', '=', '4')
->get();
Using advanced wheres:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
Or, even better, using whereIn():
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->whereIn('Cab', $cabIds)
->get();
Also, if you have a variable,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
When we use multiple and (where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.
$feedsql = DB::table('feeds as t1')
->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
->where('t2.status', 1)
->whereRaw("t1.published_on <= NOW()")
>whereIn('t1.groupid', $group_ids)
->where(function($q)use ($userid) {
$q->where('t2.contact_users_id', $userid)
->orWhere('t1.users_id', $userid);
})
->orderBy('t1.published_on', 'desc')->get();
The above query validate all where condition then finally checks
where t2.status=1 and
(where t2.contact_users_id='$userid' or where t1.users_id='$userid')

Select sql code in Laravel

Following query returning six values
SELECT tbl_start FROM timetable inner join route ON tbl_rte_id = id WHERE rte_origin = "UL" and rte_destination = "HW" ORDER BY(tbl_start) DESC;
And my laravel code is returning only one value
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'id')
->where('rte_origin', $origin, 'AND')
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get();
foreach ($tables as $table) {
$result[$table->id] = $table->tbl_start;
}
This laravel code is not similar or similar. Can anyone help me.
Change this part:
->where('rte_origin', $origin, 'AND')
// to:
->where('rte_origin', $origin)
It will know by default that it's AND operator
And if you want to provide this operator, then do this:
->where('rte_origin', '=', $origin, 'AND')
You may try something like this:
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'timetable.id')
->where('rte_origin', $origin)
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get()->lists('tbl_start', 'id');
The $tables will contain an array of id => tbl_start pairs.
Add a listener in your routes.php
Event::listen('illuminate.query', function($sql){
var_dump($sql);
});
Then execute both queries and check if you have the same result

Using Eloquent ORM in Laravel to perform search of database using LIKE

I want to use Eloquent's active record building to build a search query, but it is going to be a LIKE search. I have found the User::find($term) or User::find(1), but this is not generating a like statement. I'm not looking for a direct answer, but if someone could at least give me a direction to look in that'd be great!
You're able to do database finds using LIKE with this syntax:
Model::where('column', 'LIKE', '%value%')->get();
If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:
public function scopeLike($query, $field, $value){
return $query->where($field, 'LIKE', "%$value%");
}
So then you can use this method in such way:
User::like('name', 'Tomas')->get();
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
Use double quotes instead of single quote eg :
where('customer.name', 'LIKE', "%$findcustomer%")
Below is my code:
public function searchCustomer($findcustomer)
{
$customer = DB::table('customer')
->where('customer.name', 'LIKE', "%$findcustomer%")
->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
->get();
return View::make("your view here");
}
If you do not like double quotes like me, this will work for you with single quotes:
$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();
return view('pages/search/index', compact('books'));