How to display notifications in Laravel? - php

I'm having a weird issue.
I have two notification classes InterviewRequestReceived.php and SendJobSeekerResume.php.
I'm trying to display the total number of notifications using count() next to a little bell icon and then a message related to the respective notification class. The messages are simple, they are located in /layouts/partials/notification.
1. interview_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>
in my admin file I have 2 roles, depending on if the user is logged in as a jobseeker or employer.
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>
Both items with role_id === 1 are working, I get the count and the item with the message,
but the items where role_id === 2 I get count 0 and no item with message, it is very strange. Of course I'm viewing and testing with 2 accounts where I either have role_id set to 1 or role_id set to 2.
Here is a screenshot of my Notifications Table:
When I login with the user_id 12 (also role_id is set to 2) it should display all of the notifications where notifiable_id is set to 12.
I die and dumped my two models to see if the notifications are there,
employerProfile and jobSeekerProfile models like this, and I can see that there are no notifications in my employerProfile model, it is just an empty array. Below are screenshots.
dd($employerProfile->notifications);
dd($jobSeekerProfile->notifications);
EmployerProfile.php model:
<?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 model:
<?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');
}
}
Can anyone help?

You are getting notifications from wrong Model.
According to your code and database structure,
assume login user id is 3,employer_profile_user_id is 12
$user->unreadNotifications get records from notifications table where notifiable_type is App\User and notifiable_id is 3;
$user->employerProfile->unreadNotifications get records from notifications table where notifiable_type is App\EmployerProfile and notifiable_id is 12;
so try this for count
#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
and this for detail
#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

Related

How to show only one data in blade that coming from collection in Laravel?

im new at Laravel, so i have following problem:
I have db with issue table, that contains 15 names of diseases with it's description. This is my model
class Issue extends Model
{
use HasFactory;
use SoftDeletes;
protected $guarded = false;
public function gender() {
return $this->belongsTo(BodyPart::class);
}
}
And here's controller:
use App\Http\Controllers\Controller;
use App\Models\Issue;
class IndexController extends Controller
{
public function __invoke()
{
$eye_issues = Issue::all();
return view('app.issues.man.eyes.index', compact('eye_issues'));
}
}
And finally below my blade file:
<main>
<section id="schedule" class="section-with-bg">
<ul class="nav nav-tabs" role="tablist" data-aos="fade-up" data-aos-delay="100">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<li class="nav-item">
<a class="nav-link" href="#issue-{{ $issue->id }}" role="tab"
data-bs-toggle="tab">{{ $issue->issue }}</a>
</li>
#endif
#endforeach
</ul>
<div class="tab-content row justify-content-center" data-aos="fade-up" data-aos-delay="200">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<div role="tabpanel" class="col-lg-9 tab-pane fade show active" id="issue-{{ $issue->id }}">
<div class="row schedule-item justify-content-center">
<div class="col-md-10" style=text-align:center>
<h4>{{ $issue->description }}</h4>
Test yourself
</div>
</div>
</div>
#endif
#endforeach
</div>
</div>
</section>
</main>
So problem is, after loading the page, navigation tabs should show all disease names (as it does) and the description section must be empty and show according description of disease that selected from nav-tabs and change description if disease is changed from nav-tabs. But after loading page, in the description section, there are all disease description, even nav-tabs selected to none onload. Only after selecting all diseases from nav-tabs, page works properly.
P.S I use MySQL if case u wanted to know. i tried to use all JS and CSS hide and show functions and other methods from internet, but no one works, and i guess it depends only on laravel it self. if you dont understand what i mean, comment it, i'll leave link for demo video of the issue

i created notification function and getting this error "Undefined index: user" how to solve it?

im creating notification function,and when the user replied to a post it should send notification to the owner of the post. But there was an error showing
Undefined index: question. may i know how to solve it.
app.blade
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria- expanded="false">
<span class="glyphicon glyphicon-globe"> </span> notification <span
class="badge">{{count(auth()->user()->unreadNotifications)}}</span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
#foreach(auth()->user()->unreadNotifications as $notification)
#include('layouts.partials.notification.'.snake_case(class_basename($notification->type)))
#endforeach
</li>
</ul>
model
class RepliedToPost extends Notification
{
use Queueable;
protected $postqs;
public function __construct($postqs)
{
$this->postqs=$postqs;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'postqs'=>$this->postqs,
'user'=>$notifiable
];
}
}
notification blade file
{{$notification->data['user']['name']}} commmented on
{{$notification>data['postqs']['question']}}
"question" is not present in data['postqs'] array

Laravel - Getting all records not just the first and putting together?

