How to add custom form validation in Laravel? - php

I am trying to add custom validation in my controller.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;
class MyController extends Controller
{
public function store(Request $req)
{
$v = Validator::make($req->all(), [
'contract_ref' => 'required'
]);
$v->after(function($v) use(&$req){
dd('custom validations');
// list of custom validations
if ($req->div_id == '') {
$validator->errors()->add('div_id', 'Please select a Division');
};
});
dd('NO!');
if ($v->fails()) {
//
}
$v->validate();
}
}
However, for some reason I don't understand. Nothing in the -after closure is being done. In example above, I get "NO!" dumped instead of the expected "custom validations"
This ->after has worked for me previously and I don't get why it is not working here.

Your are requesting dd('NO!') before the actual validate
try this :
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Redirect;
use Response;
use Validator;
class MyController extends Controller
{
public function __contruct()
{
}
public function store(Request $req)
{
$v = Validator::make($req->all(), [
'contract_ref' => 'required'
]);
$v->after(function ($v) use (&$req) {
dd('custom validations');
// list of custom validations
if ($req->div_id == '') {
$validator->errors()->add('div_id', 'Please select a Division');
};
});
if ($v->fails()) {
//
}
$v->validate();
dd('NO!');
}
}

I reccomend using Closures https://laravel.com/docs/8.x/validation#using-closures as it can keep all of your validation logic in one place
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function ($attribute, $value, $fail) {
if ($value === 'foo') {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);

Have you used that?
$v->validate();
Below is an example of validation. You can also check your invalid input values inside fail check.
$validation_array = [
'id' => 'required',
'date' => 'required|date',
'material_type' => 'required',
'fabric' => 'required_if:material_type,==,0',
'color' => 'required_if:material_type,==,1',
'quantity' => 'required|numeric',
'unit' => 'required',
];
$validation_messages_array = [
'fabric.required' => 'The fabric field is required when material type is fabric.',
'color.required_if' => 'The color field is required when material type is blind.'
];
$validator = Validator::make(
$request->all(),
$validation_array,
$validation_messages_array
);
$validator->after(function ($validator) {
});
if ($validator->fails()) {
//code if not valid
}
$validator->validate();

Related

Laravel 7 "Class 'App\Http\Controllers\Validator' not found"

A few days ago I started learning laravel 7.
I bought a course on udemy.
I got to the part where the real registry system went and started to rewrite the code like in the video, but when I do it I get an error!
Error Message: "Class 'App\Http\Controllers\Validator' not found"
I've been trying to fix this for hours, and I'm not doing well
AccountController.php
<?php
namespace App\Http\Controllers;
class AccountController extends Controller
{
public function getcreate(){
return view('account.create');
}
public function postcreate(){
$validator = Validator::make(Input::all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:20|min:3|unique:users',
'password' => 'required|min:6',
'repeat_pass' => 'required|same:password'
));
if($validator->fails()){
die('ERROR');
}
else{
die('Cool');
}
}
}
you need to import validator namespace
use Illuminate\Support\Facades\Validator;
then instead of Input you could use request()->all() helper function
so it will be like this
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
class AccountController extends Controller
{
public function getcreate(){
return view('account.create');
}
public function postcreate(){
$validator = Validator::make(request()->all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:20|min:3|unique:users',
'password' => 'required|min:6',
'repeat_pass' => 'required|same:password'
));
if($validator->fails()){
die('ERROR');
}
else{
die('Cool');
}
}
}
You will need to import the Validator class from it's correct namespace which is Illuminate\Support\Facades. So goes with Input class. Best way I can suggest is to add these in aliases section in config\app.php like below:
'aliases' => [
// other imports
'Validator' => Illuminate\Support\Facades\Validator::class,
'Input' => Illuminate\Support\Facades\Input::class,
]
Now, you can simply use them in your controller like below:
<?php
namespace App\Http\Controllers;
use Validator;
use Input;
class AccountController extends Controller
{
// rest of your code
}
You can use Validator namespace in your controller at top like:
use Validator;

Laravel API: The POST method is not supported for this route. Supported methods: GET, HEAD

I am sending a post request to http://localhost/projects/webdevlist/public/api/register and getting the 405 error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.
routes\api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', 'Api\AuthController#register');
Api\AuthController.php:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create($validatedData);
$accessToken = $user->createToken('token')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken]);
}
}
If I remove the form validation then I can do post requests just fine and return a result in postman like this.
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
return response()->json([
$request->name,
$request->email,
$request->password,
]);
}
}
But something is wrong with my validation. Why does the validation cause me to no longer be able to accept POST requests?
Here is my POST request:
The problem with your validation is the password field.
Your rule say that it need to be required and confirmed, but confirmed against which field?
You need to add a field with name password_confirmation your view, if not added yet.
<input type="password" name="password_confirmation" />
And then add a new rule for password_confirmation field:
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);

If form validation failed then redirect back with input using custom request class (laravel 5.8)

