Laravel 8 Multi Step Form Submit with Validation and Example


Share:
Published By: Admin, Published On: May 19, 2021, Category: Laravel 8 Laravel

Hello Friends,

Now let's see example of how to create multi step form in laravel example. This is a short guide on laravel multi step form with validation. Here you will learn how to create multi step form laravel. We will use how to create multi step form with validation in laravel. Let's get started with how to create multi step form in laravel.

Here i will give you few step create multi step form with validation in laravel 8.

Step 1: Install Laravel 6 Application

In first step to create multi page form validation n laravel , if you haven't laravel 6 application setup then we have to get fresh laravel 6 application. So run bellow command and get clean fresh laravel 6 application.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Create Register Model

Let’s set up a register model along with the migration file.

php artisan make:model Register -m

Let’s now go ahead and modify the migration file to add the required columns.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRegistersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
   public function up()
    {
        Schema::create('registers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->longText('description');
            $table->string('productimg');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('registers');
    }
}

After create "registers" table you should create Register model for register, so first create file in this path app/Register.php and put bellow content in register.php file:

app/Register.php

<?
namespace App;

use Illuminate\Database\Eloquent\Model;

class Register extends Model
{
    protected $guarded = [];

}
Step 3: Create Route

In this is step we need to create two route one for render treeview and second for add new category file. so open your routes/web.php file and add following route.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/register-step-1', [RegisterController::class, 'createStep1'])->name('signup');
Route::post('/register-post-step-1', [RegisterController::class,'PostcreateStep1'])->name('register.post.step.1');
Route::get('/register-create-step-2', [RegisterController::class,'createStep2'])->name('register.create.step.2');
Route::post('/register-post-step-2', [RegisterController::class,'PostcreateStep2'])->name('register.post.step.2');
Route::get('/register-create-step-3', [RegisterController::class,'createStep3'])->name('register.create.step.3');
Route::post('/register-post-step-3', [RegisterController::class,'PostcreateStep3'])->name('register.post.step.3');
Route::post('/remove-image', [RegisterController::class,'removeImage'])->name('remove.image');
Route::post('/store', [RegisterController::class,'store'])->name('store');
Route::get('/data', [RegisterController::class,'index'])->name('index');
Step 4: Create Controller

In this point, now we should create new controller call CategoryController in this path app/Http/Controllers/RegisterController.php. In this controller we will manage route method, i added two method in this controller as listed bellow:

app/Http/Controllers/RegisterController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Register;

class RegisterController extends Controller
{
   /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $request->session()->forget('register');

        $products = \App\Models\Register::all();

