Insert data using Laravel
November 23, 2024 ยท AI Conversations
### 1. **Create a Model**
You can create a model using the Artisan command:
php artisan make:model ModelName
For example, if you want to create a model for a `Post`:
php artisan make:model Post
This creates a `Post` model in the `app/Models` directory.
### 2. **Define Fillable Fields**
Specify which fields can be mass-assigned by adding a `$fillable` property in your model:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
protected $fillable = ['title', 'content']; // Fields that can be mass-assigned
}
### 3. **Insert Data**
You can insert data using the `create` or `save` methods.
#### Option 1: Using the `create` Method
Ensure the fields are listed in the `$fillable` array.
use AppModelsPost;
Post::create([
'title' => 'First Post',
'content' => 'This is the content of the first post.',
]);
#### Option 2: Using the `save` Method
Create an instance of the model, set its properties, and save it.
use AppModelsPost;
$post = new Post();
$post->title = 'First Post';
$post->content = 'This is the content of the first post.';
$post->save();
### 4. **Insert Multiple Records**
You can use `insert` if you need to add multiple records. Note that `insert` bypasses Eloquent and directly works with the database.
use IlluminateSupportFacadesDB;
DB::table('posts')->insert([
['title' => 'Post 1', 'content' => 'Content for post 1'],
['title' => 'Post 2', 'content' => 'Content for post 2'],
]);
### 5. **Database Table**
Ensure the corresponding table exists in your database. You can create a migration to define the structure:
php artisan make:migration create_posts_table
Example migration:
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
Run the migration:
php artisan migrate
### Example in Context:
If you want to insert a new post:
Post::create([
'title' => 'Laravel Insert Example',
'content' => 'This is an example of how to insert a record using a Laravel model.',
]);