To get your latest posts ordered by year, you can use groupBy in your query. See the example below:
Quick tip: you can use a pretty handy Eloquent method called whereColumn() to verify if columns are equal. For example, you can find posts that have been updated or posts which have the same title and slug. Here is the code: Read more in the official documentation here.
Eloquent collections are one of the most powerful tools in the Laravel toolbox. They give you a fluent, convenient wrapper for complex SQL queries. You can chain together different conditions to create complex queries and then call methods on the resulting collection to fetch your data. And here comes the trap. For example, you filter […]
You can always retrieve IDs from Eloquent Collection in Laravel with the built-in method modelKeys: As the official documentation says, the modelKeys method returns the primary keys for all models in the collection
Suppose we have Posts which belong to many different Categories. For this purpose we make three DB tables: posts (id, title), categories (id, name), and an intermediate one (posts_categories, with columns post_id and category_id). The Post Model should be: The Category Controller: You can also return posts collection with dynamic parameters:
Here is a cool trick with the flatten method, which can convert your multi-dimensional Laravel collection into a flattened (single dimension) one. See the code below:
Here is the code which allows you remove all empty, null and false elements from you collection.
You may ask, why the expression !empty($collection) fails to work (could be a controller or a blade view). The answer is that you have to check the empty state of the collection a bit differently in Laravel. Here is the code: I would prefer the last method as the most self-explanatory one, and it doesn’t […]
Hello friends! In Laravel, you can utilize the shortcut for “higher order messages” that come with collections. This is extremely useful for performing common actions. See the code below: