doushi4956 2017-02-04 18:29
浏览 155
已采纳

Laravel,从刀片模板文件调用控制器方法

Heey guys! I use Laravel 5.4, WAMP for localhost. I am struggling with the problem to call a Controller@methodName within my header.blade.php file, because I want to show in my header.blade.php file all notifications for the User. Normally I was getting all needed data with the help of routes in different pages. But for this case I need to call without using routes. Here is my code for my NotificationController:

class NotificationController extends Controller
{   
  public function getNotification(){
    $notifications = Notification::where('user_id',Auth::user()->id)->get();
    $unread=0;

    foreach($notifications as $notify){
        if($notify->seen==0)$unread++;
    }

    return ['notifications'=>$notifications, 'unread'=>$unread];
  }
}

And I should receive all these data in my header file. I have used: {{App::make("NotificationController")->getNotification()}} and {{NotificationController::getNotification() }} But it says Class NotificationController does not exist. Please heelp!

  • 写回答

2条回答 默认 最新

  • dscc90150010 2017-02-04 18:59
    关注

    Instead of calling the controller method to get notifications, you can make a relationship method in your User model to retrieve all the notifications that belongs to the user and can use Auth::user()->notifications. For example:

    // In User Model
    public function notifications()
    {
        // Import Notification Model at the top, i.e:
        // use App\Notification;
        return $this->hasMany(Notification::class)
    }
    

    In your view you can now use something like this:

    @foreach(auth()->user()->notifications as $notification)
        // ...
    @endforeach
    

    Regarding your current problem, you need to use fully qualified namespace to make the controller instance, for example:

    app(App\Http\Controllers\NotificationController::class)->getNotification()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态