laravel how to keep same file or form for add edit form details

  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

public function create()
{
    $post = new Post();
    return view('posts.form', compact('post'));
}

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:



public function edit($id)
{
    $post = Post::find($id);
    return view('posts.form', compact('post'));
}

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:


<input type="text" name="title" value="{{ old('title', $post->title) }}">

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:

public function store(Request $request)
{
    $post = new Post();
    $post->title = $request->input('title');
    // set other fields here
    $post->save();
    return redirect()->route('posts.index');
}

And you can use the $post variable to update an existing post like this:

public function update(Request $request, $id)
{
    $post = Post::find($id);
    $post->title = $request->input('title');
    // set other fields here
    $post->save();
    return redirect()->route('posts.index');
}


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

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...