How to convert array of values into strings in laravel? - 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)
}

Related

I have multiple Notifications dispatched at once but only one is sent and no error is logged

Notification::sendNow(Admin::all(),new NewMessageNotification($tic,$message,Admin::first()));
Notification::sendNow(Admin::all(),new TicketCreatedNotification($tic));
my first notification class
class NewMessageNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(private Ticket $ticket,private TicketChat $chat,private $user)
{
//
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database','broadcast'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable): array
{
return $this->chat->append(['from','to'])->toArray()+['ticket'=>$this->ticket->toArray()];
}
public function toBroadcast($notifiable): array
{
$count = ['un_read_side_bar_count'=>$this->user->myUnReadSideBar()->count()];
if($this->user instanceof Admin){
$count+=['unread_sellers_chat'=>$this->user->myUnreadChatsSellers()->count(),'unread_users_chat'=>$this->user->myUnreadChatsUsers()->count()];
}
return $this->chat->append(['from','to'])->toArray()+['ticket'=>$this->ticket->toArray()]+$count;
}
public function broadCastType(){
return 'broadcast.message.received';
}
}
my second notification class
class TicketCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(public Ticket $ticket)
{
//
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database','broadcast'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'ticketable'=>[
'name'=>$this->ticket->ticketable->name,
],
'subject'=>$this->ticket->subject,
'identifier'=>$this->ticket->identifier,
'un_read_user_messages_count'=>$this->ticket->un_read_user_messages_count,
'un_read_admin_messages_count'=>$this->ticket->un_read_admin_messages_count,
'created_at'=>Carbon::parse($this->ticket->created_at)->format('Y-m-d H:i:s'),
];
}
public function broadCastType(){
return 'broadcast.ticket.created';
}
}
enter image description here
from image of telescope above it shows pending but in jobs table and failed_jobs its not there, I have tried delaying the job but still to no avail I removed the implement ShouldQueue still no result is there anything I am missing

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...

Notify Slack send Array

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));

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