Ida Marie
Ida Marie

Reputation: 57

Validating user access inside of controller

I just started learning Laravel 5.7 and was wondering if there is an easier way to validate if a specific user has the rights to edit, delete or view a page.

Scenario

A user has many companies, and can view, edit and delete them. So if they try to access a company name (id) they don't belong to, they would get "access dined" or something. My problem is that i keep repeating my code over and over, and it seems very unproductive.

Example code:

public function edit($id)
{

    // Check if the company ID exists
    if(!Company::whereId($id)->first() || !Company::whereId($id)->where('user_group',Auth::user()->user_group)->first())
    {
        return abort(404);
    }

    return view('company/edit');

}

So in my example, I check if the ID of the company exists, and If the company and user_group has the same ID. However, I would need to repeat this code for the "show" method, and any other methods having the same scenario (including other controllers).

How can I make my life easier with this? What's the best practice? A example would be nice.

Upvotes: 0

Views: 40

Answers (3)

Dearwolves
Dearwolves

Reputation: 453

We did this thru a middleware. You can create an user access table on the database and make a middleware that checks it if the user has the access. then allow if the access exist on the table or redirect if not. However, this approach only works on user type level and not on a specific user.

Upvotes: 0

milo526
milo526

Reputation: 5083

There are many ways to do this, I believe the best way for your problem is the use of policies. Policies can be seen as a link between the User and the Model (company in your case). You can specify create, show, update and delete methods and specify if a user should be able to perform the specific action.

Policies shine through their general usage, you don't have to check if a user can view a specific company anywhere else in your code, just the once and Eloquent handles the rest.

Upvotes: 1

The clean way is to use Laravel Validator

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }

Upvotes: 0

Related Questions