To create a new model in Laravel, you can follow these steps:
Open your terminal or command prompt and navigate to your project's root directory.
Run the following command to generate a new model:
php artisan make:model ModelName
Replace ModelName
with the name you want to give to your model.
Laravel will create a new file in the app
directory with the given name and the .php
extension. Open this file in your favorite text editor.
Inside the generated model file, you will see a class definition extending the Illuminate\Database\Eloquent\Model
class. This base class provides various methods and functionality to interact with your database.
If your model needs to use a different database table other than the default table name, you can specify it by adding the $table
property to your model with the desired table name. For example:
protected $table = 'custom_table_name';
Define any relationships your model has with other database tables. Laravel provides many relationship methods such as belongsTo
, hasMany
, hasOne
, etc. You can define these relationships within your model class.
After defining the model and its relationships, you can use the model to perform various database operations such as creating, updating, deleting, and querying data.
For example, to create a new record in the database using your model:
$model = new ModelName;
$model->attribute1 = 'Value 1';
$model->attribute2 = 'Value 2';
$model->save();
To retrieve records from the database, you can use methods like all
, find
, where
, etc., on your model.
That's it! You have now created a new model in Laravel and can use it to interact with your database.