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

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!

图片转代码服务由CSDN问答提供 功能建议

Heey伙计们! 我使用Laravel 5.4,WAMP for localhost。 我正在努力解决这个问题,在我的 header.blade.php 文件中调用 Controller @ methodName ,因为我想在我的header.blade.php文件中显示所有通知 对于用户。 通常我在不同页面的路线的帮助下获得所有需要的数据。 但是对于这种情况,我需要不使用路由来打电话。 这是我的 NotificationController 的代码:

 类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]; 
} 
} 
 <  / code>  
 
 

我应该在头文件中收到所有这些数据。 我用过: {{App :: make(“NotificationController”) - &gt; getNotification()}} {{NotificationController :: getNotification()}} 但是 它说 Class NotificationController不存在。 请注意!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)

相关推荐 更多相似问题