Support the ongoing development of Laravel.io →
IOC Architecture

Hi folks,

I'm trying to create (kind of) a base controller for some controllers. There are different controllers which should inherit from this base controller - the base controllers should provide some data for the child.

Currently I've a ProjectController which should inherit from the ProjectBaseController.

My Route: `Route::get('project/{slug}', 'ProjectController@showDetails');

Based on the slug I get the db data. But how to pass this slug to the parent controller (ProjectBaseController), without calling the parents constructor every time?

The ProjectBaseController will have methods like (pseudo names) userIsAllowedToSeeThis, different members (projectname,...), etc.. So when I'm calling any controller which inherits from the ProjectBaseController, a specific project (based on the slug, id, whatever) should be selected and be provided.

I'm thinking of something like this:

// File ProjectBaseController.php
class ProjectBaseController {
	
	protected $projectID;
	protected $projectName;
	protected $projectCreatedAt;

	public function __construct() {
		/* ??? */
	}

}

// File ProjectController.php
class ProjectController extends ProjectBaseController {
	
	public function showDetails() {
		return $this->projectID;
	}

}

class ProjectIssuesController extends ProjectBaseController {
	
	public function foo() {
		return $this->projectName;
	}

}

// Route
Route::get('/project/{slug}', 'ProjectController@showDetails');
Route::get('/project/{slug}/issue/{id}', 'ProjectIssueController@foo');

Oh, and I don't want to call the parents constructor everytime. Cause I'll need project data for every project which inherits from the base controller.

Thanks

Last updated 3 years ago.
0

If the child classes do not implement their own constructor the parent constructor will still be called.
You only need to manually call the parent constructor if the child class needs its own constructor.

Last updated 3 years ago.
0

Ok, I found a workaround for my problem... But there's another problem:

Isn't it possible to Redirect in parent classes? Tried to do:

class ProjectBaseController {
	
	public function __construct() {
		if(true) {
			return Redirect::to('somewhere');
		}
	}

}

class ProjectController extends ProjectBaseController {
	
	public function showSomething() {
		dd('foo'); // should never been displayed, since parent class redirects us
	}

}

But the redirect isn't working :(

Last updated 3 years ago.
0

Using a filter in the parent class solved my problem.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

nehalist nehalist Joined 24 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.