Have a method that's importing CSV-data into a Database. I do some basic validation using
class CsvImportController extends Controller
{
public function import(Request $request)
{
$this->validate($request, [
'csv_file' => 'required|mimes:csv,txt',
]);
But after that things can go wrong for more complex reasons, further down the rabbit hole, that throws exceptions of some sort. I can't write proper validation stuff to use with the validate
method here, but, I really like how Laravel works when the validation fails and how easy it is to embed the error(s) into the blade view etc, so...
Is there a (preferably clean) way to manually tell Laravel that "I know I didn't use your validate
method right now, but I'd really like you to expose this error here as if I did"? Is there something I can return, an exception I can wrap things with, or something?
try
{
// Call the rabbit hole of an import method
}
catch(\Exception $e)
{
// Can I return/throw something that to Laravel looks
// like a validation error and acts accordingly here?
}
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) { return $value == 'foo'; });
then you can add the foo rule in the rules'csv_file' => 'required|foo|mimes:csv,txt',
?? – Maraboctry { //my stuff } catch (Exception $ex) { echo $ex->getMessage(); //Message //$ex->getFile(); //File //$ex->getLine(); //Line }
– Raunak Guptatry { $validator = Validator::make($request, ['csv_file' => 'required|mimes:csv,txt']); if ($validator->fails()) { throw new Exception(implode('<br>', $validator->errors()->all()), 999); } } catch (Exception $ex) { if ($ex->getCode() == 999) { //this is a custom error } echo $ex->getMessage(); //Message }
– Raunak Gupta