如何修复laravel中的Class 'App\Http\Controllers\Notification' not found错误?

4

我有一个控制器(Controller),它监听新的日程创建,并通过ajax将结果发送回视图(View)。在其中,我想添加一个通知(Notification),当特定日期和时间由于缺乏资源而无法完成日程时,向用户发送电子邮件。

问题是我会收到下面的错误:

Class 'App\Http\Controllers\Notification' not found in /laravel/app/Http/Controllers/DadosAgendamentoController.php on line 89

文件夹结构如下:

-app
    -Http
        -Controllers 
            DadosAgendamentoController.php
    -Notifications
        AgendamentoPendente.php

DadosAgendamentoController.php 头部代码:

namespace App\Http\Controllers;

use Input;
use Request;
use App\Servicos;
use App\Disponibilidades;
use App\Estabelecimentos;
use App\HorariosEstabelecimento;
use App\Agendamento;
use App\User;
use App\Notifications\AgendamentoPendente;

第 88 行和 89 行:

$user = User::where('id',1)->get();
Notification::send($user, new AgendamentoPendente(1));

通过我的控制器,我可以访问上面的所有类,但无法访问 AgendamentoPendente

我的目标是向管理员发送电子邮件,以便他可以向客户建议新的日期和时间,当资源在所需日期和时间不可用时。

如何解决?我可以在这个控制器中访问这个类吗?怎么做?


请显示给我们 DadosAgendamentoController.php 文件的第 89 行。 - Alexey Mezenin
我几乎可以确定你没有导入 Notification 类。只需导入命名空间即可解决问题。如果 Notification 是一个门面,只需通过 \Notification::foo() 调用即可。 - felipsmartins
@AlexeyMezenin,我已经编辑了这个问题。 - Jaqueline Passos
@felipsmartins,我看到User有一个默认配置来使用Notifications,我也尝试使用命令use Illuminate\Notifications\Notifiable;,但是没有成功。 - Jaqueline Passos
@JaquelinePassos,Alexey Mezenin的答案是正确的。尽管它没有解决你的问题,但在另一个地方/范围内存在问题。 - felipsmartins
@felipsmartins 这是因为通知与数据库相关联,只有在数据保存后才会触发吗?这是 Laravel 中通知的工作方式吗?您知道我这种情况是否有更好的方法吗?我考虑在我的数据库中创建一个布尔状态字段,如果状态设置为 false,我可以触发通知。但我仍然遇到错误,电子邮件没有被发送...搜索网络,我猜测原因是只有在我的数据库中保存模型的新数据时才会发送通知,我是对的吗? - Jaqueline Passos
6个回答

10
通知可以通过两种方式发送:使用Notifiable特征的notify方法或使用Notification门面。

https://laravel.com/docs/5.3/notifications#sending-notifications

选项1

您可以使用notify()方法:

$user->notify(new AgendamentoPendente(1));

此外,请确保User类使用Notifiable特性:
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

选项2

使用完整命名空间的门面:

\Notification::send($user, new AgendamentoPendente(1));

错误已经解决,但它并没有按预期工作... Laravel通知只有在数据库中创建模型的新数据时才会发送?这就是它的工作方式吗?如果表字段值设置为false,我能否仅发送通知? - Jaqueline Passos

5
在你的控制器中添加 use Notification; 或者,可以使用 \Notification::send($user, new AgendamentoPendente(1)); 作为替代方案。

0

在控制器的顶部添加以下内容:

use App\Notifications\AgendamentoPendente;

我之前也遇到了同样的问题,但是现在已经解决了。


0
请注意,如果您正在使用门面模式,请确保从数据库中查询用户的电子邮件字段。
$users = User::select("email")->get();
\Notification::send($users, new AgendamentoPendente(1));

0

您可以在 Lumen 8.0 中使用以下代码引入通知库:

"illuminate/notifications": "5.3.*"

将其添加到您的 composer.json 文件中,然后运行 composer update 命令以引入通知库。

您还需要在 bootstrap/app.php 文件中添加以下代码:

$app->register(Illuminate\Notifications NotificationServiceProvider::class);

这个过程对我很有效。谢谢!


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接