Search code examples
laravelrouteslaravel-7

Laravel 7: How can I restrict URL by user?


I'm a newbie who is learning Laravel 7. I have developed a small web application with Laravel 7. But today I noticed one problem. That all the URLs are global, means all users can access all the URLs of my website. Suppose User A created data and it shows in a table where the edit and delete buttons exist with every row. The edit URL is like: localhost/records/edit/5. The problem is, that other logged-in users can access this edit page also. Like this, all the URLs are accessible by any logged-in users which is very bad. I hope you understand what I'm saying. I have almost 250+ web routes. Is there any easy way to restrict the routes? User can access their own data only. How can I do that? Thanks


Solution

  • You'll have to register policies and ensure users cannot access parts of the website without the correct authorization.

    See the docs on how to write policies and implement them.

    Sample code:

    Policy:

    class RecordPolicy 
    {
        public function delete(User $user, Record $record)
        {
            return $user->id === $record->user_id;
        }
    }
    

    Controller

    class RecordController
    {
        public function destroy(Record $record)
        {
            // Authorize the delete action before actually deleting the record
            $this->authorize('delete', $record);
    
            $record->delete();
        }
    }
    

    Records index

    @foreach($records as $record)
        <div> 
            {{ $record->name }}
    
            {{-- Only show delete button if the authorized user can actually delete the record --}}
            @can('delete', $record)
                <form action="{{ route('records.destroy', compact('record') }}" method="POST">
                    @csrf
                    @method('DELETE')
                    <button type="submit">Delete record</button>
                </form>
            @endcan
        </div>
    @endforeach