简体   繁体   English

在laravel中返回很多视图的值

[英]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. 我有一个非常简单的问题,它涉及如何在laravel中将值返回给许多视图,或者只是将其设为全局值,以便可以在许多视图中使用它。 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 我将进一步说明,我在消息控制器中有一个函数,可将消息从数据库渲染到名为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 在我的主页(app.blade.php)上,有一个菜单,在此菜单中,我想显示未读消息的数量,即使我知道这是不可能的,因为我的函数返回到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. 注意message.blade.php扩展了母版页。 Thanks. 谢谢。

Create View Composer and pass data through it. 创建View Composer并通过它传递数据。

Laravel 5 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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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