#
Eloquent ORM
Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.
First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models
directory. Let's define a User.php
model in that directory like so:
class User extends Eloquent {}
Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!
Using your preferred database administration tool, insert a few rows into your users
table, and we'll use Eloquent to retrieve them and pass them to our view.
Now let's modify our /users
route to look like this:
Route::get('users', function()
{
$users = User::all();
return View::make('users')->with('users', $users);
});
Let's walk through this route. First, the all
method on the User
model will retrieve all of the rows in the users
table. Next, we're passing these records to the view via the with
method. The with
method accepts a key and a value, and is used to make a piece of data available to a view.
Awesome. Now we're ready to display the users in our view!