Laravel notifications are saved in the database with null user_id - database

When I try to save a notification for a user, the user_id column is always NULL in the database.
I have the Notifiable trait assigned to the User model and this also happens when I use the Notification facade. It just doesn't save anything in the user_id column.
I get the user through a relationship, something like $this->buyer->user where Buyer model belongs to User. I can see that the user is retrieved properly and has the ID.
App\Models\User {#1532
#fillable: array:5 [
0 => "name"
1 => "last_name"
2 => "email"
3 => "password"
4 => "account_type"
]
#hidden: array:4 [
0 => "password"
1 => "remember_token"
2 => "two_factor_recovery_codes"
3 => "two_factor_secret"
]
#casts: array:1 [
"email_verified_at" => "datetime"
]
#appends: array:1 [
0 => "profile_photo_url"
]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:14 [
"id" => 20
"name" => "Test"
"last_name" => "User"
"email" => "test _at mail com"
"email_verified_at" => "2021-03-12 18:17:28"
"password" => ""
"two_factor_secret" => null
"two_factor_recovery_codes" => null
"remember_token" => null
"account_type" => "buyer"
"current_team_id" => null
"profile_photo_path" => null
"created_at" => "2021-03-12 18:17:22"
"updated_at" => "2021-03-12 18:17:53"
]
#original: array:14 [
"id" => 20
"name" => "Test"
"last_name" => "User"
"email" => "test _at mail com"
"email_verified_at" => "2021-03-12 18:17:28"
"password" => ""
"two_factor_secret" => null
"two_factor_recovery_codes" => null
"remember_token" => null
"account_type" => "buyer"
"current_team_id" => null
"profile_photo_path" => null
"created_at" => "2021-03-12 18:17:22"
"updated_at" => "2021-03-12 18:17:53"
]
#changes: []
#classCastCache: []
#dates: []
#dateFormat: null
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [
0 => "*"
]
#rememberTokenName: "remember_token"
#accessToken: null
}
I try to send the notification like this:
$this->buyer->user->notify(new \App\Notifications\MessageReceived(
$this->message,
'user 2')
);
The MessageReceived.php file looks like this
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class MessageReceived extends Notification
{
use Queueable;
public $message;
public $sender;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($message, $sender)
{
$this->message = $message;
$this->sender = $sender;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return [ 'broadcast', 'database' ];
}
/**
* Get the broadcastable representation of the notification.
*
* #param mixed $notifiable
* #return BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'message' => $this->message,
'sender' => $this->sender,
'link' => '/chat/'
]);
}
/**
* Get the type of the notification being broadcast.
*
* #return string
*/
public function broadcastType()
{
return 'broadcast.message';
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)->subject('New message received')->view();
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'message' => 'You have a new message from ' . $this->sender,
'link' => $this->business->id . '/chat/' . $this->channel,
'type' => 'broadcast.message'
];
}
}
When I log the database queries I get this for this operation:
array (
'query' => 'insert into `notifications` (`id`, `type`, `data`, `read_at`, `notifiable_id`, `notifiable_type`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?)',
'bindings' =>
array (
0 => '960ec22c-f121-4ef7-acca-c0e6105fd760',
1 => 'App\\Notifications\\MessageReceived',
2 => '{"message":"You have a new message from user 2","link":"/chat/","type":"broadcast.message"}',
3 => NULL,
4 => 20,
5 => 'App\\Models\\User',
6 => '2021-05-20 19:37:20',
7 => '2021-05-20 19:37:20',
),
'time' => 148.9,
),
I don't see the user_id column in this query. Is this a bug or what could I be doing wrong? I have had this issue for weeks and can't find the culprit. I am using version 8.12

The user id or notifiable id is stored at the notifiable_id column.
You can get the notifications related to the user using the relation between $user->notifications or $user->unreadNotifications().

Related

laravel- get value from json decode array

I have an array like this, after I use json_decode ($json = json_decode($items, true);), the result looks like this
array:1 [
61 => array:53 [
"id" => 2790
"name" => "ABC"
"created_at" => "2020-12-04 09:43:57.317"
"updated_at" => "2021-02-16 16:47:16.167"
"deleted_at" => null
"remark" => null
]
]
And Iwant to get the value from field name, how to do it in Laravel??
I try like this but, get error Undefined offset name
dd($array['name']);
The correct way to access the element you're trying to get to is $array[61]["name"];
$array[61] will give you:
array:53 [
"id" => 2790
"name" => "ABC"
"created_at" => "2020-12-04 09:43:57.317"
"updated_at" => "2021-02-16 16:47:16.167"
"deleted_at" => null
"remark" => null
]
Then you can use ["name"] to access the value you're after.

Get key values from a collection in Laravel

