简体   繁体   中英

return value to many views in laravel

I have a really simple question, Its about how I can return a value to many views in laravel, or just make it global so i can use it in many views. I'll explain more, I have a function in the Message Controller that render the messages from database to a view page called message.blade.php

public function index(){
  $listmsg = Message::where('idReceiver', Auth::id())->orderBy('idMess','desc')->get();

  return view('message', ['messages' => $listmsg]);
}

And on my master page ( app.blade.php ), I have a menu, in this menu I want to display the number of the unread messages, I tried this even I know it's impossible because my function return to the message.blade.php

@if(!$messages->isEmpty())
<span class="badge badge-danger badge-pill">
    {{ $messages->count() }}
</span>
@endif

Notice that the message.blade.php extends the master page. Thanks.

Create View Composer and pass data through it.

Laravel 5

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{

public function boot()
{
    // Using class based composers...
    View::composer(
        'profile', 'App\Http\ViewComposers\ProfileComposer'
    );

    // Using Closure based composers...
    View::composer('dashboard', function ($view) {
        //
    });

    // Passing multiple data to multiple views
    View::composer(['view1','view2','multipleviews.*'], function ($view) {

        $data1 = [];
        $var2 = 'string';

        $view->with(compact('data1','var2'));

    });
}
}

or you can use helper

public function boot()
{
    view()->share('key', 'value');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM