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 […]
Hello, guys! Did you know that you don’t have to wrap your Eloquent query with dd() method, and just simple can add it at the end of the query? See how simple it is. How to use dd() in Laravel What is dd() in Laravel? Dump and Die, or dd(), is a Laravel helper function […]
Hello friends. If you need to retrieve some specific columns from your Model, there is shorter way to do that. With this code, you can pass an array directly to the get method :
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
To someone who didn’t know, there is a pretty and short Eloquent method to use on your model results to get things in random order. See the code below: From the official documentation:
Hello friends! You can check if an item exists or not using Laravel Eloquent with ease. It will return true or false depending on whether it does exist or no. Let’s see the code below:
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:
If you have relationships like hasMany or manyToMany in Laravel and you need to extract data from specific columns of your DB table with your Eloquent query, just do it like that: Don’t forget to always use a column with primary key (in the example above it is id column) and not to put spaces […]
You can use conditions in Eloquent with relationships. For example, we’ve got a Team and its Users. We can define the relationship with the name “admins” which extends the user relation with a condition.