Mastering Laravel Controllers: Simplifying Code with Inheritance and Shared Data

LaravelCodeCraft
3 min readSep 17, 2023

--

Introduction

Laravel, a well-known PHP framework, provides developers with powerful tools for creating online applications. In this blog post, we’ll look at how to use inheritance and shared data to simplify your Laravel controllers. This way not only improves code organisation but also allows you to pass variables to Blade views more efficiently.

Understanding the Problem

Multiple variables are frequently passed to Blade views in Laravel applications. This can result in cluttered code and poor readability. To overcome this issue, we’ll construct a base controller that manages shared data, which we’ll then extend in additional controllers for a more organized approach.

Step 1: Creating the Base Controller

Let’s start by creating a base controller that will act as the foundation for our expanded controllers. This fundamental controller offers methods for setting, getting, and checking the existence of dynamic properties as well as a $data property.

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
/**
* @var array
*/
public $data = [];

/**
* Set a dynamic property on the base controller.
*
* @param mixed $name
* @param mixed $value
*/
public function __set($name, $value)
{
$this->data[$name] = $value;
}

/**
* Get a dynamic property from the base controller.
*
* @param mixed $name
* @return mixed
*/
public function __get($name)
{
return $this->data[$name];
}

/**
* Determine if a dynamic property is set on the base controller.
*
* @param mixed $name
* @return bool
*/
public function __isset($name)
{
return isset($this->data[$name]);
}

public function __construct()
{
$this->middleware(function ($request, $next) {
// You can perform actions here that run for all controllers that extend this base controller.
return $next($request);
});
}
}

This base controller includes the following features:

  • To hold our dynamic data, we define a $data property as an array.
  • We can set dynamic properties on the controller using the __set function.
  • The __get method is used to get dynamic properties.
  • The __isset method determines whether a dynamic property exists.

Step 2: Creating an Extended Controller

Let us now make an extended controller that inherits from our base controller. We’ll call it UserController in this example.

namespace App\Http\Controllers;

class UserController extends Controller
{
public function __construct()
{
parent::__construct();
}

public function index()
{
// Set variables in the extended controller
$this->users = User::all();
$this->exams = Exam::all();

// Pass the data to the Blade view using $this->data
return view('users.index', $this->data);
}
}

In this extended controller:

  • We use extends Controller to extend the Controller class, which allows us to inherit its properties and methods.
  • We use parent::__construct() in the constructor to guarantee that any middleware configured in the base controller is also applied here.
  • Variables like $users and $exams are set in the index method. Using $this->variableName, these variables are allocated to the base controller’s $data property.
  • Finally, when we return a view in the index method, we use return view(‘users.index’, $this->data) to provide the complete $data array to the Blade view. This is a neat and tidy approach of passing several variables to the view.

Step 3: Using Data in Blade Views

Let’s look at how to leverage the shared data in Blade views now that we’ve arranged our controllers. Here’s how to get to the variables from the data property:

<!-- Users -->
@foreach($users as $user)
{{ $user->name }}
@endforeach

<!-- Exams -->
@foreach($exams as $exam)
{{ $exam->name }}
@endforeach

Conclusion

You may simplify your Laravel controllers, improve code organisation, and encourage reusability by using this method. The base controller serves as a central repository for common data and functionality, reducing application redundancy. This way is very useful when you need to send several variables to Blade views, resulting in more maintainable and efficient code.

Implement this strategy in your Laravel applications for cleaner, more organized code and increased development efficiency.

“Enjoyed this article? Stay tuned for more thought-provoking content! Follow me on Medium for the latest updates and share this post with your fellow readers to spread the knowledge.”

Follow me on Medium: LaravelCodeCraft

Thank you for reading and being part of my Medium community! :)

--

--

LaravelCodeCraft

"Exploring the Laravel universe one line of code at a time 🚀 #LaravelCodeCraft"