Since I am using csrf in the form, the array $data
that is passed in request function is never empty. How to resolve this so that when i submit the form without any input fields filled, I get "data is empty"?
view.blade.php
<form action="{{url('/userdata')}}" method="POST">
@csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Controller.php
public function userdata(Request $request)
{
$data=$request ->all();
if(!empty($data)){
echo "data is filled";
}else{
echo "data is empty";
}
}
Sorry I misunderstood your question on my first answer. A value will always be submitted for input elements on the page, even if they're empty. The proper way to do this is to create a request validation.
Create something like this class, though much neater I'm sure ;)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserdata extends FormRequest {
public function authorize() {return true;}
public function rules() {
return ["name" => ["required", "max:64"]];
}
}
And then edit the signature of your controller method so instead of expecting a Request
it looks for your validation class (don't forget a use
statement above):
public function userdata(StoreUserdata $request){
// ....
}
Now, your requests will fail if the name
input is empty, or is too long. There are a lot of possible validation rules.
You can use required in the input fields if you don't want the form to submit empty.
<form action="{{url('/userdata')}}" method="POST">
@csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Otherwise if name is your only field you can do this:
public function userdata(Request $request){
$data = $request->except(["_token"]);
if($data['name'] != ""){
echo "data is filled";
} else {
echo "data is empty";
}
}
You can use the get()
method:
public function userdata(Request $request){
$data = $request->get("_token");
if(!empty($data)){
echo "data is filled";
} else {
echo "data is empty";
}
}