L
L
Luigi2021-08-03 17:31:09
Laravel
Luigi, 2021-08-03 17:31:09

How to restrict user access to a record?

I am new to Laravel, I have the following task: When creating a blog entry, the administrator can select the circle of users who can view this entry in detail (get to the internal page), other users, after authorization, can see all entries, but open the entry to which they don't have access.

I have created a join table user_records

=====================
  user_records_id
  record_id
  user_id


I managed to make a selection from the linking table, but then each user sees only the records available to him, but it is necessary that he can see everything, but open only those for which he has rights. Please help, I've been sitting for an hour already, no solution comes in any way ...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter Slobodyanyuk, 2021-08-05
Wampa @Annikangl

1) In the Record model, create a recordsForShowing relation method.
2) In the RecordController controller, in the index() method, display all records.
3) In the RecordController controller, in the show() method, add a check:

public function show(App\Models\Record $record) {
    // если пользователь не авторизован или не существует в таблице user_records то выдаем ошибку "недостаточно прав"
    abort_if(!auth('web')->check() || $record->recordsForShowing()->where('user_id', auth('web')->id())->count() < 1, 403);
        
    // дальше обычным образом показываешь запись
    return view('template_name', compact('record'));
}

Then all users will be able to see the list of entries, but only selected users will be able to see the full entry.

A
Anton Anton, 2021-08-03
@Fragster

read https://laravel.com/docs/8.x/authorization#creatin... and https://laravel.com/docs/8.x/authorization#via-con... to enlightenment

S
Stalker_RED, 2021-08-03
@Stalker_RED

see everything, but open only those

if you "see" and "open" these are different actions or different methods in the model, then you do not add a rights check in one, but add it in the second.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question