How to count results from database? - php

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();

Related

Error Method Illuminate\\Database\\Eloquent\\Collection::save does not exist. in Laravel

I want to change the status at $ result, to get the data at $ result I use query builder, but there is an error like that
$results = ClientVendor::where('client_id','=', $request->client_id)
->where('vendor_id','=',$request->vendor_id)
->get();
$results->status = $request->status;
$results->save();
return response()->json($results);
You cant do this because you call whole collection where is many elements. Call just single record, then you can update it.
When you use get() you call collection
When you use first() or find($id) then you get single record that you can update.
Look at example:
$results = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->first(); // this point is the most important to change
$results->status = $request->status;
$results->save();
return response()->json($results);;
Good luck!
You can try this one too.
$results = ClientVendor::where('client_id','=', $request->client_id)
->where('vendor_id','=',$request->vendor_id)
->update([
'status' => $request->status
]);
Try this:
$results = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->first();
$results->status = $request->status;
$results->save();
return response()->json($results);
It depends on your needs, if you want to :
Get and update one record, you should use first() or firstOrFail() instead of get(). Should be look like this :
$results = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->first();
$results->status = $request->status;
$results->save();
return response()->json($results);
Get and update multiple records, yes you can use get(), but you should do foreach and then update the single record one by one. just like this :
$results = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->get();
foreach($results as $result){
$result->status = $request->status;
$result->save();
}
return response()->json($results);
Many have suggested using first() instead of get(). I think fistOrFail() would be a better option to handle null results.
Otherwise, in cases where the result is null, you'd get Call to a member function save() on null error.
Eg:
ClientVendor does not have a record with either client_id or vendor_id matching $request->client_id or $request->client_id respectively.
$result = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->first();
$result->status = $request->status; //produces error Creating default object from empty value
$result->save(); //produces error "Call to a member function save() on null" because $result will be empty
The above code produces 2 exceptions: 1. "Creating default object from empty value" on lines $result->sataus = .. and 2."Call to a member function save() on null" on line $result->save because $result will be empty.
To fix that, you would call firstOrFail() like so.
$result = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->firstOrFail();
$result->status = $request->status;
$result->save();
This fix, firstOrFail, when there are no results would produce a 404, a handled error, and the subsequent lines would not be executed.
For situations where you query using find($id), it is better to use findOrFail($id)
If you need to update one item use find with it's primary key & then update.Or without primary key then use where & first.then update as like this Just Use
$results = ClientVendor::where('client_id', $request->client_id)
->where('vendor_id',$request->vendor_id)
->first();
$results->update([
'status'=>$request->status
]);
return response()->json($results);

Collection WhereIn method

I'm trying filtered a collection, but the code in the last row does not work. In this row the $property->county_id is an integer, the params.county_id is an array. I would like know the array contains the integer.
I think the code is wrong, because the key (maybe) must be the params.county_id. How I can do this?
Thanks the answers.
$buyerSearches = collect($items);
$result = $buyerSearches
->where('params.type', '=', $property->type)
->where('params.sale_type', '=', $property->sale_type)
->whereIn('params.contract_type', ['all', $property->contract_type])
->where('params.min_price', '<=', $property->price)
->where('params.max_price', '>=', $property->price)
->whereIn($property->county_id, 'params.county_id');
Be sure that the second argument in the whereIn is an array or create that array before the $result query and use it next.
I solved, it works :)
$result = $buyerSearches
->where('params.type', '=', $property->type)
->where('params.sale_type', '=', $property->sale_type)
->whereIn('params.contract_type', ['all', $property->contract_type])
->where('params.min_price', '<=', $property->price)
->where('params.max_price', '>=', $property->price)
->filter(function($buyerSearch) use ($property) {
return in_array($property->county_id, $buyerSearch['params']['county_id']);
});
Try this code instead :
->whereIn('county_id', 'params.county_id');

How to get an array result set from Laravel where condition

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.

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;

eloquent laravel: How to get a row count from a ->get()

I'm having a lot of trouble figuring out how to use this collection to count rows.
$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
I have tried adding->count() but didn't work. I have tried doing count($wordlist). I'm not really sure what to do without needing a second request as a->count() method.
Answer has been updated
count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:
$wordCount = count($wordlist);
If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:
$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();
There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478
However as of now, the query builder always returns an array.
Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:
$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
$wordCount = $wordlist->count();
However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:
// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->count();
// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();
Direct get a count of row
Using Eloquent
//Useing Eloquent
$count = Model::count();
//example
$count1 = Wordlist::count();
Using query builder
//Using query builder
$count = \DB::table('table_name')->count();
//example
$count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
also, you can fetch all data and count in the blade file.
for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
//controller $count = Post::count(); return view('post', compact('count'));
//blade {{$count}}
or
//controller $posts = Post::all(); return view('post', compact('posts'));
//blade{{count($posts)}}

Categories