the validate on a folder repository

Viewed 186

I am learning Laravel and I am stuck, in fact I have a folder Repositories with a file named StudentRepository.

In my Controller I have this:

public function index(Request $request)
{
   $students = $this->students->getAll();
   return view('admin.students.index', compact('students'));
}

And in my StudentRepository I have this:

public function getAll()
{
   return Student::oldest()->paginate(5);
}

No problem so far...

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

In my file StudentRepository I should put this code below:

if ($req->has('search') && !empty($req->search)) {

        $validated = $req->validate([
        'search' => 'alpha', 
        ]);

        $students = Student::where('name', 'LIKE', '%' . $validated['search'] . '%')->orderBy('name', 'ASC')->paginate(5);
        $students->appends($req->only('search'));
        return view('admin.students.index', compact('students'));
}

On my function getAll() of my folder StudentRepository

public function getAll()
{   
        return Auteur::orderBy('name', 'ASC')->paginate(5);
}

I really don't understand the syntax to follow?

1 Answers

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 function
public 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);
}
Related