laravel eloquent where and multiple or where - mysql

I'm using the Laravel Eloquent query builder and i want to have advance queries inside when clause
my eloquent :
bank::where('shop_id', $shopId)
->when(($search != ""), function ($query) use ($search) {
return $query->orWhere('bank_name', 'like', '%'.$search.'%')
->orWhere('account_name', 'like', '%'.$search.'%')
->orWhere('account_number', 'like', '%'.$search.'%');
})->toSql();
sql from eloquent :
select * from bank
where shop_id = 1
and bank_name like '%Bank%' or
account_name like '%Bank%' or
account_number like '%Bank%'
sql result that i want:
select * from bank
where shop_id = '1'
and (bank_name like '%Bank%' or
account_name like '%Bank%' or
account_number like '%Bank%')
i can use subquery but its not efficient.

You need to use the closure form of where around the or wheres:
bank::where('shop_id', $shopId)
->when(($search != ""), function ($query) use ($search) {
return $query->where(function ($query) use ($search) {
return $query
->orWhere('bank_name', 'like', '%'.$search.'%')
->orWhere('account_name', 'like', '%'.$search.'%')
->orWhere('account_number', 'like', '%'.$search.'%');
})
})
->toSql();

Related

Multiple value Search in Laravel Query Builder

Here is my code
$search_term = "Hary Kumar";
$filterData = DB::table('signups')->where('name','LIKE',"%{$search_term}%");
If I am not wrong above code will give me result like:
select * from signups where name like "%Hary Kumar%"
But, I am trying to get
select * from signups where name like "%Hary%" or name like "%Kumar%"
You are looking for a simple orWhere()
DB::table('signups')
->where('name', 'LIKE', "%{$first_term}%")
->orWhere('name', 'LIKE', "%{$second_term}%");
I got my answer. Here is the code:
$search_values = explode(" ",$search_term);
DB::table('signups')
->orWhere(function ($query) use($search_values) {
foreach($search_values as $search_value)
$query->orwhere('name', 'like', '%' . $search_value .'%');})

Laravel 8 How to join 2 tables and check if a value exists

I'm having trouble in querying 2 tables.
Basically I have a 'black_list' table with 2 columns 'user_id' and 'block_id', where 'user_id' is the current user and 'block_id' is the blocked user. The other table is 'users' where there are the information of the registered users.
In my site I have a page where users are searched, my problem is that if id1 blocked id2, when id2 searches id1 it should not be displayed, so in the table 'black_list' I will have these values ​​user_id = 1 and block_list = 2
I've tried so many ways, but I'm not succeeding, can you help me? Excuse my English
public function search(Request $request){
$id= Auth::id();
$query = $request->query('query');
$utentis = DB::table('black_lists')
->join('users', 'users.id', '=', 'users.id')
->where('users.id', '!=', $id)
->where('users.name', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->orWhere('users.cognome', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->where('users.id', '!=', $id)
->orWhere('users.username', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->where('users.id', '!=', $id)
->select('users.id', 'users.name', 'users.fotoProfilo')
->get();
if ($utentis->count() > 0) {
return response()->json($utentis);
}
}
I assume you create a many-to-many relationship between users and black_list is a pivot table.
public function search(Request $request)
{
$id = $request->id;
return User::where('id', $id)
->whereDoesntHave('blocks', function($query) use ($id) {
$query->where('user_id', '!=', $id);
}),
]);
}
UPDATE
// User.php
public function blocks()
{
return $this
->belongsToMany(User::class, 'black_list', 'block_id', 'user_id')
->using(BlackList::class)
->withTimestamps();
}
Notes:
The column names may be in the wrong order because I always mix them. Look at the documentation for more info.
If you created a model for pivot table you need to add ->using(BlackList::class)
If you have BlackList.php, you need to extend it to Pivot rather than Model.
Thanks to both of you for the prompt reply. Unfortunately it returns me null with #gbalduzzi solution. I try to attach a screen of the tables.
The variable $id = Auth::id();
enter image description hereWhen I run the query, it should return me the user profile only if in the black_list table there is no user_id == "user id that blocked me" and block_id == $ id. Thanks again for your help.
Perfect works great, thanks so much for the help
public function search(Request $request)
{
$id= Auth::id();
$query = $request->query('query');
$utentis = User::where('users.id', '!=', $id)
->where(function ($filter) use ($query) {
$filter->where('users.name', 'like', '%' . $query . '%')
->orWhere('users.cognome', 'like', '%' . $query . '%')
->orWhere('users.username', 'like', '%' . $query . '%');
})
->whereDoesntHave('blocks', function ($query) use ($id) {
$query->where('black_lists.block_id','=', $id)
->where('black_lists.user_id','!=', 'users.id');
})
->select('users.id', 'users.name', 'users.fotoProfilo')
->get();
//Log::debug($utentis);
if ($utentis->count() > 0) {
return response()->json($utentis);
}
}

Laravel Eloquent query for join with like

I have this raw query but I'm struggling to convert it to eloquent. Below is my raw sql. I cannot use DB:select because i'm using paginate at the end.
select * from orders
join users on orders.user_id = users.id
where orders.id = $search
or orders.reference_no like '%$search%'
or users.name like '%$search%'
public function customer()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
$orders = Order::where('reference_no', 'LIKE', "%$search%")
->orWhere('reference_no',$search)
->orWhere('id',$search)
->whereHas('customer', function ($query) use ($search) {
$query->where('name', 'like', '%$search%');
})
->paginate(10);
Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', "%$search%")
->orWhere('users.name', 'like', "%$search%") ;
})
->get();
Thanks Pavel and Unai. Based on your answer manage to do this. Need to do a 'use' and in te orWhere I need to concat '%' to the actual $search variable. If I dont have concat '.' literal search is shown in the query
$orders = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'users.id')
->where(function($q) use ($search) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', '%' . $search . '%')
->orWhere('users.name', 'like', '%' . $search .'%') ;
})
->paginate(10);
Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) use ($search){
$q->where('orders.id', $search)
->orWhere('orders.reference_no','like', '%$search%')
->orWhere('users.name','like', '%$search%') ;
})
->get();

Dynamic table name in join query alias in Laravel 5

How to alias a table name in Laravel 5?
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin($res_tbl_name, 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
Actually i need the table name alias like below.
$res_tbl_name AS r
Thanks.
Try as given below:
$data['recent_reviews'] = $reviews_table_name::where('source', 'LIKE', '%YELP%')->orderby('reviews_'.$l_state.'.id', 'desc')
->leftJoin("$res_tbl_name as r", 'reviews_'.$l_state.'.restaurant_id', '=', $res_tbl_name.'.id')
->take(6)
->get();
And then use 'r' wherever you used $res_tbl_name

Search in model and in its relations and paginate results

So I'm building an ECommerce site using Laravel/MySQL, the product related tables I have are as follows: 'products', 'attributes', 'taxonomies' and 'tags'. When a user types a keyword to search for product, I want to search all 4 tables with one query to get the desired products, then I want to use Laravel paginate function to paginate the result, now how do I make it done in one query? Maybe some joins involved?
Here it is, the relationship of my database tables, as for my models, it is defined like this:
class Product extends Eloquent {
...
public function taxonomies() {
return $this->belongsToMany('Taxonomy', 'product_taxonomy', 'product_id', 'taxonomy_id');
}
...
// Same goes for attributes and labels
public function reviews() {
return $this->hasMany('Review', 'product_id');
}
}
Maybe you want something like this:
$products = Product::where('name', 'LIKE ', '%' . $keyword . '%');
$products = $products->orWhereHas('attributes',
function ($query) use ($keyword) {
$query->where('name', 'LIKE ', '%' . $keyword . '%');
}
);
$products = $products->orWhereHas('taxonomies',
function ($query) use ($keyword) {
$query->where('name', 'LIKE ', '%' . $keyword . '%');
}
);
$products = $products->orWhereHas('tags',
function ($query) use ($keyword) {
$query->where('name', 'LIKE ', '%' . $keyword . '%');
}
);
$products = $products->paginate(10);
Now you look in product name and in names of your relations (tags, taxonomies and attributes) and paginate 10 products.
You can try like this
$data = DB::table('products')
->join('attributes', 'products.attributes_id', '=', 'attributes.id')
->join('taxonomies', 'products.taxonomies_id', '=', 'taxonomies.id')
->join('tags', 'host_vulnerabilities.tags_id', '=', 'tags.id')
->where('products.id', '=', $id)
->select('products.id', 'attributes.name') //all required fields
->paginate(15);
I have just added sample example. Please update code as per your requirement
Use UNION for this,
SELECT product_id, product name FROM Products WHERE keyword = 'my_keyword' UNION
SELECT product_id, product name FROM Attributes WHERE keyword = 'my_keyword' UNION
..... Same for other tables
Moreover it will filter out repeated results as UNION works as UNION DISTINCT. But if you provide us with a schema or some db structure, can provide a better solution.
For Laravel, this may work you can create a view and query the view instead of the actual tables, or create your Paginator manually:
$page = Input::get('page', 1);
$paginate = 10;
$w1 = 'my_keyword';
$first = DB::table('products')->where('attribute', 'like', '"%'.$w1.'%"');
$second = DB::table('attributes')->where('attribute', 'like', '"%'.$w1.'%"');
$third = DB::table('taxonomies')->where('attribute', 'like', '"%'.$w1.'%"');
$fourth = DB::table('tags')->where('attribute', 'like', '"%'.$w1.'%"');
$union1 = $first->union($second);
$union2 = $third->union($union1);
$union3 = $fourth->union($union2);
$union3->get();
$slice = array_slice($union3, $paginate * ($page - 1), $paginate);
$result = Paginator::make($slice, count($union3), $paginate);
return View::make('yourView',compact('result'));