We need to create a new model instance if we want to create a new record in the database using Laravel eloquent. Then we are required to set attributes on the model and call the save() method.
Example
public functionsaveProduct(Request $request )
$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();
To create a record in Laravel using Eloquent, you typically follow these steps:
- Define a Model: Create a model class that extends Laravel’s
Illuminate\Database\Eloquent\Model
class. This model represents the database table you want to interact with. - Instantiate a Model Object: Create an instance of the model class.
- Set Attributes: Set the attributes of the model instance with the data you want to insert into the database.
- Call the
save()
Method: Call thesave()
method on the model instance to persist the data to the database.
Here’s a basic example:
use App\Models\User; // Import your model
// Instantiate a new User model
$user = new User();
// Set attributes
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->password = bcrypt('password');
// Save the record to the database
$user->save();
Alternatively, you can use the create()
method to both instantiate and save a record in a single step, passing an array of attributes as an argument:
use App\Models\User;
// Create a new User record
User::create([
'name' => 'Jane Doe',
'email' => 'jane@example.com',
'password' => bcrypt('password'),
]);
Make sure to replace 'App\Models\User'
with the correct namespace for your model class.