Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel using WHERE in eloquent ORM

I came across this

$user = User::whereConfirmationCode($confirmation_code)->first();

In Laravels eloquent ORM, can you append the tables row name in the where statment like above?

Before I saw this I would just written

eg: $user = User::where('confirmation_code', '=', $confirmation_code)->first();

Thanks

like image 837
user2722667 Avatar asked Nov 18 '14 13:11

user2722667


People also ask

Is Laravel eloquent ORM?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database.

What is the use of eloquent ORM in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.

Is query Builder faster than eloquent?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What is whereIn in Laravel?

whereIn() Laravel Query with Example: whereIn() is used to check whether column contains value from the array or list. Basically, it is used to match column against list of values.


2 Answers

'Yes, you can build dynamic where. It's parse in simple where statement. Also you can build magic query like this:

$user = User::whereConfirmationCodeAndIdOrRole(12345, 5, 'admin')->first();

It will be transform to:

$user = User::where('confirmation_code', '=', 123456, 'and')->where('id', '=', 5, 'or')->where('role', '=', 'admin')->first();
like image 131
xAoc Avatar answered Oct 18 '22 21:10

xAoc


I may be wrong. I was un-aware of magic query builder setup.

That is a custom query scope.

IE: A post model with a query scope to get all posts with 'status' = published.

class Post extends Eloquent {
    /**
     * Get all posts with 'status' published
     *
     * @param Illuminate\Database\Query\Builder $query
     * @return Builder $query
     */
     public function scopePublished(Builder $query)
     {
         return $query->where('status', 'published');
     }
}

Then using it:

 Post::published()->first();

Note parameters can be passed to the custom scope by passing them as parameters to the query scope after the query builder.

 public function scopeStatus(Builder $query, $status)
 {
     return $query->where('status', $status);
 }
like image 2
nickcoffey Avatar answered Oct 18 '22 21:10

nickcoffey