Как отобразить уведомления в Laravel? - PullRequest
0 голосов
/ 15 марта 2020

У меня странная проблема. У меня есть два класса уведомлений InterviewRequestReceived. php и SendJobSeekerResume. php. Я пытаюсь отобразить общее количество уведомлений, используя count() рядом с небольшим значком колокольчика, а затем сообщение, относящееся к соответствующему классу уведомлений. Сообщения просты, они находятся в /layouts/partials/notification.

1. интервью_request_received.blade. php

<div>
    <span class="font-weight-bold">You've been sent an Interview request!</span>
</div>

2. send_job_seeker_resume.blade. php

<div>
    <span class="font-weight-bold">You've been sent a new Job Profile!</span>
</div>

в моем административном файле У меня есть 2 роли, в зависимости от того, вошел ли пользователь как соискатель или работодатель. admin.blade. php:

<!-- Nav Item - Alerts -->
                    <li class="nav-item dropdown no-arrow mx-1">
                        <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Notifications<i class="fas fa-bell fa-fw"></i>

                            @if(Auth::user()->role_id === 1)
                                <!-- Counter - Alerts -->
                                <span class="badge badge-danger badge-counter">{{ $jobSeekerProfile->unreadNotifications->where('type', 'App\Notifications\InterviewRequestReceived')->count() > 0 ? $jobSeekerProfile->unreadNotifications->count() : '' }}</span>
                            @endif

                            @if(Auth::user()->role_id === 2)
                                <!-- Counter - Alerts -->
                                <span class="badge badge-danger badge-counter">{{ Auth::user()->unreadNotifications->where('type', 'App\Notifications\SendJobSeekerResume')->count() }}</span>
                            @endif
                        </a>
                        <!-- Dropdown - Alerts -->
                        <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="alertsDropdown">
                            <h6 class="dropdown-header">
                                Notifications
                            </h6>

                            @if(Auth::user()->role_id === 1)
                                @foreach($jobSeekerProfile->unreadNotifications as $notification)
                                    <a class="dropdown-item d-flex align-items-center" href="#">
                                        @include('layouts.partials.notification.'. Str::snake(class_basename($notification->type)))
                                    </a>
                                @endforeach
                            @endif

                            @if(Auth::user()->role_id === 2)
                                @foreach(Auth::user()->unreadNotifications as $notification)
                                    <a class="dropdown-item d-flex align-items-center" href="#">
                                        @include('layouts.partials.notification.'. Str::snake(class_basename($notification->type)))
                                    </a>
                                @endforeach
                            @endif

                            <a class="dropdown-item text-center small text-gray-500" href="#">Show All Alerts</a>
                        </div>
                    </li>

Оба элемента с role_id === 1 работают, я получаю количество и элемент с сообщением, но элементы, где role_id === 2 я получаю счет 0 и нет деталь с сообщением, это очень странно. Конечно, я просматриваю и тестирую с двумя учетными записями, где для role_id установлено значение 1 или для role_id установлено значение 2.

Вот снимок экрана с моей таблицей уведомлений: enter image description here Когда Я вхожу в систему с user_id 12 (также для role_id установлено значение 2), на нем должны отображаться все уведомления, для которых notifiable_id установлено в 12.

I d ie, и выгрузил две мои модели, чтобы увидеть, являются ли уведомления там, модели EmployeeProfile и jobSeekerProfile, как это, и я вижу, что в моей модели EmployeeProfile нет никаких уведомлений, это просто пустой массив. Ниже приведены скриншоты.

dd($employerProfile->notifications);

enter image description here

dd($jobSeekerProfile->notifications);

enter image description here

EmployerProfile. php модель:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class EmployerProfile extends Model
{
    use Notifiable;

    protected $fillable = [

        'user_id',
        'company_name',
        'company_phone',
        'immediate_contact',
        'email',
        'company_address',
        'number_of_employees'

    ];

    public function user(){

        return $this->belongsTo('App\User');

    }

}

JobSeekerProfile. php модель:

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class JobSeekerProfile extends Model
{
    use Notifiable;

    protected $fillable = [

        'user_id',
        'photo_id',
        'resume_id',
        'video_one_id',
        'video_two_id',
        'video_three_id',
        'first_name',
        'last_name',
        'email',
        'date_of_birth',
        'full_or_part_time',
        'experience',
        'additional_skills',
        'file'

    ];

    public function user(){

        return $this->belongsTo('App\User');

    }

    public function resume(){

        return $this->belongsTo('App\Resume');

    }

    public function video(){

        return $this->belongsTo('App\Video');

    }

}

Кто-нибудь может помочь?

1 Ответ

0 голосов
/ 15 марта 2020

Вы получаете уведомления от неправильной модели.

В соответствии с вашим кодом и структурой базы данных, предположите, что идентификатор пользователя для входа равен 3, employer_profile_user_id равен 12

$user->unreadNotifications получить записи от notifications таблица, где notifiable_type равно App\User, а notifiable_id равно 3;

$user->employerProfile->unreadNotifications получить записи из таблицы notifications, где notifiable_type равно App\EmployerProfile и notifiable_id равно 12;

так что попробуйте это для счета

@if(Auth::user()->role_id === 2)
      <!-- Counter - Alerts -->
      <span class="badge badge-danger badge-counter">{{ Auth::user()->employerProfile->unreadNotifications->where('type', 'App\Notifications\SendJobSeekerResume')->count() }}</span>
@endif

и это для детализации

@if(Auth::user()->role_id === 2)
       @foreach(Auth::user()->employerProfile->unreadNotifications as $notification)
       <a class="dropdown-item d-flex align-items-center" href="#">
            @include('layouts.partials.notification.'. Str::snake(class_basename($notification->type)))
                                    </a>
       @endforeach
@endif
...