Laravel Model CRUD Operations
October 5, 2024 · AI Conversations
### Creating a New Model Record
1. **Using the `create` method**:
The `create` method is useful when you're passing an array of attributes to create a new record in the database. For this to work, the model needs to have `$fillable` or `$guarded` properties defined.
// Example: Creating a new user
use AppModelsUser;
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password123'),
]);
Make sure your model has the `$fillable` property to allow mass assignment:
// In the User model (User.php)
protected $fillable = ['name', 'email', 'password'];
2. **Using the `save` method**:
You can also create a model instance manually and then call `save()` to insert it into the database.
$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->password = bcrypt('password123');
$user->save();
### Updating an Existing Model Record
1. **Using the `update` method**:
If you want to update an existing record, you can use the `update` method. Similar to `create`, it accepts an array of attributes and updates the corresponding record.
$user = User::find(1); // Find the user with id = 1
$user->update([
'name' => 'Jane Doe',
'email' => 'jane@example.com',
]);
2. **Updating specific fields**:
If you don't want to use mass assignment, you can manually set the fields and call `save()`:
$user = User::find(1);
$user->name = 'Jane Doe';
$user->email = 'jane@example.com';
$user->save();
### Upsert (Create or Update)
Laravel also provides an `upsert` method, which inserts a record if it doesn't exist, or updates it if it does.
User::upsert([
['email' => 'john@example.com', 'name' => 'John Doe', 'password' => bcrypt('password123')],
], ['email'], ['name', 'password']);
In the example above, if a user with the email `john@example.com` exists, it updates the `name` and `password`. Otherwise, it inserts a new record.
These are the common ways to create or update models in Laravel. Let me know if you need more details on any of these!
// Add a custom 'encrypted_id' column
$emailset->encrypted_id = Crypt::encrypt($emailset->id);
return $emailset;
});
add order by id desc
$emailsets = Emailset::orderBy('id', 'desc')->get()->map(function ($emailset) {
// Add a custom 'encrypted_id' column
$emailset->encrypted_id = Crypt::encrypt($emailset->id);
return $emailset;
});
### Explanation:
– `orderBy('id', 'desc')`: This orders the results by the `id` column in descending order.
– `get()`: Fetches the results.
– `map`: Iterates over the results to add the `encrypted_id` column using Laravel's `Crypt::encrypt()`.
This will return the `Emailset` models ordered by `id` in descending order and append the `encrypted_id` to each item in the collection.