0
votes

I am making a website that during the registration process allows the users to upload some images. The image uploader is done via ajax and the data stored in the session ready to be permanently stored in the database after a successful registration. How would I implement a custom validation rule to check the session data is OK since it's not actually tied to a specific form field.

This is how it is working at the moment:

<?php namespace App\Services;

use App\User;
use Event;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use App\Events\UserRegistered;
use Session;

class Registrar extends Validator implements RegistrarContract {

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function validator(array $data)
    {
        Validator::extend('required_images', function($attribute, $value, $parameters)
        {
            if (!Session::has('images') || empty(Session::get('images'))) {
                return false;
            } else {
                return true;
            }
        });

        return Validator::make($data, [
            'first_name' => 'required_images|required|max:255',
            'last_name' => 'required|max:255',
            'discount_code' => 'max:255',
            'register_email' => 'required|email|confirmed|max:255|unique:users,email',
            'register_password' => 'required|confirmed|min:6|max:60'
        ]);
    }

As you can see I have created the rule required images and tied it to the first_name field at the moment. But it has nothing to do with the first name field or any of the other fields so how should I be calling it?

1

1 Answers

2
votes

If your custom rule is not for validate forms data, then do not make a rule for this. Instead create a helper class with some cool functions:

namespace Services;

class Helper{

    static function validateImages(){
        if (!Session::has('images') || empty(Session::get('images'))) {
                return false;
            } else {
                return true;
        }
    }

}

As your validation is not attached to any field, then create a custom warning at view:

@if (Session::has('warning'))
    <p>{{ Session::get('warning') }}</p>
@endif

... here the form elements ...

Then, you can validate the data in this way:

if (! Helper::validateImages()){
    return redirect()->back()->with("warning", "You don't have any images");
}