I have this collection
1 => {#27
+"id": 1
+"name": "Zel"
+"age": "43"
}
2 => {#28
+"id": 2
+"name": "Kol"
+"age": "56"
}
3 => {#29
+"id": 3
+"name": "Mil"
+"age": "32"
}
and I would like to return an array with the key values as a string like this:
[
'id',
'name',
'age',
]
Can someone help me with that, please?
use array_keys :
$keys = array_keys($collection->first());
Laravel collection has a keys() method you could simply use it like this:
$keys = $collection->keys();
$get = $keys->all();
It is all clearly written in the Laravel Documentation
EDIT
After looking at your edit, my first consideration would be that if your collection is consistent you could get the first one and subsequently get the keys from there on:
$keys = $collection->first();
$get = $keys->keys()->all();
Or simply put $collection->first()->keys()->all();
EDIT
Here is how i was able to reproduce your problem:
$collection = collect([
[
'id' => 1,
'name' => 'Zel',
'age' => 43
],
[
'id' => 2,
'name' => 'Kol',
'age' => 56
],
[
'id' => 3,
'name' => 'Mil',
'age' => 32
],
]);
$keys = collect($collection->first())->keys()->all();
Here is the Result I got:
array:3 [▼
0 => "id"
1 => "name"
2 => "age"
]
If it still returns a collection or an object based on your last comment, you could try any one of these:
$keys = $keys->toArray();
$keys = collect($keys)->toArray();

How can I turn an object into an array (Symfony)?

This is how I create my array fields:
public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$page = $this->getDoctrine()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
$fields = (array) $page;
return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
}
The output is:
array:3 [▼
"\x00App\Entity\Pages\x00id" => 3
"\x00App\Entity\Pages\x00name" => "cat"
"\x00App\Entity\Pages\x00color" => ""
]
But I actually need this result:
array:3 [▼
"id" => 3
"name" => "cat"
"color" => ""
]
According to the suggestions I made this change:
public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$page = $this->getDoctrine()->getManager()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
$fields = get_object_vars($page);
return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
}
But this outputs me an empty array.
You have two options:
1. Use Query::HYDRATE_ARRAY instead of findOneBy()
$query = $this->getDoctrine()
->getRepository(Pages:class)
->createQueryBuilder('p')
->getQuery();
$result = $query->getResult(Query::HYDRATE_ARRAY);
(stolen from this answer)
2. Use a Serializer
Use the Serializer Component or JMSSerializerBundle to serialize your entity object.

Create form of Category with SubCategories on Symfony

I have two entities : Category and SubCategory. One category have 0 or many subcategory. They are related with Many-to-One relation.
I don't imagine how i can make a form with subcategories group by category like this :
CATEGORY 1 :
- SubCategory 1
- SubCategory 2
CATEGORY 2:
- SubCategory 1
- SubCategory 2
My form actual :
class CategorieType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sous_categories', CollectionType::class, array(
'entry_type' => SousCategorie::class,
'entry_options' => array('label' => false),
))
;
}
Thanks for your help
I do that in my form, i obtein the subcategories. How to show them grouped in box by category ?
$builder
->add('sous_categories', EntityType::class, array(
'class' => 'AppBundle:Bdd\SousCategorie',
'query_builder' => function(EntityRepository $er) use ($revue) {
return $er->createQueryBuilder('sc')
->addSelect('sc')
->join('sc.Categorie', 'c')
->andWhere('c.Revue = :Revue')
->setParameter('Revue', $revue)
->orderBy('c.libelle', 'ASC')
->addOrderBy('sc.libelle', 'ASC')
;
},
'choice_label' => function($sousCategorie){
return $sousCategorie->getCategorie()->getLibelle()." - ".$sousCategorie->getLibelle();
},
'multiple' => true,
'expanded' => true,
))
;
You can use a groupBy in you repository function :
$builder
->add('sous_categories', EntityType::class, array(
'class' => 'AppBundle:Bdd\SousCategorie',
'query_builder' => function(EntityRepository $er) use ($revue) {
return $er->createQueryBuilder('sc')
->addSelect('sc')
->join('sc.Categorie', 'c')
->andWhere('c.Revue = :Revue')
->setParameter('Revue', $revue)
->orderBy('c.libelle', 'ASC')
->addOrderBy('sc.libelle', 'ASC')
->groupBy('sc.Categorie')
;
},
'choice_label' => function($sousCategorie){
return $sousCategorie->getCategorie()->getLibelle()." - ".$sousCategorie->getLibelle();
},
'multiple' => true,
'expanded' => true,
))
;

How do I update multiple records from one post that returns a collection?

I have an AngularJS form that uses ng-repeat and ng-form to populate a list of users that can be marked as here or not.
I am now trying to use AJAX to submit the updated field to Laravel.
My form request is trying to POST a collection and update one column for multiple records. Nothing seems to be happening, no errors.
I suspect there is something wrong with my method.
public function setRoster(Request $request, $id) {
$players[] = $request;
foreach ($players as $player) {
Player::where('playerId', $player->playerId)
->update(array('gamesPlayed' => $id));
}
}
Any ideas? Thanks!
Here is the JSON from the POST
Request {#39
#json: ParameterBag {#31
#parameters: array:1 [
"players" => array:22 [
0 => array:15 [
"playerId" => 1
"teamId" => "6"
"number" => "2"
"position" => "unknown"
"gamesPlayed" => ""
"tempNumbers" => ""
"firstName" => "Tom"
"lastName" => "Travis"
"dob" => "1968-10-01"
"email" => "tom#hotmail.com"
"mobile" => ""
"photo" => "headshot.jpg"
"created_at" => "-0001-11-30 00:00:00"
"updated_at" => "-0001-11-30 00:00:00"
"onIce" => true
]
and so on...
So based on feedback, I have tried this;
foreach ($request as $player) {
Player::where('playerId', $player['playerId'])->update('gamesPlayed', '=', $id);
}
Which is now returning this error;
Cannot use object of type Symfony\Component\HttpFoundation\ParameterBag as array

Resources