Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate or remove for extra fields in laravel

Tags:

forms

php

laravel

It's posible to validate request with rules for additional fields, or remove that fields from request?

Simple example, I have FormRequest object with rules:

public function rules() {
        return [
            'id' => 'required|integer',
            'company_name' => 'required|max:255',
        ];
    }

And when I get post request with any other fields I want to get error/exception in controller or I want to get only id and company_name fields, with no any others. It's exist any feature in laravel with that, or I must make it in my way?

like image 892
Son Avatar asked Feb 10 '16 22:02

Son


3 Answers

Your post request with laravel has more stuff than just your form input so you need to check Request to see what is inside.

To get only the fields you want you can use:

$request->only(['fieldname1', 'fieldname2', 'fieldname3']);

or

$request->except(['fieldnameYouDontWant1', 'fieldnameYouDontWant2', 'fieldnameYouDontWant3']);

to exclude the ones you don't want.

like image 89
Can Celik Avatar answered Nov 13 '22 15:11

Can Celik


To remove key from request in Laravel, use:

$request->request->remove('key')
like image 35
Anton Ganichev Avatar answered Nov 13 '22 14:11

Anton Ganichev


Since Laravel 5.5 you can do this in your controller:

public function store(StoreCompanyRequest $request)
{
    Company::create($request->validated());
}

The validated() function returns only the fields that you have validated and removes everything else.

like image 19
user3743266 Avatar answered Nov 13 '22 14:11

user3743266