Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Saturday, February 2, 2013

Laravel - Creating and using Eloquent Models


1) This tutorial demonstrates the following:
A) Creating Eloquent Data Model
B) Routing to a closure
C) Creating record using Eloquent Data Model

2) Before starting this tutorial, it is recommended that you go through:
2a) GET and POST method in routes.php file


A) CREATING ELOQUENT DATA MODEL


1) Eloquent is an Object Relational Mapper (ORM) that allows you to work with your database objects and relationships using an eloquent and expressive syntax.

2) Create {laravel root}\application\models\user.php. Edit as follows.

<?php

class User extends Eloquent
{
public function set_password($string)
{
$this->set_attribute('password', Hash::make($string));
}
}



B) ROUTING TO A CLOSURE


1) Routing is the act of linking a URL to a function in your application.

2) Open {laravel root}\application\routes.php. Locate the following codes (line no. 35-38)



Route::get('/', function()
{
 return View::make('home.index');
});





3) Beneath the above codes, add the following codes and save the file.


Route::get('createTest',function()
{
        //insert new record 
 return "The test user has been saved to the database.";
});




4) Browse {laravel home}/createTest



5) Check the content of the users table in laraveldb


mysql> select * from users;
Empty set (0.00 sec)

mysql>





C) CREATING A RECORD USING ELOQUENT DATA MODEL


1) Open {laravel root}\application\routes.php. Locate the following codes "//insert new record"

2) Replace those codes with the following underlined codes.



Route::get('createTest',function()
{
 $user = new User;
 $user->email = "test1@test.com";
 $user->real_name = "Test Account";
 $user->password = "test";
 $user->save();
 return "The test user has been saved to the database.";
});






4) Browse {laravel home}/createTest



5) Check the content of the users table in laraveldb


mysql> select id,email,real_name from users;
+----+----------------+--------------+
| id | email          | real_name    |
+----+----------------+--------------+
|  1 | test1@test.com | Test Account |
+----+----------------+--------------+
1 row in set (0.00 sec)

mysql>






No comments:

Post a Comment