In many Laravel applications, you need to share common data or functionality across multiple controllers. Instead of duplicating code, you can create a Base Controller that provides shared logic and data to all other controllers. This approach enhances maintainability and keeps your code DRY (Don’t Repeat Yourself).


Scenario: Shared Functionality via Base Controller

Imagine an application where multiple controllers require access to:

  • User Roles: Determine if a user has admin or moderator privileges.
  • Feature Toggles: Enable or disable features like file uploads.
  • App-Wide Configurations: Share global preferences like application mode or API limits.

We will implement these as shared properties and methods in a Base Controller.


Step 1: Create a Base Controller

  1. Generate the Base Controller:

If you don’t already have a BaseController, create one manually or via command:


   php artisan make:controller BaseController

Move the file to app/Http/Controllers and make it extend Laravel’s default Controller.

  1. Define Shared Logic and Properties:

Add shared functionality to the Base Controller. For example:


   namespace App\Http\Controllers;

   use Illuminate\Support\Facades\Auth;

   class BaseController extends Controller
   {
       protected $userRole;
       protected $featureToggles;
       protected $appConfig;

       public function __construct()
       {
           // Set the current user's role
           $this->userRole = Auth::check() ? Auth::user()->role : 'guest';

           // Define feature toggles
           $this->featureToggles = [
               'file_uploads_enabled' => true,
               'comments_enabled' => false,
           ];

           // Set app-wide configurations
           $this->appConfig = [
               'app_mode' => 'live', // Options: 'maintenance', 'live'
               'max_api_requests' => 100,
           ];
       }
   }

Step 2: Extend the Base Controller

Make other controllers extend the Base Controller to inherit its shared properties and logic.

  1. Modify a Child Controller:

For example, a DashboardController can extend BaseController to inherit its properties:


   namespace App\Http\Controllers;

   class DashboardController extends BaseController
   {
       public function index()
       {
           return view('dashboard.index', [
               'userRole' => $this->userRole,
               'featureToggles' => $this->featureToggles,
               'appConfig' => $this->appConfig,
           ]);
       }
   }
  1. Repeat for Other Controllers:

Any other controllers that require access to these shared properties can also extend BaseController:


   namespace App\Http\Controllers;

   class ProfileController extends BaseController
   {
       public function show()
       {
           return view('profile.show', [
               'userRole' => $this->userRole,
               'fileUploadsEnabled' => $this->featureToggles['file_uploads_enabled'],
           ]);
       }
   }

Step 3: Access Shared Data in Views

The shared data passed from controllers can now be accessed directly in Blade templates.

  1. Example Usage in Blade Templates:

   @if ($userRole === 'admin')
       

Welcome, Admin!

@else

Welcome, {{ $userRole }}!

@endif @if ($featureToggles['file_uploads_enabled'])

File uploads are currently enabled.

@else

File uploads are disabled.

@endif @if ($appConfig['app_mode'] === 'maintenance')

The application is under maintenance. Please check back later.

@else

The application is live.

@endif

Step 4: Add Shared Methods to the Base Controller

The Base Controller can also include methods that multiple controllers can use.

  1. Example Shared Methods:

Add reusable methods to handle common tasks:


   public function isAdmin()
   {
       return $this->userRole === 'admin';
   }

   public function canUploadFiles()
   {
       return $this->featureToggles['file_uploads_enabled'];
   }
  1. Use the Methods in Child Controllers:

Call these methods in child controllers to simplify logic:


   namespace App\Http\Controllers;

   class FileController extends BaseController
   {
       public function upload()
       {
           if (!$this->canUploadFiles()) {
               return redirect()->back()->with('error', 'File uploads are disabled.');
           }

           // Handle file upload logic here
       }
   }

Step 5: Advantages of Using a Base Controller

  • Centralized Logic: Common functionality is defined in one place, reducing code duplication.
  • Ease of Maintenance: Updates to shared logic automatically apply to all child controllers.
  • Improved Readability: Child controllers remain focused on specific actions, while shared concerns are handled in the Base Controller.

Conclusion

By creating a Base Controller in Laravel, you’ve centralized shared logic and data, making your application more maintainable and DRY. This approach is particularly useful for managing user roles, global preferences, and feature toggles across multiple controllers.