Support the ongoing development of Laravel.io →
Configuration Authentication Security
Last updated 2 years ago.
0

Your first query would actually have to be written like this:

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

To solve your problem, you can use query scopes, like this:

class Contact extends Eloquent {

    public function scopeGetById($query, $id)
    {
        return $query->where('user_id', Auth::user()->id)->where('id', $id);
    }

}

You can then use it like this:

$contact = Contact::getById($id)->first();

Laravel 4.2 also introduced global scopes in case you always need to check for the currently logged in user. This feature is still undocumented, but you can have a look at the soft deleting trait and the corresponding scope to see how it's done.

Last updated 2 years ago.
0

another possibility

<?php

abstract class AbstractModel extends \Illuminate\Database\Eloquent\Model
{
    public function newQuery()
    {
        $builder = $this->newEloquentBuilder(
            $this->newBaseQueryBuilder()
        );

        $builder->setModel($this)->with($this->with);

        if ($user = \Illuminate\Support\Facades\Auth::user()) {
            $builder->where('user_id', '=', $user->id);
        }

        return $this->applyGlobalScopes($builder);
    }

}

and then use it as

<?php

class MyModel extends AbstractModel {}
Last updated 2 years ago.
0

shabushabu said:

Your first query would actually have to be written like this:

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

This is because $contact = Contact::where('user_id', Auth::user()->id)->find($id); will search in ALL contacts, not only in the contacts you filtered with user_id.

Its the same as $contact = Contact::where('user_id', Auth::user()->id)->first()->first(); This will return the first contact from DB, ignoring the where part and the 1st first().

Have been thinking about it, and still find this a very weird logic. Is it just me, or others also have this feeling?

I have asked it before, but only received an advantage of it. Link

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

rturcotte rturcotte Joined 5 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.