To access the custom method (videoData()) or the video data from your custom ValidationRule instance after validation in a FormRequest, you need a way to retrieve the specific rule instance that was used during validation. By default, Laravel does not expose the rule instances after validation—they are instantiated and used internally.
However, you can work around this by injecting the rule instance into your FormRequest, storing it as a property, and then accessing it after validation.
Step-by-step Solution
1. Store the Rule Instance in the FormRequest
In your FormRequest, define a property to hold the rule instance:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\UserMusicPlayerRule;
use App\Models\User;
class StoreVideoRequest extends FormRequest
{
/** @var UserMusicPlayerRule */
public UserMusicPlayerRule $musicPlayerRule;
public function rules()
{
// Instantiate the rule and store it on the request
$this->musicPlayerRule = new UserMusicPlayerRule($this->user());
return [
'video_url' => [$this->musicPlayerRule],
];
}
}
2. Access the Data in the Controller
After validation, you can access the videoData() method from the rule instance stored on the request:
public function store(StoreVideoRequest $request)
{
$videoData = $request->musicPlayerRule->videoData();
// Now you can use $videoData as needed
}
Notes
- This approach works because the same rule instance is used for validation and then available for later access.
- If you use validation directly on the controller (e.g.,
$request->validate()), this pattern won't work. It's only possible when you control the instantiation of the rule, such as in a customFormRequest.
Summary:
Store the rule instance as a property on your FormRequest, then access its data after validation in your controller.
Let me know if you need a more advanced solution (e.g., for array rules or multiple rules)!