Eloquent is the ORM (Object-Relational Mapping) included with Laravel. It provides a simple and expressive way to interact with your database by representing database tables as PHP objects. This makes it easier to work with databases in a more natural and object-oriented way.
Create the Model:
In your terminal, run the following command to create a model named Task
:
php artisan make:model Task -m
This will create a Task.php
file in the app
directory and a migration file for creating the corresponding database table.
- Define the Model:
Open the Task.php
file located in app/Models
(or app
if you’re not using Laravel 8+ with separate Models directory), and define the model like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
protected $fillable = ['title', 'description']; // Specify which attributes can be mass assigned
// Additional methods or relationships can be defined here
}
In this example, we’ve defined a Task
model. It extends Model
, which is the base Eloquent model provided by Laravel. The HasFactory
trait is used to provide factory support for the model.
Create the Migration:
In the database/migrations
directory, you’ll find a migration file created for the tasks
table. Define the table’s schema in the up()
method.
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
Run the migration:
php artisan migrate
Using the Model:
Now you can use the Task
model to interact with the tasks
table. For example:
// Create a new task
$task = Task::create([
'title' => 'Sample Task',
'description' => 'This is a sample task description.'
]);
// Retrieve a task
$task = Task::find(1);
// Update a task
$task->title = 'Updated Task Title';
$task->save();
// Delete a task
$task->delete();
Thanks for reading