Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'));
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
389 views
Welcome To Ask or Share your Answers For Others

1 Answer

1. Option: Use the AppServiceProvider

In this case $year is available to ALL views!

<?php

namespace AppProviders;

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 AppProviders;

use IlluminateSupportServiceProvider;
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', 'CarbonCarbon')

{{ $carbon->parse()->year }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...