loburets
6/7/2016 - 8:38 AM

laravel titles

laravel titles

<?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);
    }
}