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

Active Laravel Package

watson/active

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require watson/active
    

    Add to config/app.php:

    'providers' => [
        Watson\Active\ActiveServiceProvider::class,
    ],
    

    (Optional) Add facade alias if preferred:

    'aliases' => [
        'Active' => Watson\Active\Facades\Active::class,
    ],
    
  2. First Use Case: Check if the current route matches a specific route or URI:

    // In a Blade template
    <li class="{{ active('dashboard') ? 'active' : '' }}">Dashboard</li>
    
    // In a controller
    if (active('dashboard')) {
        // Perform action
    }
    
  3. Key Methods to Explore:

    • active($route): Check if current route matches $route.
    • activeRoute(): Get the current route name.
    • activeController(): Get the current controller name.
    • activeAction(): Get the current action/method name.

Implementation Patterns

Common Workflows

1. Dynamic Navigation Highlighting

Use active() in Blade templates to highlight the current menu item:

<nav>
    <a href="{{ route('dashboard') }}" class="{{ active('dashboard') ? 'active' : '' }}">Dashboard</a>
    <a href="{{ route('profile') }}" class="{{ active('profile') ? 'active' : '' }}">Profile</a>
</nav>

2. Conditional Logic in Controllers

Restrict actions or modify behavior based on the current route:

public function index()
{
    if (active('admin.dashboard')) {
        return view('admin.dashboard');
    }

    return redirect()->route('home');
}

3. Route-Based Middleware Logic

Dynamically apply middleware or logic in middleware:

public function handle($request, Closure $next)
{
    if (active('admin.*')) {
        // Custom logic for admin routes
    }

    return $next($request);
}

4. Retrieving Route/Controller/Action

Use helper methods to inspect the current route context:

$routeName = activeRoute(); // e.g., 'admin.users.index'
$controller = activeController(); // e.g., 'Admin\UsersController'
$action = activeAction(); // e.g., 'index'

5. Integration with Laravel Mix/Blade Directives

Create a custom Blade directive for reusable active state logic:

// In a service provider
Blade::directive('activeClass', function ($expression) {
    return "<?php echo \\Watson\\Active\\Active::check($expression, 'active'); ?>";
});

// In Blade
<li class="{{ activeClass('dashboard') }}">Dashboard</li>

Integration Tips

With Laravel Collective HTML

Combine with Form::open() or Link::route() for seamless integration:

{!! Form::open(['route' => 'dashboard']) !!}
<button type="submit" class="{{ active('dashboard') ? 'btn-primary' : 'btn-default' }}">
    Submit
</button>

With Tailwind CSS

Use active() with Tailwind’s arbitrary variants:

<a href="{{ route('dashboard') }}" class="[&.active]:bg-blue-500">Dashboard</a>

(Note: Requires custom JS or a Blade directive to add the active class dynamically.)

With Inertia.js

Pass active state to Vue/React components:

return Inertia::render('Dashboard', [
    'isActive' => active('dashboard'),
]);

With API Routes

Use active() to conditionally modify API responses:

return response()->json([
    'data' => $data,
    'meta' => [
        'isAdminRoute' => active('admin.*'),
    ],
]);

Gotchas and Tips

Pitfalls

1. Route Caching Conflicts

  • Issue: If you use route caching (php artisan route:cache), the active() checks may not reflect real-time changes.
  • Fix: Clear the route cache after changes:
    php artisan route:clear
    
  • Workaround: Use Route::currentRouteName() directly in critical sections.

2. Controller/Action Detection Quirks

  • Issue: activeController() and activeAction() may return unexpected results for:
    • Closure-based routes.
    • Named controllers (e.g., App\Http\Controllers\UserController@index vs. UserController@show).
  • Tip: Test edge cases like:
    Route::get('/test', [UserController::class, 'index'])->name('test');
    Route::get('/test2', fn() => view('test'))->name('test2');
    

3. Case Sensitivity

  • Issue: Route names are case-sensitive. active('dashboard') won’t match active('Dashboard').
  • Fix: Standardize route naming conventions (e.g., snake_case).

4. Facade vs. Helper Functions

  • Issue: Facade (Active::check()) and helper (active()) may behave differently in some edge cases (e.g., nested checks).
  • Tip: Stick to one style per project for consistency.

5. Performance in Loops

  • Issue: Calling active() in tight loops (e.g., rendering a large menu) can be slow.
  • Fix: Cache the result:
    $isActive = active('dashboard'); // Call once
    foreach ($menuItems as $item) {
        echo $isActive ? 'active' : '';
    }
    

Debugging Tips

1. Inspect Current Route

Dump the current route context for debugging:

dd([
    'route' => activeRoute(),
    'controller' => activeController(),
    'action' => activeAction(),
    'uri' => request()->path(),
]);

2. Check Route Registration

Ensure routes are registered as expected:

php artisan route:list

Look for typos or missing names.

3. Test with active() Directly

Use the helper in tinker to test:

php artisan tinker
>>> active('dashboard')

4. Handle Missing Routes Gracefully

active() returns false for non-matching routes, but ensure your logic accounts for:

  • Unnamed routes.
  • Dynamic route segments (e.g., user.{id}).

Extension Points

1. Custom Active Classes

Extend the package to support custom active classes:

// In a service provider
Active::extend(function ($app) {
    $app->singleton('active.class', function () {
        return 'is-current';
    });
});

// Usage
<li class="{{ active('dashboard', 'is-current') }}">Dashboard</li>

2. Add Route Groups Support

Extend active() to support route group prefixes:

// Hypothetical extension
if (active('admin.*')) { ... } // Matches all admin routes

3. Integration with Route Model Binding

Combine with route model binding for resourceful checks:

public function show(User $user)
{
    if (active('users.edit', ['user' => $user->id])) {
        // Custom logic
    }
}

4. Publish Config for Customization

Publish the package config to override defaults:

php artisan vendor:publish --provider="Watson\Active\ActiveServiceProvider"

(Note: The package may not include publishable config; check for extension hooks.)

5. Add Support for Route Parameters

Extend to match routes with parameters:

// Hypothetical usage
active('posts.show', ['post' => 1]); // Matches /posts/1

Pro Tips

1. Use in Partial Views

Create reusable partials for navigation:

@component('partials.nav-item', ['route' => 'dashboard', 'label' => 'Dashboard'])
@endcomponent
<!-- partials/nav-item.blade.php -->
<li class="{{ active($route) ? 'active' : '' }}">
    <a href="{{ route($route) }}">{{ $label }}</a>
</li>

2. Combine with Laravel Mix

Generate a JS file to handle active states dynamically:

// resources/js/active.js
document.querySelectorAll('[data-active]').forEach(el => {
    if (window.location.pathname.includes(el.dataset.active)) {
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.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed