How to use Same Form for Create and Update in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hey Dev,

In this comprehensive tutorial, we will learn laravel create and edit same form. I would like to share with you insert and update in one form laravel. We will look at an example of laravel insert and update same form. we will help you to give an example of how to use same form for add and edit in laravel.

In this guide, I will demonstrate how to create and update records in Laravel using a single form. We will start by setting up a "products" table with columns for name and details. Afterward, we'll showcase all the products in a table with both create and edit buttons. The next step involves creating a single Blade file that serves as both the creation and update form. By utilizing this unified form, we'll be able to both store new data and update existing product information. So, let's dive into this step-by-step example.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Preview:

Step 1: Install Laravel App

Let us begin the tutorial by installing a new laravel 10 application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Step 2: Create Migration and Model

Here, we will create a "products" table using laravel migration. so let's use the following command to create a migration file.

php artisan make:migration create_products_table --create=products

After this command you will find one file in the following path "database/migrations" and you have to put below code in your migration file for creating the products table.

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('products', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->text('detail');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('products');

}

};

Now you have to run this migration by the following command:

php artisan migrate

Next, we will create Product.php model file and update as like the below:

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Product extends Model

{

use HasFactory;

protected $fillable = [

'name', 'detail'

];

}

Step 3: Create Controller

In this step, now we should create new controller as ProductController. we will write following code on that file.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;

use Illuminate\Http\RedirectResponse;

use Illuminate\Http\Request;

use Illuminate\Http\Response;

use Illuminate\View\View;

class ProductController extends Controller

{

/**

* Display a listing of the resource.

*

* @return response()

*/

public function index(): View

{

$products = Product::latest()->paginate(5);

return view('products.index',compact('products'))

->with('i', (request()->input('page', 1) - 1) * 5);

}

/**

* Show the form for creating a new resource.

*/

public function create(): View

{

return view('products.createOrUpdate');

}

/**

* Store a newly created resource in storage.

*/

public function store(Request $request): RedirectResponse

{

$request->validate([

'name' => 'required',

'detail' => 'required'

]);

$input = $request->all();

Product::create($input);

return redirect()->route('products.index')

->with('success','Product created successfully.');

}

/**

* Show the form for editing the specified resource.

*/

public function edit($id): View

{

$product = Product::find($id);

return view('products.createOrUpdate',compact('product'));

}

/**

* Update the specified resource in storage.

*/

public function update(Request $request, $id): RedirectResponse

{

$product = Product::find($id);

$request->validate([

'name' => 'required',

'detail' => 'required'

]);

$input = $request->all();

$product->update($input);

return redirect()->route('products.index')

->with('success','Product updated successfully');

}

}

Step 4: Create Routes

Here, we need to add routes for product list, create and update. so open your "routes/web.php" file and add following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ProductController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group that

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('products', [ProductController::class, 'index'])->name('products.index');

Route::post('products', [ProductController::class, 'store'])->name('products.store');

Route::get('products/create', [ProductController::class, 'create'])->name('products.create');

Route::get('products/{id}', [ProductController::class, 'edit'])->name('products.edit');

Route::put('products/{id}', [ProductController::class, 'update'])->name('products.update');

Step 5: Add Blade Files

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "products" then create blade files of crud app. So finally you have to create following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) createOrUpdate.blade.php

So let's just create following file and put bellow code.

resources/views/products/layout.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 10 CRUD Application - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

<div class="container">

@yield('content')

</div>

</body>

</html>

resources/views/products/index.blade.php

@extends('products.layout')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Laravel Create and Edit Same Form Example - ItSolutionStuff.com</h2>

</div>

<div class="pull-right">

<a class="btn btn-success" href="{{ route('products.create') }}"> Create New Product</a>

</div>

</div>

</div>

@if ($message = Session::get('success'))

<div class="alert alert-success">

<p>{{ $message }}</p>

</div>

@endif

<table class="table table-bordered">

<tr>

<th>No</th>

<th>Name</th>

<th>Details</th>

<th width="280px">Action</th>

</tr>

@foreach ($products as $product)

<tr>

<td>{{ ++$i }}</td>

<td>{{ $product->name }}</td>

<td>{{ $product->detail }}</td>

<td>

<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>

</td>

</tr>

@endforeach

</table>

{!! $products->links() !!}

@endsection

resources/views/products/createOrUpdate.blade.php

@extends('products.layout')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>@if (isset($product)) Edit @else Add @endif Product</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>

</div>

</div>

</div>

@if ($errors->any())

<div class="alert alert-danger">

<strong>Whoops!</strong> There were some problems with your input.<br><br>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

@if (isset($product))

<form action="{{ route('products.update', $product->id) }}" method="POST" enctype="multipart/form-data">

@method('PUT')

@else

<form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">

@endif

@csrf

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Name:</strong>

<input type="text" name="name" value="{{ old('name', $product->name ?? '') }}" class="form-control" placeholder="Name">

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Detail:</strong>

<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ old('detail', $product->detail ?? '') }}</textarea>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

</form>

@endsection

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/products

You will see layout as like bellow:

Add Page:

Edit Page:

I hope it can help you...

Tags :
Shares