Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in laravel controller

I want the $year variable to be available in all functions of my PagesController. I tried this code but I didn't succeed.

class PagesController extends Controller
{
    public function __construct()
    {
        $dt = Carbon::parse();
        $year = $dt->year;
    }

    public function index()
    {
        return view('pages.index');
    }

    public function about()
    {
        return view('pages.about', compact('year'));
    }

    public function create()
    {
        return view('pages.create', compact('year'));
    }
}
like image 648
Nixxx27 Avatar asked Oct 05 '15 06:10

Nixxx27


People also ask

What does controller do in laravel?

A Controller is that which controls the behavior of a request. It handles the requests coming from the Routes. In Laravel, a controller is in the 'app/Http/Controllers' directory. All the controllers, that are to be created, should be in this directory.

What is __ construct in laravel?

function __construct() is a PHP magic function. It is a simple constructor function which is called when we create an object of that Class. It is used in laravel because laravel is a framework of PHP.


1 Answers

1. Option: Use the AppServiceProvider

In this case $year is available to ALL views!

<?php

namespace App\Providers;

use Carbon;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->share('year', Carbon::parse()->year);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

2. Option: Use a View Composer

In this case, the variable is only available to the views where you need it.

Don't forget to add the newly created provider to config/app.php!

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using Closure based composers...
        view()->composer('pages.*', function ($view) {
            $view->with('year', Carbon::parse()->year);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

3. Use Blades @inject-method

Within the views that need the year you could inject a Carbon instance like this:

@inject('carbon', 'Carbon\Carbon')

{{ $carbon->parse()->year }}
like image 58
Tim Avatar answered Sep 20 '22 09:09

Tim