Skip to content

Instantly share code, notes, and snippets.

@bosunski
Last active October 7, 2018 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bosunski/eddb7af2de66cdcf6e6dd57a1724cfc5 to your computer and use it in GitHub Desktop.
Save bosunski/eddb7af2de66cdcf6e6dd57a1724cfc5 to your computer and use it in GitHub Desktop.
Dynamic Form Validation in Laravel
<?php
namespace App\Http\Controllers;
use App\Http\Requests\FooRequest;
class BudgetController extends Controller
{
// ...
public function makeFoo(FooRequest $request)
{
// Do wonderful Stuffs
}
// ...
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class FooRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$optionalRules = [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
];
$requiredRules = [
'location' => 'required',
'business_category' => 'required',
'phone' => 'required',
'business_name' => 'required|string|max:255',
];
return !Auth::check() ? array_merge($optionalRules, $requiredRules) : $requiredRules;
}
public function messages() {
return [
'name.required' => 'Please input your name.',
'email.required' => 'Please input your email.',
'email.unique' => 'The email has already been taken. Choose another.',
'password.required' => 'Please input your password.',
'password.min' => 'Password should not be less than 6 characters.',
'password.confirmed' => "Passwords doesn't match.",
'location.required' => "Please input your location",
'business_name.required' => "Please input your business_name",
'business_category.required' => "Please input your business_category",
'phone.required' => "Please input your phoneNumber",
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment