I can't find any solution on how to display error messages from custom validation. I can not find it even on StackOverflow. My problem is that I have my controller and I need to validate some stuff in my custom class.
Controller:
public function store()
{
$customStuff = new MyTestClass();
$variable = $customStuff->myCustomValidation(5 );
return view('test.index', compact('variable'));
}
And custom class:
namespace App\Classes;
class MyTestClass
{
public function myCustomValidation($a = null, $b = null)
{
if (empty($a))
{
dd('error 1'); // how to throw message here
}
elseif (empty($b))
{
dd('error 2'); // how to throw message here
}
else
{
return ($a $b);
}
}
}
This is just a sample code. I know how to use Validator
inside Controller
but is it possible to return an error back to the user if something is wrong in the custom class
? Instead of dd()
, it has to be an error message to the user.
CodePudding user response:
If you want to return that the validation failed to your view then do
return redirect()->back()->withErrors(['Message here!']);
And if you return as a API response then do
return response()->json(['error' => 'Message here!'], 404); // Or any other status code
CodePudding user response:
<?php
namespace App\Classes;
class MyTestClass
{
public function myCustomValidation($a = null, $b = null)
{
abort_if(empty($a), 403, 'error 1');
abort_if(empty($b), 403, 'error 2');
return ($a $b);
}
}
CodePudding user response:
Why did you created a plain Class for validation?
You can use laravel rules if you are trying to create a custom validator
If you don't want to use a validator you can set a flash message