8

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?

5 Answers 5

12

A simple count check will do

if (count($request->all())) {
  // foreach here.
}
Sign up to request clarification or add additional context in comments.

Comments

8

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.

2 Comments

You could simplify this function by getting rid of those inner if statements and instead using return count($request->all()) > 0; or return count($request->all()) > 1;
^ exactly. No need for the else. The first if statement will return true or false.
8

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.

1 Comment

I would go for this if (!empty($request->except('_token','_method')))
3

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.

Comments

0

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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.