I have this code:
public function inbox()
{
$id = Auth::user()->id;
$bids = Bid::where('user_id',$id)
->where('status','0')
->orWhere('status','4')
->latest()->get();
dd($bids);
return view('rooms.inbox', compact('bids'));
}
and this is my database:
But when I run it I get this result:
my Auth user id is 8 but I get wrong results? Why?
ALso when i try ;
$bids = Auth::user()->bids()->get(); then I get right results///
What is problem?
you are getting this unexpected error because of orWhere,you can do like this way
$bids = Bid::where('user_id',$id)
->where(function ($query) {
$query->where('status','0')
->orWhere('status','4');
})
->latest()->get();
You need to use Advanced Where Clauses
Your Query should like,
$bids = Bid::where('user_id',$id)
->where(function ($query) {
$query->where('status', '0')
->orWhere('status', '4');
})->latest()->get();
Related
Below is my Eloquent query.
$cat = Category::with('subcategory.items.products')
->where('id',$discates)->first();
I want to put a where on products with status = 1.
where('status',1)
You should spend some time reading Laravel docs. They are full of examples and a very good learning resource for the basics.
https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads
$cat = Category::with(['subcategory.items.products' => function($query){
$query->where('status', 1);
}])->where('id',$discates)->first();
Try this
$query = Category::query();
$query->whereHas('products', function ($q) {
$q->where('status', 1);
});
$cat = $query->with('subcategory.items.products')->find($discates);
or
$cat = $query->with('subcategory.items.products')>where('id',$discates)->first();
when i using postman get the result from chunk,but the result will return empty,how can i solve this?
enter image description here
here's my code
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240); //testing
$memberListsArray = array();
Member::select('vipcode')->where('vipcode','!=','')
->chunk(3000,function($members) use($memberListsArray){
foreach($members as $member){
$memberListsArray[] = $member;
}
});
return response()->json($memberListsArray);
}
You need to call get before use chunk; because chunk works with collections. Try with the next code.
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240);
$members = Member::select('vipcode')
->where('vipcode', '!=', '')
->get()
->chunk(3000)
->toArray();
return response()->json($members);
}
By the way, I recommend you to use paginate or some query limit to avoid performance issues
I want the following to happen - search by fields if fields are different from "all". Something like this:
// If $request['field'] != 'all' add query
if(isset($request['types'])) {
$query = Offer::whereHas('types', function ($query) use ($request) {
$typeArray = $request->get('types');
$query->whereIn('type', $typeArray);
});
}
if ($request['country'] != 'all') {
query->where('country_id', $country);
}
At the end I want to order and paginate the results like so:
$offers = $query->orderBy('created_at', 'desc')->paginate(9);
Is there any way to achieve this? If my question isn't clear enough tell me and I will edit it and try to explain better.
You can use eloquent when method to check conditions and append query. in when method you can check your conditions.
Offer::when(isset($request['types']), function($query) {
$query->whereHas('types', function ($query) {
$query->whereIn('type', request()->get('types'));
});
})
->when(request()->country != 'all', function($query) {
$query->where('country_id', request()->country);
})
->orderBy('created_at', 'desc')->paginate(9);
Can you try this:
<?php
$query = Offer::where(function($q) use ($request){
if ( !empty($request['country']) && is_numeric($request['country']) ) {
$query->where('country_id', $request['country']);
}
if( !empty($request['types']) && is_array($request['types']) ) {
$q->whereHas('types', function ($q) use ($request) {
$typeArray = $request->get('types');
$q->whereIn('type', $typeArray);
});
}
});
$offers = $query->orderBy('created_at', 'desc')->paginate(9);
Im creating a filtering search system where people can choose which filters to add to their search. I want to be able to add a filter, depending on its EXISTENCE.
So, normally you do a query like this in Laravel:
$users = User::where('active', '=', 1)->orWhere('subscribed', '=', 1)->get();
But if you dont know whether youre gonna use the orWhere() clause. How do I do that?
You can use User::query() to fetch the query, then dynamically add clauses according to your app logic:
$query = User::query();
if(Request::get('active')){
$query = $query->whereActive();
}
if(Request::get('subscribed')){
$query = $query->orWhere('subscribed', 1);
}
return $query->get();
You can use where scope to append the where clause:
$users = User::where(function($query) use ($subscribed) {
$query->where('status', 1);
if ($subscribed)
$query->orWhere('subscribed', 1);
})->get();
Your question is not 100% clear to me but here is an approach:
$query = User::where('active', '=', 1);
if ($needSubscribers) {
$query = $query->orWhere('subscribed', '=', 1);
}
if ($needOtherCriteria) {
$query = $query->orWhere('filter', '=', 3);
}
$users = $query->get();
You can use when a method
$users = User::when(condition1, function ($query) {
$query->where('subscribed', '=', 1);
})->when(condition2, function ($query) {
$query->where('filter', '=', 3);
})->get();
So I am trying to set up a search page and it has multiple get options But I am curious as to how to set this up correctly, I know this is far from correct as I am doing if statements inside of setting a variable, But I am so lost right now.
Any help would be greatly appreciated.
public function index()
{
$queryUsername = Request::get('u');
$queryPostcode = Request::get('p');
$queryOrderbyPhotos = Request::get('o1');
$queryOrderbyOnline = Request::get('o2');
$queryOrderbyTypes = Request::get('o3');
$users = User::rightJoin('user_profiles','users.id', '=', 'user_profiles.user_id')
if ($queryUsername)
{
->where('users.username', '=', "$queryUsername")
}
if ($queryPostcode) {
->where('user_profiles.postcode', '=', "$queryPostcode")
}
if ($queryOrderbyPhotos) {
->whereNotNull('user_profile.avatar')
}
if ($queryOrderbyOnline) {
->orderBy('users.last_online', 'DESC')
}
if ($queryOrderbyType) {
->orderBy('users.type', 'DESC')
}
->get();
return view('view', compact('users'));
}
This is how I'll approach the problem. I'll create a variable holding the query builder and then call all the additional query methods on it.
With Eloquent and actually with any class that allows Method Chaining you can do this:
$query = User::select(...)->join(..);
$query->where(...);
$query->get(...);
So in your case I'll be trying to achieve what you want in this manner:
public function index()
{
$input = Request::all();
$query = User::rightJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id');
if (isset($input['u']) && $input['u'])
$query->where('users.username', '=', $input['u']);
if (isset($input['p']) && $input['p'])
$query->where('user_profiles.postcode', '=', $input ['p']);
if (isset($input['o1']) && $input['o1'])
$query->whereNotNull('user_profile.avatar');
if (isset($input['o2']) && $input['o2'])
$query->orderBy('users.last_online', 'DESC');
if (isset($input ['o3']) && $input['o3'])
$query->orderBy('users.type', 'DESC');
$users = $query->get();
return view('view', compact('users'));
}
Of course it will be a good idea that you have an additional check for valid input on each input parameter. But this can be achieved in many ways. You can read more about Laravel Controller Validation or Laravel Form Request Validation
By the way I'll suggest to move all this code in your model or in separate class as I prefer keeping controllers slim.
You can try :
$users_query = new User;
$users_query->rightJoin(....);
if ($queryUsername)
{
$users_query->where('users.username', '=', "$queryUsername")
}
// Your other conditions .....
....
$users = $users_query->get();
multiple option search
This is a trait that can be used by any models
This function will remove code repetitions into your project
public function scopeSearch($query, $keyword, $columns = [], $relativeTables = [])
{
if (empty($columns)) {
$columns = array_except(
Schema::getColumnListing($this->table), $this->guarded
);
}
$query->where(function ($query) use ($keyword, $columns) {
foreach ($columns as $key => $column) {
$clause = $key == 0 ? 'where' : 'orWhere';
$query->$clause($column, "LIKE", "%$keyword%");
if (!empty($relativeTables)) {
$this->filterByRelationship($query, $keyword, $relativeTables);
}
}
});
return $query;
}
Filter into relationship also
private function filterByRelationship($query, $keyword, $relativeTables)
{
foreach ($relativeTables as $relationship => $relativeColumns) {
$query->orWhereHas($relationship, function($relationQuery) use ($keyword, $relativeColumns) {
foreach ($relativeColumns as $key => $column) {
$clause = $key == 0 ? 'where' : 'orWhere';
$relationQuery->$clause($column, "LIKE", "%$keyword%");
}
});
}
return $query;
}