About request()->all() in Laravel

Laravel has more than one way to retrieve input from your form using your controller.
For example, if you are trying to retrieve the field CompanyName of a user from the form, you will need to use request, and your store function in the controller should be like below:

public function store(Request $request)
{
    //way to retrieve input from your form
    // 1
    $CompanyName = $request->input(‘CompanyName’);
    // 2
    $CompanyName = $request->CompanyName;
    // 3
    $CompanyName = $request->get(‘CompanyName’);
}

Observe that the three ways to do the work, there is a difference between all of this ways but I will not explain it in this post. I just want to make you in previously touch with those ways.. to give the notes about request()->all()

Request()->all()?!

Gives you the opportunity to retrieving all input data in simply way, and by using all() method you will retrieve all of the input data as an array.

How request all work

Let’s suppose that we have this form, with two fields company name and priority.

form for users to fill

When we will us request all in our store function we will get all those two fields simply with clear and efficient way and store theme in an array, like below

public function store(Request $request)
{
    // logic to store data to database.
    $request->validate([
        'Companyname' => 'required',
        'priority' => 'required',
    ]);

    Company::create($request->all());

    return redirect()->route('index')
                    ->with('success','Company created successfully.');
}

Security issues

There is a lot of opinion insisting to avoid using request()->all() may cause a security vulnerability. but you are safe if you’re using validation and the $fillable property in your Model.

protected $fillable = [
    'Companyname', 'priority'
];

ENDING THIS FLASH.. HAPPY CODING

Leave a Reply

Your email address will not be published. Required fields are marked *