【问题标题】:Laravel, calling controller method from blade template fileLaravel,从刀片模板文件中调用控制器方法
【发布时间】:2023-03-26 06:32:02
【问题描述】:

大家好!我使用 Laravel 5.4,WAMP 作为本地主机。我正在努力解决在我的header.blade.php 文件中调用Controller@methodName 的问题,因为我想在我的 header.blade.php 文件中显示用户的所有通知。通常,我在不同页面中的路线的帮助下获取所有需要的数据。但是对于这种情况,我需要在不使用路由的情况下调用。这是我的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];
  }
}

我应该在我的头文件中收到所有这些数据。我用过:{{App::make("NotificationController")->getNotification()}}{{NotificationController::getNotification() }} 但上面写着Class NotificationController does not exist。请帮忙!

【问题讨论】:

  • 为什么不为此制定路线并到达那条路线。

标签: php controller laravel-blade laravel-5.4


【解决方案1】:

您可以在User 模型中创建一个关系方法来检索属于该用户的所有通知,并且可以使用Auth::user()->notifications,而不是调用控制器方法来获取通知。例如:

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

在您的view 中,您现在可以使用如下内容:

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

关于你当前的问题,你需要使用完全限定的命名空间来制作控制器实例,例如:

app(App\Http\Controllers\NotificationController::class)->getNotification()

【讨论】:

    【解决方案2】:

    尝试使用完整的命名空间:

    例如,App\Http\Controllers\NotificationController::getNotification

    当然,控制器的名称并不意味着您使用它们的方式。它们适用于路线。更好的解决方案是在您的用户模型中添加一个关系,如下所示:

    public function notifications()
    {
        return $this->hasMany(Notification::class)
    }
    

    然后像这样在你的视图中使用它:

    @foreach(Auth::user()->notifications as $notification)
    

    【讨论】:

    • 是的,没错。谢谢我这样做了)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2013-06-01
    • 2016-07-13
    • 1970-01-01
    • 2021-09-26
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多