        return view('register.index',compact('products'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function createStep1(Request $request)
    {
        $register = $request->session()->get('register');

        return view('register.step1',compact('register'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function PostcreateStep1(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|unique:registers',
        ]);
        if(empty($request->session()->get('register'))){
            $register = new \App\Models\Register();
            $register->fill($validatedData);
            $request->session()->put('register', $register);
        }else{
            $register = $request->session()->get('register');
            $register->fill($validatedData);
            $request->session()->put('register', $register);
        }
        return redirect('/register-create-step-2');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function createStep2(Request $request)
    {
        $register = $request->session()->get('register');

        return view('register.step2',compact('register'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function PostcreateStep2(Request $request)
    {
        $validatedData = $request->validate([
            'description' => 'required|unique:registers',
        ]);
        if(empty($request->session()->get('register'))){
            $register = new \App\Models\Register();
            $register->fill($validatedData);
            $request->session()->put('register', $register);
        }else{
            $register = $request->session()->get('register');
            $register->fill($validatedData);
            $request->session()->put('register', $register);
        }
        return redirect()->route('register.create.step.3');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function createStep3(Request $request)
    {  
        $register = $request->session()->get('register');
        return view('register.step3',compact('register'));
    }

   /**
     * Write code on Method
     *
     * @return response()
     */
    public function PostcreateStep3(Request $request)
    {
        $register = $request->session()->get('register');

        if(!isset($register->productImg)) {
            $request->validate([
                'productimg' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]);
            $fileName = "productImage-" . time() . '.' . request()->productimg->getClientOriginalExtension();
            $request->productimg->storeAs('productimg', $fileName);
            $register = $request->session()->get('register');
            $register->productImg = $fileName;
            $request->session()->put('register', $register);
        }
        return view('register.step4',compact('register'));
    }

   /**
     * Write code on Method
     *
     * @return response()
     */
    public function removeImage(Request $request)
    {
        $register = $request->session()->get('register');

        $register->productImg = null;

        return view('register.step3',compact('register'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $register = $request->session()->get('register');

        $register->save();

        return redirect('/data');
    }
}

?>
Step 5: Create View

In this step, we have to create total two blade file as listed bellow:

resources/views/register/step1.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-10">
                        <h5>Product Detail</h5>
                    </div>
                    <div class="col-md-2">
                        <a href="{{ route('index') }}" class="btn btn-md btn-success float-right"><i class="fas fa-arrow-left"></i></a>
                    </div>
                </div> 
            </div>
            <div class="card-body">
                <h3>Step 1</h3>
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
                <form action="{{ route('register.post.step.1') }}" method="POST">
                    @csrf
                    <div class="form-group">
                        <label for="name">Name: </label>
                        <input type="text" name="name" class="form-control mb-2" placeholder="Enter name" value="{{ session()->get('register.name') }}">
                        <button type="submit" class="btn btn-primary">Continue</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection 

resources/views/register/step2.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-10">
                        <h5>Product Detail</h5>
                    </div>
                    <div class="col-md-2">
                        <a href="{{ route('signup') }}" class="btn btn-md btn-success float-right"><i class="fas fa-arrow-left"></i></a>
                    </div>
                </div> 
            </div>
            <div class="card-body">
                <h3>Step 2</h3>
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
                <form action="{{ route('register.post.step.2') }}" method="POST">
                    @csrf
                    <div class="form-group">
                        <label for="name">Description: </label>
                        <input type="text" name="description" class="form-control mb-2" placeholder="Enter description" value="{{ session()->get('register.description') }}">
                        <a type="button" href="{{ route('signup') }}" class="btn btn-warning">Back to Step 1</a>
                        <button type="submit" class="btn btn-primary">Continue</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection  

resources/views/register/step3.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-10">
                        <h5>Product Detail>/h5>
                    </div>
                    <div class="col-md-2">
                        <a href="{{ route('register.create.step.2') }}" class="btn btn-md btn-success float-right">>i class="fas fa-arrow-left">>/i>>/a>
                    </div>
                </div> 
            </div>
            <div class="card-body">
                <h3>Step 3>/h3>
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}>/li>
                            @endforeach
                        </ul>
                    </div>
                @endif
                <hr>
                @if(isset($register->productImg))
                    <img alt="Product Image" src="/storage/productimg/{{$register->productImg}}"/>
                @endif
                <form action="{{ route('register.post.step.3') }}" method="post" enctype="multipart/form-data">
                    {{ csrf_field() }}

                    <div class="form-group">
                        <label for="name">Upload Image: >/label>
                        <input type="file" {{ (!empty($register->productImg)) ? "disabled" : ''}} class="form-control-file" name="productimg" id="productimg" aria-describedby="fileHelp">
                        <small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.>/small>
                    </div>
                    <a type="button" href="{{ route('register.create.step.2') }}" class="btn btn-warning">Back to Step 2>/a>
                    <button type="submit" class="btn btn-primary">Review Details>/button>
                </form>>br/>
            </div>
        </div>
    </div>
    @if(isset($register->productImg))
    <form action="{{ route('remove.image') }}" method="post">
        {{ csrf_field() }}
    <button type="submit" class="btn btn-danger">Remove Image>/button>
    </form>
    @endif
@endsection   

resources/views/register/step4.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <h5>Product Detail</h5>
            </div>
            <div class="card-body"> 
                <h3>Review Details</h3>
                <form action="{{ route('store') }}" method="post" >
                    {{ csrf_field() }}
                    <table class="table table-bordered">
                        <tr>
                            <td>Name:</td>
                            <td><strong>{{$register->name}}</strong></td>
                        </tr>
                        <tr>
                            <td>Description:</td>
                            <td><strong>{{$register->description}}</strong></td>
                        </tr>
                        <tr>
                            <td>Image:</td>
                            <td><strong><img alt="Product Image" src="/storage/productimg/{{$register->productImg}}"/></strong></td>
                        </tr>
                    </table>
                    <a type="button" href="{{ route('signup') }}" class="btn btn-warning">Back to Step 1</a>
                    <a type="button" href="{{ route('register.create.step.2') }}" class="btn btn-warning">Back to Step 2</a>
                    <button type="submit" class="btn btn-primary">Register</button>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection 

resources/views/register/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-P5MgMn1jBN01asBgU0z60Qk4QxiXo86+wlFahKrsQf37c9cro517WzVSPPV1tDKzhku2iJ2FVgL67wG03SGnNA==" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/js/all.min.js" crossorigin="anonymous"></script>
    <title></title>
</head>
<body class="bg-dark">
     @if (Session::has('message'))
        <div class="alert alert-info">{{ Session::get('message') }}</div>
    @endif
    <div class="container">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Product Detail</h5>
                        </div>
                        <div class="col-md-2">
                            <a href="{{ route('signup') }}" class="btn btn-md btn-success float-right"><i class="fas fa-plus"></i></a>
                        </div>
                    </div> 
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Product Name</th>
                            <th scope="col">Product Description</th>
                        </tr>
                        </thead>
                        <tbody>
                        @foreach($products as $product)
                            <tr>
                                <th scope="row">{{$product->id}}</th>
                                <td><a href="">{{$product->name}}</a></td>
                                <td>{{$product->description}}</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 
Step 6 : Making Files Public

You need to change following things. Change disk config : Open filesystems.php which is located under public directory. Change the default parameter from local to public. By doing this file will be stored in storage/app/public directory.

config/filesystems.php

'default' => env('FILESYSTEM_DRIVER', 'public'),

Symlink. Put a symlink from /public/storage to /storage/app/public folder, with one Artisan command:

php artisan storage:link
Output:

Step 1:

Step 2:

Step 3:

Step 4:

It will help you....

Share: