Search code examples
laravellaravel-9

show data in dropdown list from another model for specific user in laravel 9


how are you ?

I have a CRUD for branches , and also I have CRUD for table , and there is a dropdown list to choose the branch in table CRUD , so I want to show the branches that related to user who login in table CRUD unless if he Admin .

this is my code that I tried but not work

<?php

namespace App\Traits;

trait Tenantable
{
    public static function bootTenantable()
    {
        if (!app()->runningInConsole() && $user = auth()->user()) {
            static::creating(function ($model) use ($user) {
                $model->owner_name_id = $user->id;
            });

            if (!$user->is_admin) {
                static::addGlobalScope('owner_name', function ($query) use ($user) {
                    $query->where('owner_name_id', $user->id);
                });

            }


        }
    }
}

Solution

  • I fix it by using these code in my controller

    public function create()
    {
        $user = Auth::user();
        $branch = null ;
    
         if ($user->is_admin) {
             $branch = Branch::get(['id', 'code']);
         } else {
             $branch = Branch::where('owner_name_id', $user->id)->get(['id','code']);
         }
    
        abort_if(Gate::denies('category_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');
    
        return response([
            'meta' => [
    
                'branch'       => $branch,
                
            ],
        ]);
    }