How to get an array result set from Laravel where condition - php

I am trying to get a result set from a laravel eloquent query whereby I match a column against a list of values in an array.
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
->where('entity_type_id', '=', $operation_entity_id)
->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids);
return view('page.index')->withOperations($authenticated_operations);

You can try it as:
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
return view('page.index')->withOperations($authenticated_operations);
Add get() at the end of the query.

1) pluck returns a single value from a single row. You want lists to get a single column from multiple rows. toArray may not be needed, as it returns an array of values
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
->where('entity_type_id', '=', $operation_entity_id)
->lists('entity_access_id');
2) You're forgetting to actually retrieve the rows in your second line:
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)
->get();

You have to call get() function on the result set to obtain results. The modified code will be like
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->get()->pluck('entity_access_id');
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
return view('page.index')->withOperations($authenticated_operations);
or you can use a cursor to process it.

Related

How to count results from database?

I want to count the result fetched from database
$t = Activation::where('user_id', '=', $user->id)->first();
$w=(count($t));
dd($w);
I expect to see the number of results fetched
Your code is wrong... Please read the Laravel official documentation
With first() function you're getting just the first result of the set returned from your query. To make your code work you should use the get() function. and the dd($w) will return the correct result.
Anyway there are specific aggregate functions to achieve your goal, just changing your code from
Activation::where('user_id', '=', $user->id)->first();
// output: {"user_id": 1, "email": 'test#example.com', [...]}
to
Activation::where('user_id', '=', $user->id)->count();
// output: 123
Try to use a laravel count method.
$t = Activation::where('user_id', '=', $user->id)->count();
dd($t);
$ty = Activation::where('user_id', '=', $user->id)->count();
dd($ty);
You are using first() that will return only one object if found. use get() and then use count.
$t = Activation::where('user_id',$user->id)->get();
$w = count($t);
If you just want to count then use count()
Activation::where('user_id',$user->id)->count();

Call to a member function first() on double

I got an error in
Call to a member function first() on double
this is query builder in laravel
$player = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->sum('stats.winpot');
->first();
of course. it's obvious. the sum() function return sum of the selected column. a single value (not a collection of values)
the first() is for Collections, to get the first element from a collection.
Since the sum function returns the sum of the column values (A single value, not a Collection), you cant call first() function on it.
And Most importantly You Don't Have To.
NOTE
If you want to get both 'player' and the 'sum' you can execute two queries and bind those two results together.
Possible solution.
$player = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->first();
$player->sum = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->sum('stats.winpot');
now there is an attribute in retrieved 'player' as 'sum'. you can access it as $player->sum

How to fetch data in laravel 5.4 with out using array_push

its there's a way to optimize this code. I already google it but I don't know what the exact keyword to search, so I always failed to find the answer.
At this code I get the Approver List of ID 512 (requestor)
$approver_list = DB::table('users')
->leftjoin('approver_group_list', 'approver_group_list.user_id', '=', 'users.id')
->leftjoin('approval_roles', 'approval_roles.as_id', '=', 'approver_group_list.as_id')
->leftjoin('approver_requestor_list', 'approver_requestor_list.at_id', '=', 'approval_roles.at_id')
->where('approver_requestor_list.user_id', 512)
->get();
Then I use array_push to extract the data of approver_list, then I use the value of $result to get value in LeaveMain table.
$result = array();
foreach($approver_list as $al)
{
array_push($result , $al->user_id);
}
$leave_list = LeaveMain::whereIn('requestor_id', $result)->get();
My problem is, it is always need to use array_push to to extract data, or laravel have a way to optimize this code.
$approver_list = DB::table('users')
->leftjoin('approver_group_list', 'approver_group_list.user_id', '=', 'users.id')
->leftjoin('approval_roles', 'approval_roles.as_id', '=', 'approver_group_list.as_id')
->leftjoin('approver_requestor_list', 'approver_requestor_list.at_id', '=', 'approval_roles.at_id')
->where('approver_requestor_list.user_id', 512)
->pluck('id');
$leave_list = LeaveMain::whereIn('requestor_id', $approver_list)->get();
Basically you can pluck the id from the table itself, rather than fetching all the data and then taking the id later, and whereIn accepts collection as the second argument. so no need to cast to an array
The whereIn method filters the collection by a given key / value
contained within the given array: Link
You don't need to loop the approver_list values, you can use pluck method to retrieves all of the values for user_id.
$result = $approver_list->pluck('user_id')->toArray();
$leave_list = LeaveMain::whereIn('requestor_id', $result)->get();

