Creating models in Laravel 11 is an essential step in developing your application’s backend. Models represent your application’s data structure and interact with your application’s database. In Laravel, creating models is a straightforward process. Follow these steps to create models in Laravel 11:
- Open Your Terminal:
Open your terminal and navigate to your Laravel project directory. - Create a Model:
Use the artisan command-line tool to create a new model. The command follows this syntax:
php artisan make:model ModelName
Replace ModelName
with the name you want to give to your model.
For example, if you want to create a Product
model, you would run:
php artisan make:model Product
- Migration (Optional):
If your model requires a corresponding database table, you can generate a migration file using the following command:
php artisan make:model ModelName -m
This command generates both the model and its corresponding migration file.
- Define Model Properties:
Open the newly created model file located atapp/Models/ModelName.php
and define your model properties and relationships. For example:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name', 'description', 'price'];
}
- Defining Relationships (Optional):
If your model has relationships with other models, define those relationships within your model class. For example:
public function category()
{
return $this->belongsTo(Category::class);
}
- Use Your Model:
You can now use your model throughout your application to interact with the database. For example, to create a newProduct
instance:
$product = new Product();
$product->name = 'Example Product';
$product->description = 'This is an example product';
$product->price = 10.99;
$product->save();
That’s it! You’ve successfully created a model in Laravel 11. You can now use this model to interact with your application’s database.