0

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?

Robbie
  • 642
  • 1
  • 6
  • 12
  • 2
    what is the problem with using your first query that works? if you want it to be fancier something like, Contact::ofUser(Auth::user()->id); you can take a look Laravel's Query scopes http://laravel.com/docs/eloquent#query-scopes – Darryldecode Jun 06 '14 at 05:38

2 Answers2

0

As suggested, you can use a query scope. Add this in your Contact model:

public function scopeOfUser($query, $user_id)
{
    return $query->where('user_id', '=', $user_id);
}

And then use it like this: $contacts = Contact::ofUser(Auth::user()->id)->get();.

Antoine Augusti
  • 1,598
  • 11
  • 13
0

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.

Robbie
  • 642
  • 1
  • 6
  • 12