0

I am trying to create relations, and when notifications are fetched via $user->unreadNotifications I want to control which fields are shown, and fetch the relations. I cannot figure out where to do this.

I did the following:

  1. php artisan notifications:table
  2. php artisan make:migration add_relations_to_notifications_table
  3. In this new migration I added requester_id.

    $table->integer('requester_id')->unsigned()->nullable();
    $table->foreign('requester_id')->references('id')->on('users')->onDelete('cascade');
    
  4. php migrate

  5. php artisan make:notification AnInviteWasRequested

Then in AnInviteWasRequested I removed the toArray and replaced it with toDatabase:

public function toDatabase($notifiable)
{
    return [
        'requester_id' => Auth::guard('api')->user()->id
    ];
}

However this does not set the requester_id field, it just put json into the data column that looks like this: {"requester_id":1}.

Is there anyway to get this to update the requester_id field instead of updating data?

And also is it possible somewhere, like a Model file (not in vendor dir) to control which fields are displayed when $user->unreadNotifications is done?

Blagoh
  • 1,225
  • 1
  • 14
  • 29
  • 1
    should not be any problem if you change migration – Sohel0415 Jan 15 '18 at 09:22
  • 2
    Yea. You shouldn't do any changes on any files inside `vendor` directory. I suggest to generate new migration file for adding the relation. – Dharma Saputra Jan 15 '18 at 09:23
  • Thank you @Sohel0415 and @ DharmaSuptra - I'll create a new migration. where may I add the relations though? Is there a Notify model that I can edit? – Blagoh Jan 15 '18 at 09:40
  • @DharmaSaputra I updated my post so it is more clear. Thanks much if you can help. – Blagoh Jan 15 '18 at 17:54

1 Answers1

0

Actually to define which field to show/save, and then you need it to display, you only need to modify the toDatabase method. Example:

public function toDatabase($notifiable)
{
    $user = Auth::guard('api')->user();

    return [
        'requester_id' => $user->id,
        'requester_name' => $user->name,
        // and more data that you need to show
    ];
}

So for relational data or any other data, just define it inside this method. Hope it helps. :)

Dharma Saputra
  • 1,524
  • 12
  • 17
  • Thanks @Dharma, however this is hard coded into data json. If hte user changes their name for instance I wont get that updated. Do you have any ideas no how to get a relation live, like with other models? – Blagoh Jan 16 '18 at 01:13
  • 1
    Maybe you could try this one https://stackoverflow.com/questions/43646085/laravel-5-4-5-3-customize-or-extend-notifications-database-model#answer-43658694. It's creating new Notification Channel, but basicly its extended from DatabaseChannel. – Dharma Saputra Jan 17 '18 at 06:06