ABD
ABD

Reputation: 889

How to do Uploaded File Validations in Model in Laravel

This is my Previous Question's Continuation

I am using Model for Validations

I will send the values to the model by this way

$VehicleData = Input::all();
$validation  = Validator::make($VehicleData, VehicleModel::$rules);

And Validate using the following rule

public static $rules = array(
        'VehicleNumber' => 'required|unique:vehicle', 
        'NumberSeats' => 'required', 
);

But Now i want to do validate the Upload File to for size and extension

I tried to do it in the Model in the SetFooAttribute

public function setInsurancePhotoAttribute($InsurancePhoto)
{
    if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000')
    {
    $this->attributes['InsurancePhoto'] = Input::get('VehicleCode') . '-InsurancePhoto.' . Input::file('InsurancePhoto')->getClientOriginalExtension();
    Input::file('InsurancePhoto')->move('assets/uploads/vehicle/', Input::get('VehicleCode') . '-InsurancePhoto.' . Input::file('InsurancePhoto')->getClientOriginalExtension());
    }
}

But I realize it is a Bad Practice. Because it will called only after the validations and when this is called VehicleModel::create($VehicleData);

I don't know where to do the File Validations and How in the Model.

Kindly suggest me the way to proceed.

Upvotes: 0

Views: 2119

Answers (1)

ctf0
ctf0

Reputation: 7579

in the model

public static $rules = array(
    'VehicleNumber'  => 'required|unique:vehicle', 
    'NumberSeats'    => 'required',
    'InsurancePhoto' => 'required|image|mimes:jpg,png,gif|max:2000'
);

in the controller

$VehicleData = Input::all();
$validation  = Validator::make($VehicleData, VehicleModel::$rules);
    if($validation->passes())
    {
        // Input::file('InsurancePhoto') stuff
        // store the data to the db
    }

Upvotes: 4

Related Questions