on laravel we can access by using DB::table('table')->get();
or using model::('table')->all();
My question is what's the difference between them ?
thanks.
Laravel Create Model is an MVC based PHP system. In the MVC architecture, 'M' stands for 'Model'. A model is used as a way for questioning data to and from the table within the database. Laravel gives a basic way to do that using Eloquent ORM where each table incorporates a Model to interact with it.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.
DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.
You can do this because Model
and the DB
facade both implement functions that yield a Builder
instance.
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html
https://laravel.com/api/5.2/Illuminate/Database/Query/Builder.html
The difference is, instances of Model
have properties which set up a Builder
with predesignated information, like table, and also provide it with events, relationship information, specific static bindings, and a bunch of other handy helpers that constrain to objects and make object-oriented programming easier.
So yes, you can use a model and then take the query Builder
object and change its table (just like you can change anything else about a Builder
), but it's fighting a system specifically designed to make query building easier.
At heart, what Laravel does is take the Symfony2 framework and streamline it so everything is simpler. Models are one such instance of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With