Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DB::table('table') and model::('table')

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.

like image 318
plasma geek Avatar asked May 08 '16 00:05

plasma geek


People also ask

What is model in laravel?

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.

What is eloquent ORM in laravel?

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.

What is query Builder in laravel?

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.

How write raw SQL query in laravel?

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.


1 Answers

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.

like image 131
Josh Avatar answered Nov 15 '22 03:11

Josh