Question

I would like to know how to use Fluent Query Builder in a model? I cannot find any example on how to do it properly. All examples are using Eloquent ORM. From laravel's documentation, to create Eloquent model is by extending Eloquent class :

class User extends Eloquent {}

I understand Eloquent can be great but I am new to laravel right now and all Eloquent is doing is it's confusing me. How would I write the model? so that i can use it in my controller?

I come from codeigniter where I would write

class some_model extends CI_Model {}

and i was able to easily autoload this model into my control and take advantage of it. How is it done with fluent?

Was it helpful?

Solution

The Eloquent ORM extends Fluent, so all the fluent methods are available. Eloquent is just like some syntax sugar. I suggest you get used to it, it will keep your code cleaner.

Heres a example:

// Fluent query builder
DB::table('users')->where('id', '=', 1)->first();

// Eloquent
User::find(1);

// Generated SQL
select * from users where id = 1 limit 1;

Both generate the same SQL, and behind the scenes Eloquent is using Fluent. The main difference is that using Eloquent requires you to have models that extend the Eloquent model.

The important thing to understand is that Eloquent methods are available to you ONLY if you extend the Eloquent class. The fluent query builder methods are always available to you as long as you have specified a correct database for your application.

So why use Eloquent at all?

As in the above example Eloquent and Fluent generates the same SQL, but theres still major differences in the returned result when the response is more complex.

The Fluent query builder will return a "simple" response with just the values, theres no methods available. This is depending on your PDO settings.

Eloquent will do much more for your. You get methods available to you that comes straight from the Eloquent model. Theres also one great benefit here, Eloquent will return a collection that implements has many useful interfaces. This means you can do a lot with the returned data.

Heres some good reads:

Whats eloquent and Fluent?

Eloquent collections

OTHER TIPS

Well, you can just use it like the docs are displaying. Example:

<?php
class Foobar extends Eloquent
{
    public static function retrieve($code, $language)
    {
        return static::where('code', $code)->where('language', $language)->first();
    }
}

$foobar = Foobar::retrieve('code', 'EN');

I'm using static::where because this is a static method. (no shit, Sherlock (-: )

You can also just use $this->where() or any other method then where() if the model is initialized. link to query builder docs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top