Why are you declaring an validator extension in the AppServiceProvider.php file ?
According to me it's not necessary.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Dear Friends, I am looking a file upload pdf validation for limiting the number of pages in PDF uploaded . I tried many ways . But now get Exception as
"message": "Object of class App\Rules\MaxPages could not be converted to string",
"exception": "Error",
"file": "C:\xampp\htdocs\ksit_mission\vendor\laravel\framework\src\Illuminate\Validation\ValidationRuleParser.php",
"line": 134,
my AppServiceProvider class is
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use Smalot\PdfParser\Parser;
use App\Rules\MaxPages;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// $this->app['validator']->extend('max_pages', function ($attribute, $value, $parameters, $validator) {
// $maxPages = $parameters[0];
// $rule = new MaxPages($maxPages);
// return $rule->passes($attribute, $value);
// });
Validator::extend('max_pages', function ($attribute, $value, $parameters, $validator) {
if (!is_array($value)) {
return false;
}
$maxPages = $parameters[0];
foreach ($value as $file) {
if (!$file->isValid()) {
return false;
}
$pdf = (new Parser())->parseFile($file->path());
$numPages = count($pdf->getPages());
if ($numPages > $maxPages) {
return false;
}
}
return true;
});
}
}
<?php
namespace App\Rules;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Smalot\PdfParser\Parser;
class MaxPages extends Rule
{
protected $maxPages;
public function __construct($maxPages)
{
$this->maxPages = $maxPages;
}
public function passes($attribute, $value)
{
if (!is_array($value)) {
return false;
}
foreach ($value as $file) {
if (!$file->isValid()) {
return false;
}
$pdf = (new Parser())->parseFile($file->path());
$numPages = count($pdf->getPages());
if ($numPages > $this->maxPages) {
return false;
}
}
return true;
}
public function message()
{
return "The :attribute must have a maximum of {$this->maxPages} pages.";
}
}
call it in 6 places in controller as
'quali_upload.*' => ['required', 'file', 'mimes:pdf', 'max:2048', new MaxPages(3)], // 2 times called
'upload_additional.*' => ['nullable','file','mimes:pdf','max:2048',new MaxPages(2)], // 2 times called
'uploadworkexperience.*' => ['nullable','mimes:pdf','max:2048',new MaxPages(1)], // 2 times clalled
with included in controller
use App\Rules\MaxPages;
Please help
Thanks
Anes P A
Please or to participate in this conversation.