I have tried asking this question to everyone but nobody can see why I am trying to do it or why its not working but I will try my best to explain it properly this time.
I have a simple government page on my website that shows 3 panels in bootstrap with Higher Government, Senior Ministers and Junior Ministers. Inside each of them panels it shows a list of accounts assigned to that government rank.
Here is my government.blade.php:
#include('frontend.header')
<div class="col-md-12" style="padding-bottom:24px;">
<ul class="nav navtab nav-tabs" id="myTab" style="border-bottom:none;border-radius:1px;">
<li style="padding-right:13px;" class="active"><a style="" data-target="#higher_government_team" data-toggle="tab"><i class="fa fa-diamond" aria-hidden="true"></i> The Monarch/PM</a></li>
<li style="padding-right:13px;"><a style="" data-target="#senior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Seniors</a></li>
<li style="padding-right:13px;"><a style="" data-target="#junior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Juniors</a></li>
</ul>
</div>
<div class="col-md-8">
<div class="tab-content">
<div class="tab-pane active" id="higher_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
higher gov here
</div>
</div>
</div>
<div class="tab-pane" id="senior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
senior gov here
</div>
</div>
</div>
<div class="tab-pane" id="junior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
#foreach ($juniorGovernment as $governmentMember)
{{ $governmentMember->user_id }}<br>
#endforeach
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
#include('frontend.footer')
Here is my controller for displaying the page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Now as you can see, I only select the first record where government_type matches. But the issue is I have multiple government roles with that government type and I want to get all the account stats for all records with that government type. I have looked at others suggestions and none of them work, either throwing an error or don't do what I want to do.
Now, I have modals for each Roleplay and GovernmentRoles, I have posted them both below.
GovernmentRole:
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Roleplay:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
}
}
So what I am trying to achieve is not just grabbing all the Roleplay instances for the FIRST government role record in the database it finds but putting together ALL roleplay instances for ALL records that match government_type either higher_government, senior_ministers, or junior_ministers.
If I understand what you are asking, can you not do something like fetching the stats on your loop through in blade? For example (I removed the cache, its adding complexity to the question/answer without any benefit):
// controller
$higherGovernment = GovernmentRole::where('government_type', 'higher_government')->get();
// blade
#foreach($higherGovernment as $g)
{{ $g->id }}
{{ $g->name }}
#foreach($g->stats as $stat)
{{ $stat->id }}
{{ $stat->something }}
#endforeach
#endforeach

How to make relationship between two models and update the database

It's me again but now I need some more help from you, I have some version of shopping cart and the whole idea is when I click on the product button the database to be update with the informations which user(id) has order that product(id). First I make orders table with informations(id, product_name, price), other table is users table (id, user_name) and the final table user_order table(id, user_id, order_id);
After that I make two models, one is the Orders model for the products and the second one is the User model. The relationship that I want to make is between this two models.
User model function:
public function orders(){
return $this->belongsToMany('App\Orders', 'user_order', 'user_id', 'order_id');
// return $this->belongsToMany('App\Orders');
}
Orders model function:
public function users(){
return $this->belongsToMany('App\User', 'user_order', 'order_id', 'user_id');
//return $this->belongsToMany('App\User');
}
This is the main html where I show all products with the submit button:
<div class="row">
#foreach($orders as $order)
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="http://placehold.it/320x150" alt="">
<div class="caption">
<h4 class="pull-right">{{ $order->cena }}</h4>
<h4>{{ $order->order_name }}
</h4>
<p>See more snippets like this online store item at <a target="_blank" href="http://www.bootsnipp.com">Bootsnipp - http://bootsnipp.com</a>.</p>
</div>
<div class="ratings">
<p class="pull-right">15 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
</p>
</div>
<div class="btn-group center">
Order this product!
</div>
<br>
</div>
</div>
#endforeach
Controller function:
public function makeOrder(Request $request, $id){
$user = User::where('email', $request['email'])->first();
$findorder = Orders::find($id);
//$user->orders()->detach();
$user->orders()->attach(Orders::where('id', $findorder))->first();
return redirect()->back();
}
And the route:
Route::get('/add-to-database/{id}',[
'uses' => 'AppController#makeOrder',
'as' => 'product.makeOrder'
]);
The whole idea is how to make function after submiting the button the table user_order to be updated with the id of the user, and id of the product.
Any help?
Your makeOrder() should be as:
public function makeOrder(Request $request, $id) {
$user = User::where('email', $request->get('email'))->first();
// this is to make sure that order is available in database
$order = Orders::findOrFail($id);
$user->orders()->attach($order->id);
return redirect()->back();
}

dynamic menu in laravel

Im trying to create dynamic menu. Basically,I have two tables :Category and pages.Not sure how should I do this but following is something I have tried
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="{{url('/',null)}}" class="pull-left">Consulate</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
#foreach($categories as $category )
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{$category->title}}<span class="caret"></span></a>
<ul class="dropdown-menu">
#foreach($pages as $page)
<li>{{$page->title}}</li>
#endforeach
</ul>
</li>
#endforeach
With above code, I got the same drop down menus in all the categories.I require dropdown only if the category have pages.
example1
example2
My models looks like following:
Pages model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pages extends Model
{
protected $fillable=[
'title',
'details',
'image',
'category_id',
];
//A page has a category
public function category()
{
return $this->belongsTo('App\Categories');
}
}
categories model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
protected $fillable=[
'title',
'details',
];
public function pages()
{
return $this->hasMany('App\Pages');
}
}
You could store your categories in a database table called categories (id, name, url). You could then also have another table called pages (id, name, url, category_id).
Create a Category and Page model.
Define a one-to-many relationship (one category-to-many pages).
You could then do:
#foreach( $categories as $category )
<!-- display your category html -->
#foreach( $category->pages as $page )
<!-- display your page html -->
#endforeach
#endforeach
Have a look at one-to-many relaitonships in Laravel: Eloquent: Relationships - one-to-many

Categories