try to create validator manually in Lumen. The official documentation is written:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
I wrote
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController,
Validator;
class Welcome extends BaseController
{
public function index()
{
$validator = Validator::make(
['test' =>'TestValidation'],
['test' => 'required|unique:posts|max:255']
);
}
}
but Lumen returns fatal error: Fatal error: Class 'Validator' not found in ...
I have tried to do like in Laravel 5:
use Illuminate\Support\Facades\Validator;
but then Lumen returns Fatal error: Call to a member function make() on a non-object in
Somebody knows how to use the Validator class in Lumen? Thank you.
In general, validation in Lumen works exactly like validation in Laravel, so you should consult the full Laravel validation documentation; however, there are a few important differences. Form requests are not supported by Lumen.
By default, Lumen's base controller class uses a ProvidesConvenienceMethods trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.
Unfortunately, this is not supported in Lumen. The Lumen documentation explains why. Lumen instead provides a helper method $this->validate available within Routes closures and Controllers. However, if you are building an API to scale, it may become important to have an elaborate and structured way to manage requests.
Lumen does not support sessions out of the box, so the $errors view variable that is available in every view in Laravel is not available in Lumen. Should validation fail, the $this->validate helper will throw Illuminate\ Validation\ValidationException with embedded JSON response that includes all relevant error messages.
Validator is a facade. Facades aren't enabled by default in lumen.
If you would like to use the a facade, you should uncomment the
$app->withFacades();
call in your bootstrap/app.php
file.
This is for Lumen version 5.3 (as shown in the docs):
use Illuminate\Http\Request;
$app->post('/user', function (Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users'
]);
// Store User...
});
https://lumen.laravel.com/docs/5.3/validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With