The update Method in Laravel 5.4: Moving Beyond create
When building a CRUD system in Laravel 5.4, the distinction between creating a new resource and modifying an existing one is often handled by two distinct Eloquent methods: create() and update(). Your initial implementation for storing a new article looks correct because you are using Article::create(). This method instantiates the model with the provided attributes and persists it to the database, automatically assigning a fresh primary key.
However, when you attempt to edit an article, simply pasting that same logic into your edit controller action will fail. If you try to save data without specifying which record you are modifying, Eloquent treats the operation as a new insertion. This results in duplicate records appearing in your database rather than updating the intended row. To fix this, you must explicitly target the existing model instance using its unique identifier before calling save().
Locating and Updating an Existing Record
The core mechanism for updating data relies on finding the specific record first. In Laravel 5.4, you typically retrieve a model by its primary key using the findOrFail method. This approach is preferred over find because it throws a helpful ModelNotFoundException if the record does not exist, preventing silent failures that can lead to confusing application behavior.
Here is how you should structure your controller method to handle an update request:
public function update(Request $request, $id)
{
// Find the specific article by ID; throws exception if not found
$article = Article::findOrFail($id);
// Merge incoming request data into the existing model
$article->update([
'content' => $request->content,
'live' => (boolean) $request->live,
'post_on' => $request->post_on,
]);
return redirect('/articles');
}
Alternatively, if you prefer chaining methods for a more explicit flow, you can use fill() followed by save():
public function update(Request $request, $id)
{
$article = Article::findOrFail($id);
$article->fill([
'content' => $request->content,
'live' => (boolean) $request->live,
'post_on' => $request->post_on,
]);
$article->save();
return redirect('/articles');
}
Both approaches achieve the same result: they locate the existing row in the articles table and overwrite the specified columns. The update() mass assignment method is often preferred for its brevity and readability, while fill() combined with save() offers slightly more control if you need to handle timestamp logic manually or perform additional checks before persisting changes.
Handling Mass Assignment and Timestamps
A critical detail to consider when updating models is mass assignment protection. In Laravel 5.4, you must ensure that the $fillable property on your Article model is defined correctly. If content, live, or post_on are not listed in $fillable, attempting to update them via an array will result in a validation error, regardless of whether you use update(), fill(), or direct assignment.
// In Article.php model
protected $fillable = ['user_id', 'content', 'live', 'post_on'];
Additionally, be mindful of automatic timestamps. If your migration defined created_at and updated_at columns, Laravel will automatically update the updated_at field when you call save() or use the update() method. However, if you are updating a model that was retrieved using findOrFail, you should avoid manually setting these fields unless there is a specific reason to freeze them.
Routing Considerations
Finally, ensure your routes are configured to pass the ID to the controller method. In Laravel 5.4, the standard resource controller syntax or manual route definition should look like this:
Route::put('articles/{id}', ['uses' => 'ArticleController@update']);
// Or using a resource route group
Route::resource('articles', 'ArticleController');
The {id} segment in the URL is crucial. When you access PUT /articles/5, Laravel binds that value to the $id parameter in your controller method, allowing you to locate the correct record. Without passing this ID, you have no way to distinguish which article you intend to modify.
For further reading on building robust CRUD controllers in Laravel 5.4, you might explore resources like https://laravelcompany.com. Understanding these fundamental patterns ensures that your application scales correctly and avoids common pitfalls associated with data duplication.