Here's one approach you can take:
Create a form view file that contains the form fields you want to display for both adding and editing data.
In your controller method for adding data, pass an empty instance of the model associated with the form to the view.
For example, if you have a Post model and a create method in your controller, you can pass an empty instance of the Post model to the view like this
In your controller method for editing data, retrieve the data to be edited and pass it to the same form view.
For example, if you have an edit method in your controller, you can retrieve the Post to be edited and pass it to the same form view like this:
In the form view, use the $post variable to populate the form fields.
For example, if you have a title field in your form, you can populate it like this:
The old() function is used to display the previously submitted value for the field (if there is one), and the $post->title variable is used to display the existing value (if you're editing an existing post).
In your form submission handler, use the $post variable to either create a new record or update an existing one.
For example, if you have a store method in your controller, you can use the $post variable to create a new post like this:
And you can use the $post
variable to update an existing post like this:
That's a basic example of how you can use the same form file for adding and editing data in Laravel.
No comments:
Post a Comment