skip to Main Content

I’m starting with laravel/filamentphp in version 10 and I want to automatically filter the table of a resource so that the current user looks only at its records that I capture.

I have the “user” model related to the “sale” model through the user id, that is, in the “sale” migration table I have:

$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();

and in the main index (table) of the “sale” resource the user ID appears in the corresponding record that was captured.

But I can’t or rather I don’t know how to make a query to filter by user and their id automatically.

I hope you can guide me and give me support.thank you

Filter resource table by registered user id or current user.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the response, I did the following place ->query() below return $table where the salesresoruce table section begins.

    public static function table(Table $table): Table {

        return $table
        ->query(function (Sales $sales) {
        return $sales->where('user_id', auth()->id());
    

    })

    Now, if you could help me... how to adapt or what to do to be able to see all the records "if the user or users have a specific ID" and if not, only look at the records that correspond to the user ID.


  2. You need to create a relationship between User and sale
    like in User Model add this.

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

    then in controller function you can get the values like

    public function userSales(){
       $user = Auth::user();
       $sales = $user->sales;
       .... remaining logic
    }
    

    If u want to retrieve data without defining relationship u can get through this

      public function userSales(){
       $user = Auth::id;
       $sales = Sale::where('user_id', $user)->get();
        .... remaining logic
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search