Notify Slack send Array - laravel

im trying to send some values from a DB with Notify to Slack. Somehow every time I load my Website the only message I get is "Array" and not the data from the DB.
This is my Notifications .php
class InventoryReStock extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($reorder)
{
$this->reorder = $reorder;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['slack'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->content([$this->reorder]);
}
This is the function that Im using on my controller to get the data form the Db
public function index()
{
//shows all the products in the database in an overview
$products = Product::all()->toArray();
$reord = Product::select('Product_Name')->where('Number_Runs', '<=', '5')->get();
$reorder = json_decode(json_encode($reord), true);
Notification::route('slack', 'https://hooks.slack.com/services/..../...../......')->notify(new InventoryReStock($reorder));
return view('products.lab_inventory_overview', compact('products', 'reorder'));
}
and this is my User.php
public function routeNotificationForSlack($notification)
{
Return 'https://hooks.slack.com/services/..../...../......';
}

Never mind, I found a solution . Just converting the array to string makes it work.
$reorder = implode(', ', array_flatten($reorde));

Related

RelationNotFoundException error only in laravel dispatched jobs

I have a very strange error in laravel 7 where I have defined a hasOne relationship in the User Model called user_badge
public function userBadge()
{
return $this->hasOne(UserBadge::class, 'id', 'user_badge_id');
}
I have added user_badge_id to the users table and I have also made the user_badges table which holds the badge information. When a job runs in the background, I get the following error
Illuminate\Database\Eloquent\RelationNotFoundException: Call to undefined relationship [userBadge] on model [App\User]. in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:34
Navigating throughout the site I get no issue at all.
This issue occurs when sending an email to the job queue. It happens to all notifications that is sent. Further to this, sometimes the email does get sent but most of the time it doesn't. The code is below for one of the notification
class NewFollowUserNotification extends Notification implements ShouldQueue
{
use Queueable;
public $sender;
public $receiver;
/**
* Create a new notification instance.
*
* #param User $sender
* #param User $receiver
*/
public function __construct(User $sender, User $receiver)
{
$this->sender = $sender;
$this->receiver = $receiver;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
if (Profile::sendEmailNotification('NewFollowUserNotification', $this->receiver)) {
return ['database', 'mail', 'broadcast'];
} else {
return ['database', 'broadcast'];
}
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$user_notifications = UserNotifications::create('NewFollowUserNotification');
$user_notifications->setUsername($this->receiver->username);
$user_notifications->setEmailTemplate(EmailTemplate::getDefaultEmail());
$user_notifications->setButtonUrl(config('app.url').'/member/profiles/'.$this->sender->username);
$notification = $user_notifications->getEmailNotification();
$user_notifications->setTags('{receiver_first_name}', $this->receiver->first_name);
$user_notifications->setTags('{receiver_last_name}', $this->receiver->last_name);
$user_notifications->setTags('{receiver_full_name}', $this->receiver->first_name . ' ' . $this->receiver->last_name);
$user_notifications->setTags('{sender_first_name}', $this->sender->first_name);
$user_notifications->setTags('{sender_last_name}', $this->sender->last_name);
$user_notifications->setTags('{sender_full_name}', $this->sender->first_name . ' ' . $this->sender->last_name);
return $user_notifications->sendUserNotification($notification);
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'heading' => 'New contact request',
'message' => $this->sender->first_name.' '.$this->sender->last_name.
' sent you a contact request',
'link' => '/member/profiles/'.$this->sender->username,
'username' => $this->sender->username,
'module' => 'user',
];
}
Locally on my own development machine everything works fine.
The issue here was the serialization of models within a job. There are limitations as to how much data jobs can serialize so I ended up passing the id of the model to the job and accessing the necessary information from there.

How to convert array of values into strings in laravel?

I am developing one controller which is responsible for send a mail with the books details(these details i am fetching from database),these are coming as a array of objects but what i need here is i want to pass a data like a normal strings, How to convert this array of objects to the strings ,please help me how to acheive this thing...
CustomersController.php
public function orderSuccessfull(Request $request){
$cust=new Customers();
$cust->user_id = auth()->id();
$cust_id=Customers::where('user_id',$cust->user_id)->value('user_id');
$user_email=User::where('id',$cust_id)->value('email');
$order = User::where('email', $user_email)->first();
$ord = Orders::create(
[
'orderNumber' => $order->orderNumber=Str::random(6),
'customer_id'=>$order->id,
'order_date'=>$order->order_date=Carbon::now(),
]
);
$bookgetter1 = DB::table("Books")->select('name')->where('cart',['1'])->get();
$bookgetter2 = DB::table("Books")->select('price')->where('cart',['1'])->get();
$bookgetter3 = DB::table("Books")->select('author')->where('cart',['1'])->get();
if($order && $ord){
$order->notify(new orderSuccessfullNotification($ord-
>orderNumber,$bookgetter1,$bookgetter2,$bookgetter3));
}
return response()->json(['message'=>'order created successfully']);
}
orderSuccessfullNotification.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class orderSuccessfullNotification extends Notification
{
use Queueable;
public $orderNumber;
public $bookgetter1;
public $bookgetter2;
public $bookgetter3;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($orderNumber,$bookgetter1,$bookgetter2,$bookgetter3)
{
$this->orderNumber = $orderNumber;
$this->bookgetter1=$bookgetter1;
$this->bookgetter2=$bookgetter2;
$this->bookgetter3=$bookgetter3;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line("You'r order has been placed successfully.. ")
->line('This is the order-id keep it furthur!')
->with($this->orderNumber)
->with($this->bookgetter1)
->with($this->bookgetter2)
->with($this->bookgetter3);
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$bookgetterPrices = json_decode($this->bookgetter2);
$totalPrice = 0;
foreach ($bookgetterPrices as $p) {
$totalPrice += $p->price;
}
$bookgetter1 = implode(',', array_map(function($x) { return $x->name; }, json_decode($this->bookgetter1)));
$bookgetter2 = implode(',', array_map(function($x) { return $x->price; }, $bookgetterPrices));
$bookgetter3 = implode(',', array_map(function($x) { return $x->author; }, json_decode($this->bookgetter3)));
return (new MailMessage)
->line("You'r order has been placed successfully.. ")
->line('This is the order-id keep it furthur!')
->with($this->orderNumber)
->with($totalPrice)
->with($bookgetter1)
->with($bookgetter2)
->with($bookgetter3)
}
You are passing the direct objects to the MailMessage, change the toMail method in your notification to this.
This should set the name of book1, however this whole class can be simplified.
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line("You'r order has been placed successfully.. ")
->line('This is the order-id keep it furthur!')
->line($this->bookgetter1[0]->name)
->with($this->orderNumber)
}

Custom user credentials for Nexmo / Vonage in Laravel notification

I'm writing a Laravel SMS notification with Nexmo channel. I don't want to use global API key but a different user-specific API key / secret instead. I tried to do it this way:
class MyNotification extends Notification
{
use Queueable;
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
$channels = ['mail'];
if ($notifiable instanceof User) {
if ($notifiable->sms_notifications && $notifiable->nexmo_api_key) {
$channels[] = 'nexmo';
}
}
return $channels;
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
// ...
}
public function toNexmo($notifiable)
{
/** #var User $notifiable */
$nexmoClient = new Client(new Basic($notifiable->nexmo_api_key, $notifiable->nexmo_api_secret));
return (new NexmoMessage())
->content("Test")
->usingClient($nexmoClient); // Ignored?
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Unfortunately this doesn't work and the client set by ->usingClient seems to be ignored. Could anybody help me please?

Laravel 5.8 on demand notification error Call to a member function create() on null

When I do this, the user receives email without error:
Notification::send($user, new TicketNotification($details));
But, when I do this, the user also receives an email, but with an error in the screenshot below
Notification::route('mail', 'email_of_non-db_user')->notify(new TicketNotification($details));
Error: Call to a member function create() on null
Do have any idea why? How can I avoid this error?
I have to use On Demand Notification because I need to send a notification to someone who is not stored as a "user".
i think try this one
in TicketNotification update via method with this for only send to mail.
But u r also saved notification into database..
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
Thanks Jignesh, your answer works.
Sorry Thamer, I should have posted the whole code from the beginning.
Before, it was :
return ['mail','database'];
Now only :
return ['mail'];
Then, there is no error anymore.
Here my TicketNotification that made the error:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class TicketNotification extends Notification
{
use Queueable;
private $details;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail','database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject($this->details['subject'])
->greeting($this->details['title'])
->line($this->details['body'])
->line($this->details['links'])
;
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'order_id' => $this->details['order_id']
];
}
}
Add this to your via method to use the same Notification for all your issues:
public function via($notifiable)
{
$availableChannels = [
'mail' => 'mail',
'database' => 'database',
'slack' => 'slack',
'telegram' => TelegramChannel::class
];
$channels = [];
foreach ($availableChannels AS $channel => $driver) {
if ($notifiable->routeNotificationFor($channel)) {
$channels[] = $driver;
}
}
return $channels;
}
You can now use On-Demand Notifications or fire the notificaton on users, without having to make multiple Notifications for each Channel or ON-DEMANDS etc...

