the validate on a folder repository the validate on a folder repository laravel laravel

the validate on a folder repository


Now, I would like to improve my Application with the validate system.

Do the validation in the controller directly over the request, it is the first thing you can check, so if validation fails, you will not use unnecessarily system resources.
Add the sometimes rule, that checks against a field only if that field is present.
And you can mark it as nullable if you do not want the validator to consider null values as invalid.

Controller

public function index(Request $request){    $request->validate([        'search' => 'sometimes|nullable|alpha',     ]);    // assign the value of the request field to a variable, note that the value will be null if the field doen't exist    $search = $request->search;    // pass the variable as parameter to the repository function    $students = $this->students->getAll($search);    // If you would like to determine if a value is present on the request and is not empty, you may use the filled method    if ($request->filled('search')) {        $students->appends($request->only('search'));    }    return view('admin.students.index', compact('students'));}

StudentRepository

// receives the parameter in the functionpublic function getAll($search){    // here you can use when() method to make this conditional query, note that if the value is null, the condition will not pass    return  Student::when($search, function ($query) use ($search) {                $query->where('name', 'LIKE', '%' . $search . '%');            })            ->orderby('name', 'asc')            ->paginate(5);}