I know this question is pretty old but I recently wanted to test a controller POST and found it difficult to find an answer, so here is my solution:
I created a formRequest class which I wanted to test in Tinker. The class looks something like this:
<?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()
);
}
In tinker:
$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"
]