How to get unique year values from created_at? - laravel

I have a collection called $products, each instance of which has a field created_at. The latter obviously has a format ('Y-m-d H:i:s') in the DB. Now, it's easy to get instances with unique created_at. However, I'd like to retrieve unique year values of created_at in one single expression (that I can write in my view). What I am looking for is:
$products->unique( year value ('Y' ONLY) of 'created_at' )
This expression should evaluate to something like this: ['2012', '2013', '2016'].

Building on the comment that gives you a collection with unique timestamps, you can map out the year and sort with the following code.
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();

In addition to Tim result
$products = DB::table('products')->get();
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();
You can use toArray or values() to get the result of collection

Related

Eloquent query to get Highest and 2nd highest value in database

I have a problem with Laravel Eloquent to get the subject name with the highest value and second highest value from the 'student_number' where the subject group = 'E1'.
This is what I have tried but it contains an error "max(): When only one parameter is given, it must be an array" and I don't know how to get the 2nd highest value of 'student_number'.
public function electiveGroup(){
$E1 = FinalyearSubject::get()
->where('subject_group','=','E1')
->orWhere('student_number','=',max('student_number'));
return view ('admin.elective')->with(compact('E1'));
}
FinalyearSubject::where('subject_group', 'E1')
->orderBy('student_number', 'DESC')
->limit(2)
->get()
Explanation:
Add filters
Order them by student_number descending
Take the top 2
get() the result
In your example, the moment you are doing FinalyearSubject::get(), the query is already done. get() returns a Collection object (more like an enriched array). Everything you chain afterwards is calculated using Laravel's Collection utilities. ->get() usually should be the last thing in your call so that you can do as much work in SQL as possible.
So, Question is you want maximum of all and 2nd maximum of subject
group = 'E1'.
Max of all
FinalyearSubject::where('subject_group','E1')
->max('student_number');
2nd max of 'E1'
FinalyearSubject::where('subject_group','E1')
->OrderBy('student_number','desc')
->offset(1)
->limit(1)
->get();

How to check if collection's column matches an array

Model CustomerDocuments holds customer docs, doc_id is a column in this model that signifies which document is there.
I have an array of needed document IDs, say $neededDocs = [1,2,3].
How do I check if my collection CustomerDocuments contains $neededDocs in each item of this collection.
if all $neededDocsare present in each CustomerDocuments.doc_id then return true, else, false.
I would like to preform this with collection->contains as follows:
CustomersDocuments::where('customer_id', $customer->id)
->contains('doc_id',$required_onboarding_docs)
->get();
Yet this syntax is wrong
I think you could probably achieve this with something like the following:
$documents = CustomersDocuments::where('customer_id', $customer->id)
->get()
->pluck('doc_id')
->toArray();
The above will output an array with all the doc_id.
return $documents == $neededDocs;
You could then just compare it with your $neededDocs array.
Edit: If you, however, want to check that each row in your collection contains a doc_id that is present in $neededDocs, you could do it like this:
$collection = CustomersDocuments::where('customer_id', $customer->id)->get();
return $collection->contains(function($value, $key) use ($neededDocs) {
return in_array($value->doc_id, $neededDocs);
});
I am not entirely sure which one you want, but these should do the trick.

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

How to use whereBetween for dates in Laravel

I am trying to get the number of new users for each week using the created_at column. I am trying to use the whereBetweensyntax but it always return 0 even when it is suppose to return otherwise.
{{ DB::table('users')
->whereBetween('created_at', array(date("Y/m/d h:i:s", strtotime('sunday last week')), date("Y/m/d h:i:s", strtotime('saturday this week'))))->count(); }}
Any suggestions?
The query itself should work as written, though you might want to verify that created_at is a column of either timestamp, date, or datetime type. When you created the users table, did you use a migration to create your users table, and if so, did you specify $table->timestamps();? Or did you manually define the created_at column, and perhaps set it to a string?
A couple other (unrelated) suggestions:
• It appears that you're running this query in a view, echoing the count using blade. This logic would be better handled elsewhere, perhaps in your User model, and the result passed to the view by the controller.
• You can simplify your query using PHPs DateTime object, replacing your date(...strtotime...) with date_create(...):
$usersThisWeek = User::whereBetween(
'created_at', array(
date_create('sunday last week'),
date_create('saturday this week')
))->count();

Laravel - When to use ->get()

I'm confused as to when ->get() in Laravel...
E.G. DB::table('users')->find(1) doesn't need ->get() to retrieve the results, neither does User::find(1)
The laravel docs say "...execute the query using the get or first method..."
I've read the Fluent Query Builder and Eloquent docs but don't understand when the usage of get() is required...
Thanks for the help
Since the find() function will always use the primary key for the table, the need for get() is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.
But when you're using the Fluent Query Builder you can nest conditions as such:
$userQuery = DB::table('users');
$userQuery->where('email', '=', 'foo#bar.com');
$userQuery->or_where('email', '=', 'bar#foo.com');
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
// Done with building the query
$users = $userQuery->get();
For find(n), you retrieve a row based on the primary key which is 'n'.
For first(), you retrieve the first row among all rows that fit the where clauses.
For get(), you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).
find returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3 is equivalent to DB::table('users')->find(3);
get returns an array of objects. e.g. SELECT * FROM users WHERE created_at > '2014-10-12' is equivalent to DB::table('users')->where('created_at', '>', '2014-10-12')->get() will return an array of objects containing users where the created at field is newer than 4014-10-12.
The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:
When I want all data from a table I use the all() method
Model::all();
When I want to find by the primary key:
Model::find(1)->first();
Or
Model::findOrFail(1)->first();
This will work if there is a row with a primary key of one. It should only retrieve one row so I use first() instead of get(). Remember if you deleted the row that used key 1, or don't have data in your table, your find(1) will fail.
When I am looking for specific data as in a where clause:
Model::where('field', '=', 'value')->get();
When I want only the first value of the data in the where clause.
Model::where('field', '=', 'value')->first();
Basically what you need to understand is that get() return a collection(note that one object can be in the collection but it still a collection) why first() returns the first object from the result of the query(that is it returns an object)
#Take_away
Get() return a collection first() return an object
You can use get() method with latest() method to get the latest record that were recently added to your table
For example
$user=Student::latest()->get();
return all the data in descending order

Resources