prgrm
prgrm

Reputation: 3833

Checking if a request array is empty in Laravel

I have a dynamically generated form that gives me an array of inputs. However the array might be empty, then the foreach will fail.

    public function myfunction(Request $request)
    {
    if(isset($request))
     {
       #do something
     }

    }

This obviously doesn't work since it is a $request object and is always set. I have no idea however how to check if there is any input at all.

Any ideas?

Upvotes: 8

Views: 48742

Answers (5)

stanley mbote
stanley mbote

Reputation: 1306

A simple modification @Saravanan code above. I agree with him that a simple check on the total number of inputs in the request will do.

if(count($request->all()) >= 1)
{
   //execute if the request has one or more input fields
}
else {
  //executes if the request is totally empty.
}

Upvotes: 0

ordinov
ordinov

Reputation: 79

Request class has a except() method that includes everything except the key/keys defined. So:

if ( !empty( $request->except('_token') ) )

execute the code when there is "something" in the request array.

Upvotes: 8

mbozwood
mbozwood

Reputation: 1402

I always do this with my installations by adding a function to the Controller in the App\Http\Controllers directory.

use Illuminate\Http\Request;
public function hasInput(Request $request)
{
    if($request->has('_token')) {
        return count($request->all()) > 1;
    } else {
        return count($request->all()) > 0;
    }
}

Rather self explanatory, return true if other input variables outside of the _token, or return true if no token and contains other variables.

Upvotes: 8

edcs
edcs

Reputation: 3879

If you have a reference of the form inputs you're expecting, then Request::has() might be a good method to use. Request::all() could contain things like the XSRF token and would give you false positives.

Upvotes: 3

Saravanan Sampathkumar
Saravanan Sampathkumar

Reputation: 3261

A simple count check will do

if (count($request->all())) {
  // foreach here.
}

Upvotes: 12

Related Questions