laravel lists is giving wrong ids for the column values - laravel

I am fetching a list of rosters
$rostersList = Roster::where('school_id', $this->schoolId)->get()->lists('id', 'name');
$rostersList->prepend('Select Roster');
but the ids always start from 0,1,2 why is that? However according to the where condition the returned list should not be starting from 0 or 1 but from 4. What can be the possible issue here?

When you prepend a single value without assigning a key with it, the collection gets re-keyed.
Laravel prepend lets you pass a second parameter to use as the key.
So you would want something like:
$rostersList->prepend('Select Roster', '');

Related

Make a group by with a where in statement Laravel

I am writing a little script to load an Attendee_logs, based that counts the total of prints for based on the hour.
First I load the id's from the attendees
$allAttendees->pluck('id')->implode(',')
So I get 389832, 321321 from this (this are the id's from the attendees, based on a group).
Now I want to group them by the hour.
But I cannot find out how I add the whereIn statement
$badgesPrintedByDate = DB::table('Attendee_logs')->select(DB::raw('hour(created_at)'), DB::raw('COUNT(id)'))->whereIn('id', [$allAttendees->pluck('id')->implode(',')])->groupBy(DB::raw('hour(created_at)'));
When I do it like this, I get an empty result.
But when I remove the whereIn I get a result.
So my question, How can I count the rows based on the Hour and where I also give the ID's with it :)?
I think this is gonna work:
$badgesPrintedByDate = DB::table('Attendee_logs')->select(DB::raw('hour(created_at)'), DB::raw('COUNT(id)'))->whereIn('id', $allAttendees->pluck('id')->all())->groupBy(DB::raw('hour(created_at)'));
Instead of saying:
$allAttendees->pluck('id')->all()
Which returns an array of ids, you can also say:'
$allAttendees->pluck('id')->values()
Or:
$allAttendees->pluck('id')->toArray();

query to get only one item from target column in Laravel

Is there any query to get only one item from target column? below didn't working?
App\Job::whereNotNull('deleted_at')->pluck('customer_name')->first()
I wish to get just one item name from 'customer_name'
Now Laravel 5.6 using...
When using eloquent, using first will give you a single item, the first record matching your query. You can then access the property on that item:
// This will give you an instance of App\Job (or null)
$job = App\Job::whereNotNull('deleted_at')->first();
// You can then access the customer_name property on the object
$job->customer_name;
If you only want to retrieve that single column when you run your query, you can pass an array of columns to first.
App\Job::whereNotNull('deleted_at')->first(['customer_name']);
Assuming you're using the SoftDeletes trait in your model, your query will automatically have an additional check added to all of your queries to ensure that deleted_at is null. So when you're doing ->whereNotNull('deleted_at') you're adding an additional clause to ensure records are not null as well, so you won't have any records being returned.
If you want to look only at deleted records, you can use onlyTrashed():
App\Job::onlyTrashed()->first();
There is a built-in method for this: value('field')
App\Job::whereNotNull('deleted_at')->value('customer_name');
Docs: https://laravel.com/docs/5.6/queries, look for "Retrieving A Single Row / Column From A Table"
If you meant only one field but still as rows, you can use ->select('field') instead.
And since you want only trashed items, you can use ->onlyTrashed() instead of the not null check.
Soft deleting documentation: https://laravel.com/docs/5.6/eloquent#deleting-models
Try like this:
$job = \App\Job::selectRaw('customer_name')
->whereNotNull('deleted_at')
->first();
And use it like $job->customer_name

laravel the best way to check the contents of a variable

I have a few questions, the first one is:
What is the best way to check if the variable has any records from the database. e.g when I want get single row from collection:
$variable->sth->first()->url
I get reply:
Call to a member function first() on null.
So if I will use something like this:
#if($variable->sth->count() > 0)
code here
#endif
is this correct ? and what's the difference between
#if($variable->sth->count() > 0) and #if(count($variable->sth)>0 #endif because both work, but not always
second question is: Why when I want get one row from collection and when collection is empty an error appears? but when I use foreach to get all rows from db and when collection whether row is empty, nothing is not appears.
the third question is: when should I check that, the returned data isn't empty?
I'am newbie, sorry.
What is the best way to check if the variable has any records from the database.
You can use laravel methods like dd() or use var_dump() to see the content of a variable.
I get reply: Call to a member function first() on null.
That happens because property sth in $variable is null so it doesn't contains a function or member called first()
Why when I want get one row from collection and when collection is empty an error appears? but when I use foreach to get all rows from db and when collection whether row is empty, nothing is not appears.
Foreach evaluates first if there is data on the collection before doing whatever. You are getting an error because you are accessing a row that maybe doesn't exist. You need to evaluate first if the collection is null or not before accessing its data
when should I check that, the returned data isn't empty?
Before attempting to use it

How to stop Doctrine from returning a primary key for every query

I am kind of annoyed at Doctrine for returning primary keys in each and every query even though I don't want it to. Is there anyway to stop this ? coz I don't really want those damn primary keys along with my doctrine query results.
A query for instance that I have is:
$getAllDatesForUserQuery = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_ARRAY) ;
In this situation, it retrieves all the datenames as it should, but also happily returns the primary key column value. I DON"T WANT IT.
Is it me? or is it Doctrine ?
In a case like this where you want a simple array and only have a single field being selected, the answer is the Single Scalar Hydration mode. Use it like this:
$q = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_SINGLE_SCALAR);
You should find that the query will return a simple one-dimensional array containing only the value(s) you wanted.

Compare 2 generic lists and return missing values from list b

I have 2 generic lists.
List 1 is populated with products from a database and List 2 is populated with products from a webservice.
I am wanting to compare lists and any values that are not in List 2 add them to List 3.
I have tried
List<ProductModel> productsToAdd = productsInDatabase.Except(productsFromService).ToList();
However all results are displayed even tho product already is in the database.
What am I doing wrong? do I need to somehow use Except but use an Id field?
Use overloaded version of Except method and pass equality comparer: MSDN

Resources