So I am attempting to create a basic CMS in Laravel as a sort of pet project. I am coming from a wordpress background, and so I tend to think in terms of post types. Because of this, I tend to think of Models as sort of post types. In my base CMS I have a model for pages, articles, categories, tags, and various other things. Some models I don't want in the dashboard nav, and some I do, so inside the Models.php file I added a variable called $in_dash, with a function to return this variable.
protected $in_dash;
protected $dash_labels;
public function get_dash() {
return $this->in_dash;
}
public function get_labels() {
return $this->dash_labels;
}
Then inside my newly created models I have a __construct function that generates their ability to be in the dash and labels:
public function __construct() {
$this->in_dash = true;
$this->dash_labels = array(
'label' => 'Articles',
'slug' => 'articles',
'add' => 'Add New',
'view' => 'View All'
);
}
To get this data into my dashboard, I pieced together this function in a service provider that passes all the 'active' models into a nav view in the dashboard. It scans my models directory and returns any model found. Then creates a new instance and runs get_dash() and then ger_labels() if that is true. An array of dash labels is passed into the view. I have another function in there to check a $type variable that doesn't really apply to my thread. It just makes sure any route variable used in dash matches a model slug.
public function boot()
{
view()->composer('dashboard.partials.nav', function($view) {
$dash_items = [];
$files = scandir(app_path() . '\Models');
$namespace = 'App';
foreach($files as $file) {
//skip current and parent folder entries and non-php files
if ($file == '.' || $file == '..') continue;
$file = str_replace('.php', '', $file);
$model = '\\' . $namespace . '\\Models\\' . $file;
$model = new $model();
if ($model->get_dash()) {
if ($model->get_labels()) {
$dash_items[] = $model->get_labels();
}
else {
$dash_items[] = $file;
}
}
}
if ($view->type) {
$pass = false;
foreach ($dash_items as $item) {
if (is_array($item)) {
if ($view->type == $item['slug']) {
$pass = true;
}
}
else {
if ($view->type == $item) {
$pass = true;
}
}
}
if ($pass == false) {
dd('false');
}
}
$view->with('nav_items', $dash_items);
});
}
I guess I don't have any questions. This just feels a little... strange to me. I am fairly new to PHP dev and very new to Laravel, so if there is a better way to do this, I'd love to know. I know I can hard code my models into my dashboard, but part of the CMS is the ability to create new post type models inside the dashboard, so I need a programmatic way to display them.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community