Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Current User Bundle Laravel Package

dyvelop/current-user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dyvelop/current-user-bundle
    

    Ensure your Laravel project uses Symfony components (e.g., via symfony/http-foundation or symfony/security-bundle for authentication).

  2. Service Provider Registration: Add the bundle to your config/app.php under providers (if using Laravel 5.x) or create a custom service provider to bridge Symfony-style services:

    // config/app.php
    'providers' => [
        // ...
        Dyvelop\CurrentUserBundle\ServiceProvider::class,
    ],
    
  3. First Use Case: Fetch the current user in a controller or service:

    use Dyvelop\CurrentUserBundle\CurrentUserProvider;
    
    class UserController extends Controller
    {
        protected $currentUser;
    
        public function __construct(CurrentUserProvider $currentUser)
        {
            $this->currentUser = $currentUser;
        }
    
        public function show()
        {
            $user = $this->currentUser->getUser(); // Returns null if unauthenticated
            return response()->json($user);
        }
    }
    

Implementation Patterns

Dependency Injection

  • Service Binding: Bind the CurrentUserProvider to Laravel’s container in a service provider:

    public function register()
    {
        $this->app->bind('dyvelop.current_user.provider', function ($app) {
            return new CurrentUserProvider($app['auth']); // Laravel's auth manager
        });
    }
    
  • Trait-Based Injection: Use the CurrentUserAware trait in services/controllers:

    use Dyvelop\CurrentUserBundle\CurrentUserAwareTrait;
    
    class ArticleService
    {
        use CurrentUserAwareTrait;
    
        public function createArticle()
        {
            $article = new Article();
            $article->setAuthor($this->getCurrentUser()); // Auto-injected
            // ...
        }
    }
    

Doctrine Entity Integration

  • Annotation Setup: For Laravel (using Doctrine via doctrine/orm), configure the annotation driver in config/doctrine.php:

    'orm' => [
        'entity_managers' => [
            'default' => [
                'mapping_types' => [
                    'annotation' => 'Dyvelop\CurrentUserBundle\Doctrine\AnnotationDriver',
                ],
            ],
        ],
    ],
    
  • Entity Example:

    use Doctrine\ORM\Mapping as ORM;
    use Dyvelop\CurrentUserBundle\Annotation as Dyvelop;
    
    class Post
    {
        /**
         * @ORM\ManyToOne(targetEntity="User")
         * @Dyvelop\CurrentUser
         */
        private $author;
    }
    

Middleware Integration

  • Guard the Provider: Extend Laravel’s middleware to ensure the provider respects auth state:
    class CurrentUserMiddleware
    {
        public function handle($request, Closure $next)
        {
            $user = auth()->user();
            app('dyvelop.current_user.provider')->setUser($user);
            return $next($request);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Backend Mismatch:

    • The bundle assumes Symfony’s SecurityContext. In Laravel, ensure the provider uses Laravel’s Auth facade or manager:
      $user = auth()->user(); // Laravel
      // vs.
      $user = $this->security->getToken()->getUser(); // Symfony
      
  2. Doctrine Annotation Driver:

    • The annotation driver may conflict with Laravel’s default AnnotationDriver. Explicitly configure it in Doctrine’s ORM setup:
      $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(
          [__DIR__.'/../src/Entity'],
          'Dyvelop\CurrentUserBundle\Doctrine\AnnotationDriver'
      );
      
  3. Thread Safety:

    • The provider is not thread-safe. Avoid sharing it across requests (e.g., in queues) without resetting the user.

Debugging

  • Null User Issues: Verify the setUser() method is called before getUser(). Add a debug log:

    $provider = app('dyvelop.current_user.provider');
    \Log::debug('Current user:', [$provider->getUser()]);
    
  • Annotation Not Working: Clear Doctrine’s metadata cache:

    php artisan doctrine:cache:clear-metadata
    

Extension Points

  1. Custom User Provider: Extend the base provider to add logic (e.g., guest user fallback):

    class CustomUserProvider extends CurrentUserProvider
    {
        public function getUser()
        {
            $user = parent::getUser();
            return $user ?: new GuestUser(); // Fallback
        }
    }
    
  2. Event Listeners: Trigger events when the user changes (e.g., for analytics):

    $provider->addListener(function ($user) {
        event(new UserChanged($user));
    });
    
  3. Laravel-Specific Adaptations:

    • Override the trait to use Laravel’s auth() helper:
      use Illuminate\Support\Facades\Auth;
      
      class LaravelCurrentUserTrait
      {
          public function getCurrentUser()
          {
              return Auth::user();
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky