Francisunoxx Francisunoxx - 3 months ago 7
PHP Question

Is isEmpty() method is applicable for $request?

Is it possible to use

isEmpty()
method for validating a input a for empty field? I have a
validate($request)
where it has a multiple form to be filled up. I have additional form where it's not totally required.

Controller:

$this->validate($request,
[
'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
'content' => 'required',
'category' => 'required',
'approver' => 'required',
'recipient' => 'required',
]);


$document = new Document();
$user = Auth::user();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();

foreach($request->recipient as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}


I have a form name
department
which is not required to be filled out. I'm trying to check if it's not empty it will insert this into database. If empty nothing will happen.

if(!$request->department->isEmpty())
{
foreach($request->department as $departmentId)
{
foreach(Department::find($departmentId)->users()->get() as $user1) //find the users belonging to the current department
{
$document->sentToUsers()->sync([ $user1->id => ['sender_id' => $user->id]],false );
}
}
}
else
{

}

Answer

You can always use empty():

if(!empty($request->department))

I guess isEmpty() is for collection only and you're checking property of Request object:

The isEmpty method returns true if the collection is empty; otherwise, false is returned