Latest

Tuesday, July 11, 2017

Best place to write permission code in Laravel

Asked by: Naseeha Sahla


Where is the best place to check some condition before doing an database updation in Laravel.

During form submission, I am using form validation class for handling those request validation.

I have tables users, awards, award_user

Here when I am assigning user to an award, in some cases, one award can be assigned by maximum one user, I have to check whether already user assigned or not in when trying to assign user to award,

I written code in my controller and throwing 403 exception as follows

    //get award
    $award = Award::with('type')->findOrFail($id);
    //get award assigned members by department
    $userCount = AwardUser::join('users', 'users.id', 'award_user.user_id')
            ->where('award_id', $id)
            ->where('users.department_id', $departmentId)
            ->count();
    //not allowed to assign more than one if max person > 0
    if ($award->type->max_person > 0 && $userCount > 0) {
        abort(403, 'No more user allowed to assign!');
    }
    $award->members()->attach($userId, ['created_by' => Auth::user()->id]);
}

Is it good method or should I follow any other methods.



Source

No comments:

Post a Comment

Adbox