M
M
mrFlyer2016-07-05 17:55:56
Laravel
mrFlyer, 2016-07-05 17:55:56

How to properly pass headers from controller/template to main template (laravel5)?

Hello.
I am studying Laravel 5 and it is not clear how to implement the following correctly:
There is a class that is responsible, say, for the h1 header and the title tag.
I want to call it from any controller or blade template. Something like Titles->set("Hello!"); Inside this method, I process the data and already in the main template I do Titles->getTitle() ; Titles->getH1();
Tell me in which direction to dig in order to correctly implement such functionality. I got completely lost in providers, service controllers, facades, etc...
Thanks in advance for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2016-07-06
Hrebet @hrebet

Create a main helper class for this purpose, let's say app/Helpers/Titles.php :

<?php

namespace App\Helpers;

class Titles
{

    private $title = null;
    private $h1 = null;

    public function setTitle($title) {
        $this->title = $title;
    }

    public function getTitle() {
        return $this->title;
    }

    public function setH1($h1) {
        $this->h1 = $h1;
    }

    public function getH1() {
        return $this->h1;
    }

}

Register this singleton class in app/Providers/AppServiceProvider.php :
...
    public function boot()
    {
...
        $this->app->singleton('Titles', function($app) {
            return new \App\Helpers\Titles();
        });
...
    }
...

Access such a helper from anywhere in the controller or view as:
app()['Titles']->setTitle('Очередной интернет-магазин');
app()['Titles']->getTitle();

For a more aesthetic look, you can use a facade, create \app\Facades\Titles.php :
<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Titles extends Facade
{

    protected static function getFacadeAccessor() {
        return 'Titles';
    }

}

Next, register it in \app\config\app.php :
...
    'aliases' => [
...
        'Titles' => \App\Facades\Titles::class,
...
    ],
...

And, let's say, use in the controller, for example:
<?php

namespace App\Http\Controllers;

use Titles;

class UserController extends Controller
{

    public function signup() {
        Titles::setTitle('Добро пожаловать!');
        return view('user.signup');
    }

}

Good luck! ;-)

A
Alexander Aksentiev, 2016-07-05
@Sanasol

Main Template
I Page Template
@section('title') SomeTitle @endsection

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question