10-Apr-2023
.
Admin
Hi Guys,
In this tutorial laravel 6 required_with Validation. You can validate required_with validation rules.The field under validation must be present and not empty only if any of the other specified fields are present.
If there is a dependent item (multiple values ??separated by commas: foo, bar, ...) and the item has a value, and the specified item has a value (empty or not null).
Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Location;
class MainController extends Controller
{
public function index()
{
return view('form.index');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'surname' => 'required_with:name'
]);
return back();
}
}
Create Form
Following the path in create blade file: path=resources/views/from/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 required_with Validation Example</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 mt-5">
<div class="card">
<div class="card-header bg-light">
Laravel 6 required_with Validation Example
</div>
<div class="card-body">
@if (count($errors) > 0)
<div class="row">
<div class="col-md-12">
<div class="alert alert-danger">
@foreach($errors->all() as $error)
{{ $error }} <br>
@endforeach
</div>
</div>
</div>
@endif
<form action="{{route ('form.store')}}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }} ">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" value="{{old('name')}}" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Surname:</label>
<input type="text" name="surname" value="{{old('name')}}" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-block">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If name is empty the required check will be skipped,you need to use the surname to conditionally add rules based on the conditions you want.
It Will help you....
#Laravel
#Laravel 6