Laravel Model Using Or in where Condition?

I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..
$templates= $this->where('notify_admin',1)
->orwhere('notify_customer',1)
->where('user_webhooks.user_id',$user_id)
->where('user_webhooks.app_id',$app_id)
->select( 'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
'user_webhooks.sms_template as sms'
)
->join ('webhooks',function($join){
$join>on('webhooks.id','=','user_webhooks.webhook_id');
})
->get()
->toArray();
when i get query using DB::getQueryLog(), I found the query seems Like
select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
`telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
`telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
`telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
`telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
`telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`
inner join
`telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`
where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
= ? and `telhok_user_webhooks`.`app_id` = ?
The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Advanced usage:
Usere::where('id', 46)
->where('id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
More: https://laravel.com/docs/5.5/queries
Change
->where('notify_admin',1)
->orwhere('notify_customer',1)
to
->where(function($q){
$q->where('notify_admin',1)
->orWhere('notify_customer',1);
})
Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns

Nested SQL Query in Laravel Controller

I have two queries running in my controller. I need a value from the first query to be passed into the second. I want the result of both these queries sent to my view.
public function jobs()
{
$query = DB::table("dbQuotes")
->leftJoin("dbACT", "dbQuotes.act_id", "=", "dbACT.ID")
->leftJoin("dbOpps", "dbQuotes.act_id", "=", "dbOpps.contactID")
->leftjoin('dbBids', 'dbQuotes.act_id','=',
DB::raw('dbBids.quote_id AND dbBids.user_id = '. Auth::user()->id))
->where("dbQuotes.active", "=", "1")
->select("dbQuotes.*", "dbACT.*", "dbBids.*",
(DB::raw('date_format(dbQuotes.posted_date, "%d/%m/%Y %H:%i") as posted_date')),
(DB::raw('date_format(dbOpps.expected_date, "%d/%m/%Y") as expected_date')))
->groupBy("dbQuotes.id")
->orderBy("posted_date", "desc")
->get();
$passinvaluehere = $query->dbQuotes.act_id
$bids = DB::table("dbBids")
->where("quote_id", "=", $passinvaluehere)
->get();
return view('jobs', ['query' => $query,'bids' => $bids]);
}
My query works and the view is established in the correct way if I replace the passed value with a number, i.e "8763". My question is how, within this function, can I pass the value/s of dbQuotes.act_id into this second query?
***UPDATED Code from answer: [error Call to a member function lists() on a non-object]
public function jobs()
{
$query = DB::table("dbQuotes")
->leftJoin("dbACT", "dbQuotes.act_id", "=", "dbACT.ID")
->leftJoin("dbOpps", "dbQuotes.act_id", "=", "dbOpps.contactID")
->leftJoin('dbBids', 'dbQuotes.act_id','=',
DB::raw('dbBids.quote_id AND dbBids.user_id = '. Auth::user()->id))
->where("dbQuotes.active", "=", "1")
->select("dbQuotes.*", "dbACT.*", "dbBids.*",
(DB::raw('date_format(dbQuotes.posted_date, "%d/%m/%Y %H:%i") as posted_date')),
(DB::raw('date_format(dbOpps.expected_date, "%d/%m/%Y") as expected_date')))
->groupBy("dbQuotes.id")
->orderBy("posted_date", "desc")
->get();
$act_id = $query->lists('act_id');
$bids = DB::table("dbBids")
->whereIn("quote_id", $act_id)
->get();
return view('jobs', ['query' => $query,'bids' => $bids]);
}
If you have multiple records (as per the ->get() method) you have two ways: either you loop over the Collection and make a query each iteration (bad) or you create an array of ids and use a whereIn in the second query (better):
$passinvaluehere = $query->lists('act_id');
// https://laravel.com/docs/5.2/queries#retrieving-results
// this creates and array of `act_id` s
$bids = DB::table("dbBids")
->whereIn("quote_id", $passinvaluehere)
->get();
// you now have a Collection of multiple $bids
If you expect only a single records from your first query, you need to change the fetcher method, using first() instead, or else take only the first element of your actual collection, something like first($query) or $query[0]
$query = DB::table("dbQuotes")
....
->first();
$passedvaluehere = $query->act_id;

Categories