I recently wanted to test a controller POST in Tinker, so I needed to create the Request Object to pass into the POST controller. I couldn’t find a decent answer on Google, so here’s my solution:
First, I created the formRequest class which was the bit that I wanted to test in Tinker. The Form Request class handles all the validation and subsequent saves. My model has dependant children, so it’s not always just a simple $post->update(validated attributes).
php namespace App\Http\Requests; use App\Models\Task; use Carbon\Carbon; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class TaskRequest extends FormRequest { private $_validator; private $_task; /** * Determine if the user is authorized to make this request. * * @return bool */ // public function authorize() // { // return false; // } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'task_name' => ['required', 'max:100'], 'task_description' => ['nullable', 'max:1024'], 'due_date' => ['nullable', 'max:50','after:today'], // ... and more ]; } public function validator() { return $this->_validator ?? $this->_validator = Validator::make($this->sanitize(), $this->rules()); } /** * Convert any of your incoming variables, such as dates to required format **/ public function sanitize() { // get request vars $vars = $this->all(); if ( !empty($vars['due_date']) ) { $date = new Carbon($vars['due_date'] ); $vars['due_date'] = $date->toDateTimeString(); } return $vars; } public function save() { if ( $this->validator()->fails() ) return false; return $this->_task = Task::create( $this->validator()->validated() ); }
And then in Tinker you can create this class and then user the merge method to add your post variables as follows:
$form = new App\Http\Requests\TaskRequest();
$form->merge(['task_name'=>'test task','due_date'=>'2022-04-22Z15:45:13UTC']);
$form->validator()->validated();
=> [
"task_name" => "test task",
"due_date" => "2022-04-22 15:45:13"
]
And that’s it!