skip to Main Content

I’m currently working on a project in FilamnentPHP v3 and I am trying to figure out how to automatically pass the current user_id to my database-entity.

I thought of creating a hidden input-field and setting the default value of the field to the current user_id. But it seems like Filament ignore the hidden() TextInput and inserts null or does simply nothing.

My wrong solution

TextInput::make('user_id')
        ->label(__('messages.created_by'))
        ->required()
        ->default(
              Filament::auth()->id()
        )->readOnly()
            ->hidden()

So is there any way to pass values automatically to the database after the form-submit in Filament v3.

I also tried to look through the dilament-docu but I hab no real luck finding something that helps me to solve my problem

2

Answers


  1. you can try creating an observer for the model.

    class PostObserver
    {
      public function creating(Post $post)
      {
        if (!isset($post->user_id) && auth()->check()) {
          $post->user_id = auth()->id();
        }
      }
    }
    
    Login or Signup to reply.
  2. Also you can use this way.
    for example,if you want to insert the auth user id to blog table (created_by) so you can track who created this blog.
    you can use model event in event service provider:
    like this. and it will work.

       /**
         * Register any events for your application.
         */
        public function boot(): void
        {
            //
            Blog::creating(function($blog){
                $blog->created_by = auth()->id();
                });
    
                Blog::updating(function($blog){
                    $blog->updated_by = auth()->id();
                    });
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search