Using Fluent in a Model - php

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?

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

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

Related

What's the best practice of creating models and getting the information using the Laravel Eloquent?

I'd like to know what is the best way of creating models using the Laravel framework? As far as I know, the model is used for the connection to the DB table and then, you can do whatever you want with its data.
Creating a new model per DB table (as stated here) isn't good and models should be created per business object. Not sure what it means. I'd like to access the same table and get some information from it using the Eloquent, so similar to this:
<?php
// Get the model class
use App\Post;
// Grab some data from the posts table
$posts = Post::all();
But it requires having a model. Using the select method, e.g.:
$posts = DB::table('posts')->select('title, body')->get();
Doesn't require having a model so I don't quite understand what's the point of models? I couldn't find enough information inside the Laravel docs: https://laravel.com/docs/5.6/eloquent.
As a full explanation of your question:
Using method:
<?php
// Get the model class
use App\Post;
// Grab some data from the posts table
$posts = Post::all();
will be the same as running a query like:
<?php
$posts = DB::table('posts')->select('*')->get();
but the biggest difference is that the first returns an Eloquent object, while the later returns a normal object. The first model requires a model, which extends eloquent, the later method is using the DB class, which does not extend eloquent. So when you want to use Eloquent you would have to use models.
Creating a new model per DB table (as stated here) isn't good and models should be created per business object. Not sure what it means.
Entities are things like Users, Posts, Comments, messages, but not relation tables such as user_has_posts or user_has_messages. Not entirely sure how else to explain it, but i'm sure you will get the idea.
Also keep in mind, models are supposed to only contain database logics, I've seen it plenty of times where people use models to filter arrays but this should not belong to models.

Laravel 5.x - How could Eloquent model be QueryBuilder?

I am trying to understand how could an Eloquent model also be a query builder. I could not see any polymorphic relationship between Illuminate\Database\Eloquent\Model class and Illuminate\Database\Query\Builder class in the source code. There is no inheritance or interface implementation between these two classes.
So, could anyone please explain how Laravel made it possible for an eloquent model to be a query builder? Thanks in advance.
Edit: I am asking this question because I don't understand how I could call the methods in Builder class through my models, e.g. ModelObject::orderBy('created_at', 'asc')->get(), where orderBy() is a method in Builder class.
There is a query() function on the Eloquent base model which creates a new query builder instance when being called (with the table of the model being already set for the builder). You can find the function here.
Additionally to that, the magic __call() and __callStatic() functions create a new query builder and delegate the method call to this builder whenever a function is called that is not part of the Eloquent model and which they don't have an implicit call for (like increment(), decrement()). You can find the code for this here.
So to sum it up: it's magic. The magic functions.

Laravel 4 model without eloquent

I'm just starting to learn about Laravel and trying to migrate from CI. I have a few simple questions.
Do I have to use eloquent when using a model?
In CI using model you just extends Model. Is there the same to use in Laravel? So far all the docs I found only state that I have to use eloquent if I want to use model. Eloquent is a bit confusing at the moment for me. So I just want to use simple query builder in my model.
I guess number 1 and 2 questions are somehow related.
You can use fluent:
DB::table("...");
Eloquent, which is based on PDO is ORM and more abstracted from raw queries.
Eloquent is a great tool, so I recommend familiarizing yourself with it if you get the chance.
You can build queries on your own using Laravel's query builder.
Read up on it here, I hope this answers your question and sorry if I misunderstood!
http://laravel.com/docs/queries
Good luck!
I think you can`t create a model without extends eloquent like laravel 4 Doc
class User extends Eloquent {}
because a model in laravel based into eloquent ORM unlike CodeIgniter
If you need to deal with database tables with creating models ,you can use DB class
like laravel 4 Doc
DB::select('') and DB::table('')

How to create Laravel Model without Eloquent?

As I am not sure, is it possible to create models with DB Class instead of Eloquent? I want to stay away from ORM.
Thanks
Yes of course its possible. You dont need to extend any class to make a model class that encapsulates business logic and consists of methods calling the DB class.
Just create your model inside app/models/MyModel.php like this
class MyModel{
public static function getMyData(){
return DB::table('users')->select('column')->get();
}
}
then you should be fine to call your new class statically:
$data = MyModel::getMyData();
If you wanted to extend the DB class you could, though more likely you would be looking to extend the Database/Builder class to extend functionality but this is a complex topic and I suspect you would have asked a very different question if this was what you were after.
As I final note, I wouldn't steer clear of Eloquent, it's the greatest thing about Laravel amongst a lot of other great things
Just remove the "extends Eloquent" and build the queries using the DB class.

Can I use an Eloquent model as a fully featured class?

I'm just learning Laravel 4 and I was unsure about how Eloquent models work. It is clear to me that they are a good way to interact with the database but can I define constructors and functions on a class that extends Eloquent to use it for more than database interaction?
Yes! A class that extends Eloquent, doesn't make it a class solely used for Eloquent purposes. You've got the realize the concept of class extension. Class extension is there to simply add features to ANY class from another, existing class. In this case Eloquent.
You can take any model you already have, and tomorrow decide that you want to use it with Eloquent and simply extend it. Your original class is still your original class and works the same. Any methods or properties in the original class will ovewrite its parent (Eloquent) if the parent has something with the same name.
In fact, creating other methods in a class that extends Eloquent is the real way to create robust models that do all sorts of cool stuff. I create methods in my User model for example, to calculate how many day's until their birthday. Instead of pulling the birthday column into a controller then using PHP to do the calculation, I just have a method like User::daysUntilBirthday();
If you use a constructer and extend Eloquent, make sure you still fire off Eloquent's constructor as well though.
class MyModel extends Eloquent {
public function __construct($attributes = array(), $exists = false)
{
parent::__construct($attributes, $exists); // This will fire off Eloquent's constructor.
// Your construct code.
}
}

Categories