Laravel Policy and Show Method with View Method logical Problem

Viewed 43

I am using Policys and want to be sure that I am prevent data to be shown of other users. In every Table I have the column 'user_id' and check if the current logged in user with his id the same with the data and his user_id. In this specific case I have a table of Objects and Objektverwaltung where the objekt_id is given as foreign key.

I want to use my policy to be sure that just the data for the given object was shown in objektverwaltung where the foreign key 'objekt_id' is given.

ObjektVerwaltung Controller with the show method:

public function show($objektvwId) {

        $objektId = ObjektVerwaltung::with('Objekt')->find($objektvwId);

        
        
        $this->authorize('view', $objektId);
        $objekte = ObjektVerwaltung::where('objekt_id',$objektvwId)->get();
  
        
        
     
        return view('objekte.verwaltung', compact('objekte'));
    }

Policy:

  public function view(User $user, ObjektVerwaltung $objektVerwaltung)
    {
        
        return $objektVerwaltung->user_id === $user->id;
    }

Models:

class ObjektVerwaltung extends Model
{
    use HasFactory;

    protected $table = 'objekte_verwaltungens';

    protected $fillable = ['user_id','objekt_id','key', 'value'];

    public function Objekt() {
        return $this->belongsTo(Objekt::class);
    }
}

class Objekt extends Model
{

    use HasFactory;

    protected $table = 'objekts';

    protected $fillable = ['name','strasse', 'hausnummer', 'plz', 'ort', 'user_id'];


    public function Mieter() {
        return $this->hasMany(Mieter::class);
    }

    public function Company() {
        return $this->belongTo(Company::class);
    }

    public function Objektverwaltung() {
        return $this->hasMany(ObjektVerwaltung::class);
    }


}

I learned that I can easily use find() as method for the Models to validate data. But in this specific case I have to check for the objekt_id (foreign key in objektverwaltung) and not for the ID and because of that I cant use find(). But if I use where or another method I cant use my policy and always getting unauthorized.

I tried to use the with method on the model but maybe there is a better way to my problem. I strongly believe.

Thanks!

This could be solution, but I am getting always "Unauthorized" and do not get to the policy: $objekt= ObjektVerwaltung::where('objekt_id', $objektId)->get(); $this->authorize('view', $objekt);

0 Answers
Related