【问题标题】:preg_split() expects parameter 2 to be string, object givenpreg_split() 期望参数 2 是字符串,给定对象
【发布时间】:2020-09-24 23:46:29
【问题描述】:

我在我的用户和学生 eloquent 上使用一对多的关系。我正在使用 Laravel 的通知向用户发送邮件。

我正在尝试发送邮件,内容是那天出生的人。关系很好,我在学生表中有单独的 user_id 列,该学生创建了该用户。并且在发送邮件时,它应该只发送由经过身份验证的用户创建的人。

但是当我登录时,我得到了错误:preg_split() 期望参数 2 是字符串,给定对象

这是我按日期过滤用户的代码

$user->students()->where('birth_date','=', Carbon::today())

我如何调用 toMail 方法

$user->notify(new BirthdayReminder())(在 LoginController 中经过身份验证)

我的 toMail 方法

public function toMail($notifiable)
    {
        $user = User::findOrFail(auth()->user()->id);

        return (new MailMessage)
                    ->from('admin@site.com')
                    ->line('Hello, '.User::first()->name.'!')
                    ->line('Today is birthday of:')
                    ->line($user->students()->where('birth_date','=', Carbon::today()));
    }

这里有什么问题?

【问题讨论】:

  • 使用 Carbon::now()->format('Y-m-d') 代替 Carbon::today() ,如果 birth_date 格式是 Y-m-d
  • 没有解决问题
  • BirthdayReminder 中有什么内容以及错误来自哪里(文件名,即使它是供应商文件)?
  • BirthdayReminder 是我用make:notification 创建的通知文件,
  • 而错误来自vendor\laravel\framework\src\Illuminate\Notifications\Messages\SimpleMessage

标签: php sql laravel


【解决方案1】:

问题(可能)在line($user->students()->where('birth_date','=', Carbon::today()))

这将尝试用$user->students()->where('birth_date','=', Carbon::today()) 的结果放置一行,但这个结果是学生的集合。

如果您想获取所有名称,请执行以下操作:

line($user->students()->where('birth_date','=', Carbon::today())->pluck('name')->implode(','));

这将返回所有学生姓名的逗号分隔字符串。

您可以以任何方式操作这些结果,但重点是 line(...) 中的最终结果需要是一个字符串

【讨论】:

    【解决方案2】:

    错误可能来自最后一行:

    ->line($user->students()->where('birth_date','=', Carbon::today()))

    不确定您希望通过此实现什么。但是这一行将返回一个不是字符串的查询生成器。

    你可以试试这样的:

    $user = User::findOrFail(auth()->user()->id);
    
    $mail = (new MailMessage)
        ->from('admin@site.com')
        ->line('Hello, '.User::first()->name.'!')
        ->line('Today is birthday of:');
    
    foreach ($user->students()->where('birth_date', Carbon::today())->pluck('name') as $userName) {
        $mail = $mail->line($userName);
    }
    
    return $mail;
    

    【讨论】:

    • 我将我的两个 eloquent 与一对多相关联,并且该行应该返回 birth_date 列等于今天的记录
    • 我已经更新了我的答案。请看看这是否适合你!
    猜你喜欢
    • 2023-03-15
    • 2016-06-26
    • 2019-12-14
    • 2015-06-27
    • 1970-01-01
    • 2020-11-22
    • 2018-08-07
    • 2017-08-30
    • 2020-06-01
    相关资源
    最近更新 更多