1
\$\begingroup\$

I read the documentation part of Eloquent, especially scopes:

Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

And so, with using Slim, I'm retrieving an object of Employee Type and pass it to my view. I only know two ways to do this.

$app->get('/user/create', $guest(), function() use ($app) {

$employee_type = $app->option->where('type', '=', 'employee_type')->get();
$employee_type = $app->option->employeeType()->get();

$app->render('user/create.twig', [
    'employee_type' => $employee_type
]);
})->name('user.create');

First one is the normal way we do, we retrieve the objects of Option class and get the values of employee_type.

$employee_type = $app->option->where('type', '=', 'employee_type')->get();

Second is, using scopes:

$employee_type = $app->option->employeeType()->get();

And on my Option class, I have this chunk of code:

public function scopeEmployeeType($query) {
    $query->where('type', '=', 'employee_type');
}

It just does the same. Just like in the description above I gave on using scopes, it allows to easily re-use query logic in your models. Now the problem is, which is better to use? I'm starting a project and encountered this part, and I'm kind of worried I might overuse scoping.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.