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

Acorn Laravel Package

roots/acorn

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require roots/acorn
    

    Follow the official installation guide to scaffold a new project or integrate into an existing WordPress project using Bedrock.

  2. First Use Case: Replace a WordPress template file (e.g., page.php) with a Blade template in resources/views/page.blade.php. Use Laravel’s Blade syntax:

    <h1>{{ $post->post_title }}</h1>
    <div>{{ $post->post_content }}</div>
    

    Register the template in app/Providers/AppServiceProvider.php:

    use Roots\Acorn\View\ViewServiceProvider;
    
    public function boot()
    {
        ViewServiceProvider::registerTemplate('page', 'page');
    }
    
  3. Key Files to Explore:

    • app/Providers/ – Service providers for Laravel integrations.
    • resources/views/ – Blade templates.
    • routes/web.php – Laravel routes (coexist with WordPress).
    • .env – Environment variables (shared between Laravel and WordPress).

Implementation Patterns

Workflows

  1. Hybrid Routing:

    • Use Laravel routes for REST APIs or custom endpoints:
      // routes/web.php
      Route::get('/api/data', function () {
          return response()->json(['data' => 'Hello from Laravel!']);
      });
      
    • WordPress routes remain unchanged for traditional page requests.
  2. Service Integration:

    • Replace WordPress plugins with Laravel packages (e.g., spatie/laravel-permission for user roles):
      composer require spatie/laravel-permission
      
      Configure in config/acorn.php:
      'providers' => [
          Spatie\Permission\PermissionServiceProvider::class,
      ],
      
  3. Blade in WordPress:

    • Override WordPress templates with Blade:
      // app/Providers/ViewServiceProvider.php
      public function boot()
      {
          ViewServiceProvider::registerTemplate('single', 'posts.single');
      }
      
    • Access WordPress globals via $post, $wp_query, etc., in Blade:
      <article>
          <h1>{{ $post->post_title }}</h1>
          <p>{{ $post->post_content }}</p>
      </article>
      
  4. Database Abstraction:

    • Use Eloquent models for WordPress data:
      // app/Models/Post.php
      namespace App\Models;
      use Illuminate\Database\Eloquent\Model;
      
      class Post extends Model
      {
          protected $table = 'wp_posts';
      }
      
    • Query with Laravel syntax:
      $posts = Post::where('post_status', 'publish')->get();
      
  5. Events and Listeners:

    • Replace WordPress hooks with Laravel events:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'eloquent.created: App\Models\Post' => [
              'App\Listeners\LogPostCreation',
          ],
      ];
      
  6. Artisan Commands:

    • Extend WP-CLI with Laravel commands:
      php artisan make:command SyncPosts
      
      Register in routes/console.php:
      $this->commands([
          \App\Console\Commands\SyncPosts::class,
      ]);
      
  7. Caching:

    • Leverage Laravel’s cache drivers (Redis, Memcached) for WordPress transients:
      Cache::put('key', 'value', $seconds);
      
  8. Validation:

    • Use Laravel’s validation in WordPress forms:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($data, [
          'email' => 'required|email',
      ]);
      

Integration Tips

  • Theme Development: Use resources/views/partials/ for reusable Blade components. Include them in WordPress templates:
    @include('partials.header')
    
  • Multisite Support: Configure config/acorn.php to isolate cache/session per site:
    'multisite' => [
        'enabled' => true,
        'cache_prefix' => 'wp_{site_id}_',
    ],
    
  • Vite Integration: Use Laravel Mix/Vite for asset compilation. Configure in vite.config.js:
    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    
    export default defineConfig({
        plugins: [
            laravel({
                input: ['resources/js/app.js'],
                refresh: true,
            }),
        ],
    });
    
    Access assets in Blade:
    <script type="module" src="{{ vite('resources/js/app.js') }}"></script>
    

Gotchas and Tips

Pitfalls

  1. Request Handling:

    • Acorn does not automatically handle all WordPress requests by default. Opt-in via config/acorn.php:
      'wordpress_request_handler' => [
          'enabled' => true,
          'priority' => 10,
      ],
      
    • Gotcha: Disabling this may break WordPress template rendering. Test thoroughly.
  2. Superglobals:

    • WordPress superglobals ($post, $wp_query) are not automatically available in Laravel contexts. Access them via:
      global $post, $wp_query;
      
      Or bind them in service providers:
      View::share('post', $post);
      
  3. Database Connections:

    • WordPress’s wp_ tables are not automatically mapped to Eloquent. Define custom tables:
      class Post extends Model
      {
          protected $table = 'wp_posts';
          public $timestamps = false; // WordPress uses `post_date` instead of `created_at`
      }
      
  4. Session Flash Data:

    • Flash data (e.g., session()->flash('success', '...')) may not persist across WordPress template requests. Use middleware to re-flash:
      // app/Http/Middleware/FlashSession.php
      public function handle($request, Closure $next)
      {
          if (session()->has('flash')) {
              foreach (session('flash') as $key => $message) {
                  session()->flash($key, $message);
              }
              session()->forget('flash');
          }
          return $next($request);
      }
      
  5. Middleware Conflicts:

    • WordPress’s WP_Rewrite and Laravel’s routing may conflict. Use Acorn’s RouteServiceProvider to merge rules:
      public function boot()
      {
          parent::boot();
          $this->mergeWordPressRules();
      }
      
  6. Asset Paths:

    • WordPress uses get_template_directory_uri(), while Laravel uses asset(). Configure aliases in config/acorn.php:
      'aliases' => [
          'asset' => function () {
              return get_template_directory_uri() . '/dist';
          },
      ],
      
  7. Queue Workers:

    • Laravel queues do not integrate directly with WordPress cron. Use a separate process or WP-Cron:
      php artisan queue:work --daemon
      
  8. Multisite Cache Isolation:

    • Without configuration, cache may bleed between sites. Enable isolation:
      'multisite' => [
          'cache_prefix' => 'wp_{site_id}_',
      ],
      

Debugging

  • Enable Laravel Logging: Configure config/logging.php to write to WordPress’s debug log:
    'channels' => [
        'single' => [
            'driver' => 'single',
            'path' => WP_CONTENT_DIR . '/debug.log',
            'level' => 'debug',
        ],
    ],
    
  • WP-CLI Debugging: Use WP_DEBUG and Acorn’s --verbose flag:
    WP_DEBUG=1 acorn about --verbose
    
  • Route Debugging: Dump routes with:
    php artisan route:list
    
    Or in Blade:
    @dd(\Illuminate\Support\Facades\Route::getRoutes()->getRoutes())
    

Extension Points

  1. Custom Providers: Extend Laravel’s service container in app/Providers/AppServiceProvider:

    public function register()
    {
        $this->app->bind('custom.service', function () {
            return new CustomService();
        });
    }
    
  2. WordPress Hooks as Events: Convert WordPress hooks to Laravel events in app/Providers/EventServiceProvider:

    add_action('wp_loaded', function () {
        event(new \App\Events\WordPressLoaded);
    });
    
  3. Custom Artisan Commands: Extend WP-CLI with:

    php artisan make:command CustomCommand
    
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.
andydefer/laravel-cluster
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views