Baptiste Arnaud Baptiste Arnaud - 4 months ago 9
PHP Question

Request validation, how to show errors?

I have a form that allows the user to upload 3 files.

Here is the Controller function called :

public function registerUpdate(CardAvsRequest $request){
$id = Auth::user()->id;
$first_name = User::find($id)->student->first_name;
$last_name = User::find($id)->student->last_name;
$name = $first_name . " " . $last_name;
$message = "";
if ($request->hasFile('carte-id'))
{
$image1 = $request->file('carte-id');
if($image1->isValid())
{
if ($request->hasFile('avs'))
{
$image2 = $request->file('avs');

if($image2->isValid())
{
if ($request->hasFile('permit'))
{
$image3 = $request->file('permit');

if($image3->isValid())
{
$path = config('card.path')."/$id";
$name = "carte-id.".$image1->getClientOriginalExtension();
$image1->move($path, $name);
$path = config('card.path')."/$id";
$name = "avs.".$image2->getClientOriginalExtension();
$image2->move($path, $name);
$path = config('card.path')."/$id";
$name = "permit.".$image3->getClientOriginalExtension();
$image3->move($path, $name);
$message = "Super ! Vous avez importé tous les fichiers nécessaires.";
//ici on dit dans la DB que l'utilisateur à uploadé tous les fichiers
}
}
}
}
}

}
return redirect()->route('account', $id)->with('message', $message);
}


So the Validation rules are set in CardAvsRequest.php :

class CardAvsRequest extends Request
{
/**
* 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()
{
return [
'carte-id' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'avs' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'permit' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
];
}
}


I would like to know how to display errors if a file isn't validated.

Isn't it supposed to work like this ?

@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif


Any ideas ?

Answer

This is how Laravel 5.2 documentation suggestion to validate input and return error if any. The view looking good and will display error if occurred.

   public function store(Request $request)
   {
     $rule = 'required|file|mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000';

      $validator = Validator::make($request->all(), [
          'file_one'   => $rule,
          'file_two'   => $rule,
          'file_three' => $rule,
      ]);

      if ($validator->fails()) {
          return redirect('account')
                     ->withErrors($validator)
                     ->withInput();
      }

     // no errors proceed managing your files

    }