trafficker
trafficker

Reputation: 601

Validate file in Laravel

I have validation:

public function saveUser($request)
    {
        // validacja
        $this->validate($request, [
            'name' => 'required|string',
            'surname' => 'required|string',
            'email' => 'required|email'
        ]);

        if ($request->hasFile('userPicture')) {
            $this->validate($request, [
                'userPicture' => 'image|max:1000'
            ]);
        }

        // save
    }

I need add to this validation:

'userPicture' => 'image|max:1000'

How can I do this ?

Upvotes: 0

Views: 56

Answers (3)

simplism
simplism

Reputation: 98

What about:

'userPicture' => 'max:1000|mime:image/jpeg'

The documentation states you can use the following mime types: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

image/jpeg allows for: image/jpeg - jpeg jpg jpe

For more information: https://laravel.com/docs/5.8/validation#rule-mimes

Upvotes: 1

nakov
nakov

Reputation: 14268

Mime is a filetype rule that you need to set.

So, you can first make the rules array and then validate:

public function saveUser($request)
{
    // validacja
    $rules = [
        'name' => 'required|string',
        'surname' => 'required|string',
        'email' => 'required|email'
    ];

    if ($request->hasFile('userPicture')) {
        $rules['userPicture'] = 'image|max:1000|mimes:jpeg'
    }

    $this->validate($request, $rules);
    // save
}

Upvotes: 0

rené
rené

Reputation: 114

Depending on your Laravel version there are some different ways.

https://laravel.com/docs/5.8/validation#rule-image https://laravel.com/docs/5.8/validation#rule-dimensions

Upvotes: 0

Related Questions