Laravel Notification with ShouldQueue: toDatabase store different [data]

I have ServiceOrderCreated.php notification and want to use ShouldQueue, but it stores notification other than when I don't use ShouldQueue.
These are data sent to ServiceOrderCreated Class:
//notification
class ServiceOrderCreated extends Notification implements ShouldQueue
{
use Queueable;
protected $serviceOrder;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(ServiceOrder $serviceOrder)
{
$this->serviceOrder = $serviceOrder;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return json
*/
public function toDatabase($notifiable)
{
//dd($this->serviceOrder);
return [
$this->serviceOrder
];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$message = new MailMessage;
$message->subject('Sportservis-Hostivice: Nová zákazka č. '.$this->serviceOrder->id);
foreach ($this->serviceOrder->serviceOrderItem as $item) {
$message->line('<li>'.$item->customerOrderAsset->name.' - '.$item->serviceType->name.' - '.$item->price.'</li>');
}
return $message;
}
Problem is, that when I remove "implements ShouldQueue", it stores whole collection ($newServiceOrder) to Notifications table ([data] column). When "implements ShouldQueue" is in place, only bare model without relations is stored to Notifications table.
Any idea? Did I miss Something?
UPDATE
This is the collection which is passed from ServiceOrderController.php to notification.
$newServiceOrder = ServiceOrder::with(['serviceOrderItem', 'serviceOrderItem.serviceType', 'serviceOrderItem.customerOrderAsset', 'customer'])->find($serviceOrder->id)
$newServiceOrder->customer->notify(new ServiceOrderCreated($newServiceOrder));
UPDATE 2:
This is what is store in notifications table when I don't use ShouldQueue:
https://pastebin.com/hXF03tEa
And this is what is stored when I use ShouldQueue:
https://pastebin.com/Vb6hFZkH

Resources