Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 720
prgrm Avatar asked Feb 14 '17 15:02

prgrm


People also ask

How do I check if a request is null?

The IsNullOrEmpty() method returns true if the input is null . IsNullOrEmpty() returns true if the input is an empty string.


2 Answers

A simple count check will do

if (count($request->all())) {
  // foreach here.
}
like image 198
Saravanan Sampathkumar Avatar answered Oct 07 '22 00:10

Saravanan Sampathkumar


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.

like image 39
mbozwood Avatar answered Oct 07 '22 00:10

mbozwood