Model (Eloquent ORM)
The Eloquent ORM is responsible for the database operations(Model). By using this we can avoid the sql quering. The eloquent model files are placed in app/model directory. Every databse table have a eloquent file.
| class User extends Eloquent { protected $table = 'my_users'; } |
Here this eloquent will deal with the ‘my_users’ table in database. If we do not specify the table here then laravel will take the plural form of the class name as the table name ie, here it is ‘users’.
We can access a model function by calling in the following manner:
Display corresponding model values: $model = User::display()
Insert value to database:
$user = new User;
$user->name = ‘Test Name’;
$user->save();
Insert value in database using ‘create’ method:
$user = User::create(array(‘name’ => ‘Test Name’)); // Create a new user in the database.
$user = User::firstOrCreate(array(‘name’ => ‘Test Name’)); // Retrieve the user by the attributes, or create it if it doesn’t exist.
$user = User::firstOrNew(array(‘name’ => ‘Test Name’)); // Retrieve the user by the attributes, or instantiate a new instance…
Updating a database values:
$user = User::find(1); //load record by id
$user->email = ‘[email protected]’; //load new value
$user->save(); //update new value
Delete record:
$user = User::find(1); //load record by id
$user->delete(); //delete record
Read More