The problem is i want to return back with the inputs when the validation is fails. Here I'm using a custom request class to validate user input.
Now my question is where i place this piece of code on Controller Or in Request class.
or is there another way to do it?
Here is the code i want to use:
return redirect()->back()->withInput();
Here is the Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\Admin\counter\CreateCounterRequest;
use App\Models\Admin\Counter;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CounterController extends Controller
{
public function store(CreateCounterRequest $request)
{
Counter::create([
'title' => $request->title,
'ion_icon' => $request->ion_icon,
'counter_value' => $request->counter_value,
]);
session()->flash('success', 'Counters created successfully.');
return redirect(route('counter.index'));
}
}
Here is the Request Class:
<?php
namespace App\Http\Requests\Admin\counter;
use Illuminate\Foundation\Http\FormRequest;
class CreateCounterRequest extends FormRequest
{
public function rules()
{
return [
'ion_icon' => 'required',
'title' => 'required',
'counter_value' => 'required|numeric',
];
}
}
you can use a method from FormRequest class, that is failedValidation() method.
and example code is like this:
protected function failedValidation(Validator $validator)
{
return back()->withErrors($validator)->withInput();
}
you must add a argument from Illuminate\Contracts\Validation\Validator class to your method failedValidation and add Illuminate\Http\RedirectResponse class for get redirect method.
add Illuminate\Validation\ValidationException class, if not your method cant be read.
please check this
use Illuminate\Support\Facades\Validator;
protected function validator(array $data)
{
return Validator::make($data, [
'ion_icon' => 'required',
'title' => 'required',
'counter_value' => 'required',
]);
}
public function store(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return redirect()->route('your_route')->withInput(['title' => $request->title, 'icon_icon' => $request->icon_icon,'counter_value' => $request->couter_value,'phone_number'=>$request->phone_number])->withErrors($validator, 'your_desire_name');
}
Counter::create([
'title' => $request->title,
'ion_icon' => $request->ion_icon,
'counter_value' => $request->counter_value,
]);
session()->flash('success', 'Counters created successfully.');
return redirect(route('counter.index'));
}
Want In Your Blade File Show this error message
<div >
<input type="text" name="title" class="form-control"
value="{{old('title')}}" required>
</div>
#if ($errors->your_desire_name->has('title'))
<span class="messages"><p
class="text-danger error">{{ $errors->your_desire_name->first('title') }}</p></span>
#endif

BadMethodCallException in Macroable.php line 74: Method validate does not exist

I'm getting little bit issue in laravel 5.2
When i submit data throgh post. data found in request but not save. pls help.
https://www.awesomescreenshot.com/image/3111642/0ec1946875e85f53eaec7970483ff5f0
Customer.php
<?php
namespace App\Http\Controllers;
enter code here
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Customer extends Controller {
public function index() {
//$members = Customer::latest()->paginate(10);
return view('pages.admin.customers.customers', compact('customers'));
// ->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
return view('pages.admin.customers.create');
}
public function store(Request $request) {
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
Customer::create($request->all());
return redirect()->route('customer.index');
}
}
Model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = [
'firstname', 'lastname'
];
protected $table = 'customers';
}
You have a mistake in validation, instead of:
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
You need use:
$this->validate($request, [
'firstname' => 'required',
'lastname' => 'required',
]);
There are other ways to validate which you can read about in official documentation Validation.

Laravel 5 Auth::attempt() always failing

my Auth::attempt() returning fail everytime, I'm using my own subscribers table, i have already changed settings in config/auth.php to use subscribers table.
below is my logincontroller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Subscriber;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class LoginController extends Controller
{
public function login()
{
$email = Input::get('email');
$password = Input::get('password');
// $subscriber = Subscriber::where('email', $email)->first();
// $checked = Hash::check($password, $subscriber->pass);
if (Auth::attempt(['email' => $email, 'pass' => $password]))
{
return 'it workedddd.';
}
else
return 'failed';
}
}
subscriber model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subscriber extends Model
{
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['password', 'remember_token'];
}
subscriber controller
<?php
namespace App\Http\Controllers;
use App\Subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class SubscribersController extends Controller
{
public function newSubscriber(Request $request) //function to register new subscriber
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email|unique:subscribers,email',
'password' => 'required|min:5',
'address' => 'required',
'city' => 'required',
'state' => 'required',
'zip' => 'required',
'phone' => 'required|unique:subscribers,phone'
]);
if ($validator->fails()) {
return redirect('/register')
->withErrors($validator)
->withInput();
}
$subscriber = new Subscriber();
$subscriber->firstname = Input::get('firstname');
$subscriber->lastname = Input::get('lastname');
$subscriber->email = Input::get('email');
$subscriber->pass = Hash::make(Input::get('password'));
$subscriber->address = Input::get('address');
$subscriber->city = Input::get('city');
$subscriber->state = Input::get('state');
$subscriber->zip = Input::get('zip');
$subscriber->phone = Input::get('phone');
$subscriber->trial_time = 30;
$subscriber->date_signed_up = Carbon::now();
$subscriber->next_bill_date =Carbon::now()->addMonth(1);
$subscriber->account_status = 'trial';
$subscriber->save();
return $subscriber;
}
}
routes
Route::get('/', function () {
return view('home');
});
Route::post('/', 'LoginController#login');
Route::get('contact', function() {
return view('contact');
});
Route::get('register', function() {
return view('register');
});
Route::post('register', 'SubscribersController#newSubscriber');
Route::get('feedback', function() {
return view('feedback');
});
Route::get('dashboard', array(
'before' => 'auth.basic',
function(){
return view('dashboard.user');
}));
When using Auth::attemp()You can't do:
Auth::attempt(['email' => $email, 'pass' => $password])
It should be:
Auth::attempt(['email' => $email, 'password' => $password])
So in your case you should add the following to your User model:
public function getAuthPassword()
{
return $this->attributes['pass'];
}
In your newSubscriber method change
$subscriber->pass = Hash::make(Input::get('password'));
to
$subscriber->pass = bcrypt(Input::get('password'));
Your Subscriber model should look like this..
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Subscriber extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['pass', 'remember_token'];
public function getAuthPassword()
{
return $this->pass;
}
}
Hope this will work.

Categories