Laravel and PHP - Condition in the SQL request - php

I have a query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);
It work fine. But i need insert condition "where" to search in result
i send $request from form. How insert condition to query?
In PHP it looks like this:
if($request['add_1'])
{
$insert1=" and add_1<>'' ";
}
if($request['add_2'])
{
$insert2=" and add_2<>'' ";
}
...
$sql=" SELECT users.*, user_infos.add1, user_infos.add3 FROM users JOIN user_infos where users.ustatus=1 and user_infos.user_id=users.id ".$insert1." ".$insert2."";
How can this be done on laravel in Controller? I mean - just insert the necessary condition insert1, insert2 ... into the query

you can use where() and has() to build your query
$query = DB::table('users');
if($request->has('age')) {
$query->where('age', '>', $request->age);
}
$query = $query->get();
I hope it's helpful

All is simple ) I use when in query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->when($request->input('f_add3'), function ($query) {
return $query->where('user_infos.add3', '<>', '');
})
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);

Related

How can I select data rows by id in a database query?

I have a database query that needs filtering further. The id needs to match a number in an array I have. For some reason, I can select where using every column except id. Even something as simple as $query->where('users.id', 1); doesn't work. How can I perform a database query by id?
$portfolio_query_array = UserPortfolio::all()->pluck('user_id')
$query = DB::table('users');
$query->select('users.id as user_id','users.user_slug', 'users.social_id', 'users.social_img_update_status', 'users.avatar', 'users.first_name', 'users.last_name', 'users.bio', 'comments.rating', 'user_portfolios.title', 'user_portfolios.description', 'user_portfolios.filepath');
$query->leftjoin('comments', 'comments.comment_to', '=', 'users.id');
$query->leftjoin('user_portfolios', 'user_portfolios.user_id', '=', 'users.id');
$query->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', '=', 'users.id');
$query->where('users.status', 1);
$query->where('users.user_type', 3);
// The below simple query line doesn't work
$query->where('users.id', 1);
// The lines I do want to work also fail.
foreach ($portfolio_query_array as $user_id){
$query = $query + $query->where('users.id', $user_id);
}
Thank you for your help!
First of all, you should take advantage of Eloquent ORM, there is no need to use raw queries unless you have some performance issues or really complex queries.
Assuming you have 3 models User, UserPortfolio, Comment, and all relationships defined, you could do something as simple as this:
$users = User::with('comments', 'portfolio')
->where('status', 1)
->where('user_type', 3)
->whereHas('portfolio')
->get();
In this way, you are getting all users with portfolios which is what I assume you want.
Anyway, if you insist to use a raw query, there whereIn() method is what you need
$portfolio_query_array = UserPortfolio::pluck('user_id')->toArray();
$query = DB::table('users')
->select(
'users.id as user_id',
'users.user_slug',
'users.social_id',
'users.social_img_update_status',
'users.avatar',
'users.first_name',
'users.last_name',
'users.bio',
'comments.rating',
'user_portfolios.title',
'user_portfolios.description',
'user_portfolios.filepath'
)
->leftjoin('comments', 'comments.comment_to', 'users.id')
->leftjoin('user_portfolios', 'user_portfolios.user_id', 'users.id')
->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
->where('users.status', 1)
->where('users.user_type', 3)
->whereIn('users.id', $portfolio_query_array)
->get();
BTW, why are you doing a leftJoin to user_profile_category_selects if no fields are selected from that table?
In addition, if you are looking for all users that have a portfolio, starting from the whole list of portfolios, wouldn't be better to do a join to portfolios and get only those users having portfolios?
$query = DB::table('users')
->select(
'users.id as user_id',
'users.user_slug',
'users.social_id',
'users.social_img_update_status',
'users.avatar',
'users.first_name',
'users.last_name',
'users.bio',
'comments.rating',
'user_portfolios.title',
'user_portfolios.description',
'user_portfolios.filepath'
)
->leftjoin('comments', 'comments.comment_to', 'users.id')
->join('user_portfolios', 'user_portfolios.user_id', 'users.id')
->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
->where('users.status', 1)
->where('users.user_type', 3)
->get();

Laravel 8 Eloqunet: How to set OR condition to where clause in Laravel

I want to show all the Orders from orders table where the status field of that table, equals to canceled OR ignored.
Currently my query goes like this:
$canceled = Order::where('status', 'canceled')
->where('user_id', $uid)
->latest()
->paginate(2);
So how can I add ignored as well to the where clause here?
I think whereIn will do the trick
$canceled = Order::whereIn('status', ['canceled','ignored'])
->where('user_id', $uid)
->latest()
->paginate(2);
Try this query -
$canceled = Order::where(function($q) {
$q->where('status', 'canceled')
->orWhere('status', 'ignored');
})
->where('user_id', $uid)
->latest()
->paginate(2);

Laravel 5.4 subquery in where condition?

I want to write sub query inside where in condition and in subquery were condition, checking with parent query field.
as follows,
$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
$query->select('award_user.user_id')
->from('award_user')
->where('award_user.user_id', 'users.id')
->where('award_user.award_id', $request->award_id);
});
Query is working fine, but
->where('award_user.user_id', 'users.id')
This line, users.id is not taking from parent query. If I enter manually number, then it is working correctly.
What is wrong with my query.. can you please suggest.
use whereRaw rather than where
$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
$query->select('award_user.user_id')
->from('award_user')
->whereRaw('award_user.user_id', 'users.id')
->whereRaw('award_user.award_id = '.$request->award_id);
});

Laravel Eloquent query get users from another model

I have another table called tableb and it has a user relationship defined through the user_id field.
I want to run a query against tableb where a certain date is within a certain range but then I want to grab the user table associated with that row but I only want it to grab the user if it's not been grabbed yet. I'm trying to do this all in 1 DB query. I have most of it done, but I'm having trouble with the unique part of it.
Here's what I have right now:
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->get();
So right now I have 3 entries in tableB from the same user, and ideally I'd like to only get 1 entry for that user.
How would I go about doing this?
Since you're selecting only users data, just add a groupBy clause in your query.
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get();
You should just add groupBy like this :
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get
Try This Code
App/user.php
public function getrelation(){
return $this->hasMany('App\tableB', 'user_id');
}
In Your Controller
Controller.php
use App/user;
public funtion filterByDate(user $user)
{
$date = '2016-02-01';
$result = $user->WhereHas('getrelation', function ($query) use($date) {
$query->whereDate('tableb.start_date', '>', $date)
->first();
});
}

Native SQL to Query Builder in Laravel5

I have two tables on Laravel 5 and have to use Query Builder. I have already got the sql for it but i am not able to convert it to Query Builder syntax. SQL is
SELECT COUNT(A.cid) FROM `A` WHERE A.cid IN (SELECT `id` FROM `B` WHERE `create_user`='$name') AND `access_time` BETWEEN '$start_data' AND '$end_data'
when I use
DB::table('A')
->join('B', function ($join) {
$join->on('A.id', '=', 'B.cid');
})
->get();
some syntax like this , it's error so how can I turn the native SQL like "IN" into Query Builder ,thanks
Try Below queries and look at result:
$result= DB::table('a')
->select(DB::raw('COUNT(a.cid) as total_cid'))
->join('b', 'a.cid', '=', 'b.id')
->where('b.create_user', $name)
->whereBetween('a.access_time', [$start_data, $end_data])
->first();
Or try this
$result= DB::table('a')
->join('b', 'a.cid', '=', 'b.id')
->where('b.create_user', $name)
->whereBetween('a.access_time', [$start_data, $end_data])
->count();
In your question you asked how to use IN, for IN try something like this:-
$result= DB::table('a')->whereIn('cid', [1,2,3,4]);
This is the syntax for joins in Laravel 5.2:
$result= DB::table('a')
->join('b', 'a.id', '=', 'b.cid')
->select('a.cid')
->where('A.cid', 'like', '%string%') //optional like
->get();

Categories