menu

Questions & Answers

Laravel 9: Trait with validation

I created a trait to use with a controller. The controller should start the trait function, which validates its input and then does a thing.

Inside the FooController.php:

[..]
$do_stuff = $this->create_stuff($input);

The trait:

    <?php
    namespace App\Traits;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Str;
    [..]
    use Illuminate\Support\Facades\Validator;
    
    trait Foo
    {
       public function create_stuff(Request $input)
        {
            // validation part
            $validatedData = $input->validate([
                    'Value' => 'required|numeric',
                    ]);
            // end of validation part

    [..]

Everything works fine without the validation part but as soon as I add it I get the error:

Argument 1 passed to App\\Http\\Controllers\\FooController::create_stuff() must be an instance of Illuminate\\Http\\Request, instance of stdClass given,[..]

I understand the $input is a 'normal' (?) PHP object and it seems the validation only works with 'request' objects, so how can I make this work?

Comments:
2023-01-20 23:01:13
public function create_stuff($input) if you want it to accept everything. By doing Request $input in your code, you've told PHP your function only accepts a Request object.
2023-01-20 23:01:13
You understand correctly; $input is currently a stdClass object, but you're defining it as Request $input. You'd have to call it via something like create_stuff(request()) (or a variable $request, etc), or use a manual validator, which accepts a plain array of input to validate: laravel.com/docs/9.x/validation#manually-creating-validators‌​. Oh, and @ceejayoz create_stuff($input) would fail for a stdClass or array, as $input->validate(...) would be invalid (unless this stdClass has a validate method of course)
2023-01-20 23:01:13
@TimLewis Fair; I was focused on the immediate reason for OP's error. You're right they're going to encounter additional issues along the way with my answer.
2023-01-20 23:01:13
I see, thanks guys @TimLewis and ceejayoz. I'll go with a manual validator then.
Answers(0) :