简体   繁体   中英

laravel Eloquent with and without an instance

I am new to Laravel .

I want to know the difference between

  1. Instanstiating a Model class.
 $example = new modelClass();
 $example->first();

  1. Without instantiating a Model Class.
  $example = ModelClass::all();

Could anyone please help. Thanks.

The difference is in that when you use new operator you get an instance of model class with all methods available, but empty properties. When you calling first() method of this empty model instance, since Eloquent is active record ORM, Model class makes it's magic, calling sql, filling the properties and returns you same model but with not empty properties already.

Meanwhile, when you use model class as facade for you'r operation, system again resolves entity of model class under the hood, and then calling all method of same initialized object, like int first example, but all method returns not model instance, it returns Collection of Models - the object that used like array, so you can itterate through, but with the bunch of additional functions.

So, if you want to know what is the difference between calling facade or initilized object, it's none, except that system will init object for you, but if you are looking for system to be flexible, you'l be aware from using facades, because to call facade you should call directly to the class, not it's abstraction, while for model you can make a factory instance and call it like abstraction.

But, for new one, you will be fine with facades, but when you will dig dipper into OOP, remember about thing above!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM