Search code examples
phpauthenticationlaravelmulti-userdatabase-security

Laravel 4 - User should access only his data in a multi-user database


I hope I described the subject properly. I'm creating a contact management application where each user will have his own contacts within the same contact table. Users must not be able to see each other's contacts.

I started by doing this but there must be a better way:

$contact = Contact::where('user_id', Auth::user()->id)->find($id);

The problem with the line above is that I would like to write it this way:

$contact = Contact::find($id)

Is there a way to have the where clause loaded somehow like filters maybe so that all searches have to match the Auth::user()->id?


Solution

  • I found the answer I was looking for on laracasts.com. (video: Repositories Simplified)

    I solved the problem by creating repositories. For example in my ContactController:

    $contact = Contact::where('user_id', Auth::user()->id)->find($id);
    

    is now

    $contact = $this->contact->getAll();
    

    The DbRepository file has:

    public function getAll() {
        return $this->model->where('user_id', Auth::user()->id)->get();
    }
    

    There's a lot more to it and you'll need to view the video to set it up. It's a lot more work to set up but it's a lot cleaner and the DbRepository can be used by all my controllers since every table will have a user_id field.