php – Validation setup-ThrowExceptions

Exception or error:

Now I am working on to create a validation when user didn’t input which user will handle the task. The user_id input is stetted in a option list. In the TaskController:

public function create(Request $request)
    {

        $task = new Task();
        $task->description = $request->get('description'); 
        $task->user_id = $request->get('user_id');
        $val = Task::Inputvalidator($request->validated()); 
        $file = $request->file('file');
        if($request->hasFile('file')){
            foreach($file as $file){
                $file->move('storage/uploads', $file->getClientOriginalName());
                $task->image =\Storage::url("uploads/".$_FILES["file"]["name"][0]);
                $task->image2 =\Storage::url("uploads/".$_FILES["file"]["name"][1]);
                $task->save();
            }

        }
        $task->task_date = request('task_date');
        $dt1 = Carbon::now();
        $dt2 = Carbon::parse($task->task_date);
        if($dt1 > $dt2){
            echo $messages->first("You have to chose after today as the deadline");
            return redirect('/');
        }else{
            $dt3 = $dt1->diffInDays($dt2);
            $task->expired = $dt3;
        }


        $duplicate = Task::where('description',$request->get('description'))->first();
        $duplicateUser = Task::where('user_id',$request->get('user_id'))->first();
        $duplicateDate = Task::where('task_date',$request->get('task_date'))->first();
        if($duplicate&&$duplicateDate&&$duplicateUser)
        {
            return redirect('/')->with('popup', 'duplicate');
        } 
        else
        { 
            $task->save();
        } 

        return redirect('/'); 
    }

In my task model:

 protected $fillable = ['name','user_id','description','task_date'];

    public function user()
    {   
        return $this->belongsTo(User::class);
    }

    public static function Inputvalidator(Request $request){

            $rules = array(
            'user_id' =>'required|not_in:0'
            );
        $this->validate($request,$rules);
    }

    protected function getInputCredentials(Request $request){

        $validator = $this->inputvalidator($request);

        var_dump($validator); die();

        if($validator->passes())
        {
            return[
                'user_id' => Request::input('user_id')
            ];

            return true;
        }
        else{
            return redirect()->back()->withErrors();
        }
    }

But I now I come up different error, too few arguments, request need to instance. Now under this code, it said undefined variable rules. I am not too sure what should I fix this code. Can you help me to solve and check this code right or not? Thank you.

How to solve:
  1. Run php artisan make:request TaskRequest

  2. Fill the new app\Http\Requests\TashRequest.php file with:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TaskRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'user_id' =>'required|not_in:0',
        ];
    }
}
  1. In the controller do something like:

<?php

namespace App\Http\Controllers;

...

use App\Http\Requests\TaskRequest;

...

class YourControllerName extends Controller
{

...

    public function yourMethodName(TaskRequest $request)
    {
        $validatedData = $request->validated();

...

If the validation above fails it will return back with a 422 and the messages automatically ready to be pulled from the message bag.

Sources:

Example in the wild:

Answer´╝Ü

Instead of passing $this->validate($request,$rules) parameter inside Inputvalidator() function, simply pass the $request variable as the function expects.

//TaskController

$task->user_id = $request->get('user_id');
$val = Task::Inputvalidator($request); 

Instead of using Request Validation inside the model for reusability, Laravel provides Creating Form Request Validation under the hood for simplicity and understandable.

Leave a Reply

Your email address will not be published. Required fields are marked *