Last active
July 2, 2017 22:04
-
-
Save loburets/ff5739cb5c67a0c9cb09bb7560f113e5 to your computer and use it in GitHub Desktop.
laravel titles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\ViewComposers; | |
use Illuminate\View\View; | |
use App\Http\Requests; | |
class TitleComposer | |
{ | |
/** | |
* Array of controllers' names with empty title in view | |
* like as 'UserController' | |
* @var array | |
*/ | |
private $exceptControllers = [ | |
'AuthController', | |
'PasswordController' | |
]; | |
/** | |
* Array of actions' names with empty title in view | |
* like as 'UserController@index' | |
* @var array | |
*/ | |
private $exceptActions = []; | |
/** | |
* Bind 'title' to the view if it doesn't exist | |
* | |
* @param View $view | |
* @return void | |
*/ | |
public function compose(View $view) { | |
if ($view->offsetExists('title')) { | |
return; | |
} | |
$title = $this->getTitle($view); | |
$view->with('title', $title); | |
} | |
/** | |
* Return title text | |
* @param Illuminate\View\View $view | |
* @return string Text for the title or empty sting | |
*/ | |
private function getTitle($view) { | |
$actionArray = app('request')->route()->getAction(); | |
$controllerAndMethod = class_basename($actionArray['controller']); | |
list($controller, $action) = explode('@', $controllerAndMethod); | |
$entity = str_replace('Controller', '', $controller); | |
if (in_array($controller, $this->exceptControllers)) { | |
return ''; | |
} | |
if (in_array($controllerAndMethod, $this->exceptActions)) { | |
return ''; | |
} | |
if ($action == 'index') { | |
return str_plural($entity); | |
} | |
if ($action == 'show' && $view->offsetExists(strtolower($entity))) { | |
if ($view->offsetGet(strtolower($entity))->name != null) { | |
return $view->offsetGet(strtolower($entity))->name; | |
} | |
return ''; | |
} | |
return ucfirst($action) . ' ' .strtolower($entity); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment