i want to send notification to my clinic owner, when a clinic is added by admin. The following is my code,but mails are not sending,please not that email field in my db is clinicemail . Following is my code in clinic controller
public function storeClinics(Request $request)
{
$postdata = $request->all();
$api_key = Str::random(16);
$checkApiKey = Clinic::where('api_key', $api_key)->first();
if(!empty($checkApiKey)) {
$api_key = Str::random(16);
}
$clinic = new Clinic;
$clinic->clinicName=$postdata['user_name'];
$clinic->clinicFname=$postdata['contact_fname'];
$clinic->clinicLname=$postdata['contact_sname'];
$clinic->clinicAddress=$postdata['contact_address'];
$clinic->clinicCity=$postdata['contact_city'];
$clinic->clinicState=$postdata['contact_state'];
$clinic->clinicZip=$postdata['zip'];
$clinic->clinicEmail=$postdata['email'];
$clinic->clinicPhone=$postdata['phone'];
$clinic->clinicURL=$postdata['clinic_website'];
$clinic->clinicPub="no";
$clinic->api_key=$api_key;
$clinic->save();
Notification::route('mail', $clinic->clinicEmail)->notify(new ClinicRegisteredNotification($clinic));
return redirect('clinics');
}
I have also created a notification named ClinicRegisteredNotification in notificcations folder and following is code
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ClinicRegisteredNotification extends Notification {
public function __construct($clinic) {
$this->user = $clinic;
}
public function via($notifiable) {
return ['mail'];
}
public function toMail($notifiable) {
return (new MailMessage)
->success()
->subject('Welcome')
->line('Dear ' . $this->clinic->clinicName . ', we are happy to see you here.')
->line('Please tell your friends about us.');
}
}
In the ClinicRegisteredNotification, try to add a protected attribute before the __construct($clinic) method and change the line in the constructor.
The beginning of ClinicRegisteredNotification should be this:
class ClinicRegisteredNotification extends Notification {
protected $clinic;
public function __construct($clinic) {
$this->clinic = $clinic;
}
This should solve the issue.
Related
I made my code where an administrator can send a message to a group, and soon all users within that group receive notification on the mobile app:
public function create(Request $request)
{
if(!($error = $this->isNotValidate($request))){
//Log::error(print_r("validado", true));
$message = Message::create($request->toArray());
$message->recives()->attach($request->recive_ids);
foreach($message->recives as $group){
foreach($group->users as $user){
$user->notify(new NotificationMessage($message));
}
}
$response = ['message' => $message];
return response($response, 200);
}
return response($error, 422);
}
I used the library: https://github.com/laravel-notification-channels/fcm it is working he send the notification to the mobile through the firebase.
my difficulty is that in the toFcm function I want to retrieve the message to build the notification I'm sending:
public function toFcm($notifiable)
{
return FcmMessage::create()
->setData(['message_id' => $this->invoice->id, 'message_created' => $this->invoice->created_at])
->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
->setTitle($this->invoice->title)
->setBody($this->invoice->content)
//->setImage('http://example.com/url-to-image-here.png')
)->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setNotification(AndroidNotification::create()->setColor('#0A0A0A'))
)->setApns(
ApnsConfig::create()
->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios')));
}
I thought that in the variable $this->invoice or in the $notifiable would come the $message that I am passing as a parameter in the creation, but it does not pass, both are returning the user.
does anyone know how i can make this dynamic notification with my message data?
UPDATE
class NotificationMessage extends Notification
{
/**
* Specifies the user's FCM token
*
* #return string|array
*/
public function routeNotificationForFcm()
{
return $this->fcm_token;
}
public function via($notifiable)
{
return [FcmChannel::class];
}
public function toFcm($notifiable)
{
return FcmMessage::create()
->setData(['message_id' => $notifiable->id, 'message_created' => $notifiable->created_at])
->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
->setTitle($notifiable->title)
->setBody($notifiable->content)
//->setImage('http://example.com/url-to-image-here.png')
)->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setNotification(AndroidNotification::create()->setColor('#0A0A0A'))
)->setApns(
ApnsConfig::create()
->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios')));
}
// optional method when using kreait/laravel-firebase:^3.0, this method can be omitted, defaults to the default project
public function fcmProject($notifiable, $message)
{
// $message is what is returned by `toFcm`
return 'app'; // name of the firebase project to use
}
}
I decided to invert the logic of who was my notify, now instead of the user being the notify, my message became
In my control I'm even simpler:
public function create(Request $request)
{
if(!($error = $this->isNotValidate($request))){
//Log::error(print_r("validado", true));
$message = Message::create($request->toArray());
$message->recives()->attach($request->recive_ids);
$message->notify(new NotificationMessage);
$response = ['message' => $message];
return response($response, 200);
}
return response($error, 422);
}
in my message template I made the following changes:
use Illuminate\Notifications\Notifiable;
...
class Message extends BaseModel
{
use Notifiable;
...
public function routeNotificationForFcm()
{
$tokens = [];
foreach($this->recives as $group){
foreach($group->users as $user){
$tokens = array_merge($tokens, $user->notifications()->pluck('token')->toArray());
}
}
return $tokens;
}
}
with that in my variable $notifiable started to receive the information of the message and then it was easy to pass them as parameter.
I have customer data in my database with their emails. In my case, i want to get user email from customer table and send a custom email to customer. I'm new to laravel and this is the very first time i'm working with laravel notification. Help me to do this!
I have created this SendMailController:
public function sendNotifications(Request $request, $id)
{
$id = $request->id;
$customer_id = DB::table('jobs')->select('customers_id')->where('id', '=', $id)->get();
$customer_email = DB::table('customer')->select('email')->where('id', '=', $customer_id)->get();
$customer_firstname = DB::table('customer')->select('firstname')->where('id', '=', $customer_id)->get();
sendEmail($customer_firstname, $customer_email);
return view('admin.sendNotifications');
}
I have created a sendEmail Notification class:
class sendEmail extends Notification
{
use Queueable;
public function __construct($customer_firstname, $customer_email)
{
$this->customer_email = $customer_email;
$this->customer_firstname = $customer_firstname;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Thank you!')
->from('hashankannangara#gmail.com', 'Sender')
->to($this->customer_email)
->line($this->customer_firstname.''.'Thanks for got services from us!');
}
public function toArray($notifiable)
{
return [
//
];
}
}
How can i pass the customer email to to() function? I want to display customer first name in email with Thanking them. How can i use a custom template and add to this email? I appreciate if you can help me.
https://laravel.com/docs/6.x/notifications#mail-notifications
You can use something like this in toMail method:
return (new CustomMail($this->customer))->to($this->customer->email);
and when you call notify you must pass a customer
use Mail;
$data = 'set data variable pass in view'
$email= 'receiver' email'
Mail::send('here set your file for view (ex. email.access(blade))', $data, function ($message) use ($email) {
$message->from('sender mail','Title')->subject('Register');
$message->to($email);
});
I am building custom mvc framework in php in order to learn and when I am trying to submit my form with an mail that already exists in the database, my validation should prevent me to do so, instead I get this error:
Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:\xampp\htdocs\gacho\App\Controllers\UsersController.php:
UsersController.php
<?php
namespace App\Controllers;
use App\Models\User;
use Core\Controller;
class UsersController extends Controller
{
public function __construct($controller, $action)
{
parent::__construct($controller, $action);
$this->userModel = $this->load_model('User');
}
public function registerAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
'email' => trim($_POST['email']),
];
}
if (empty($data['email'])) {
$data['email_err'] = "Please enter your email!!!";
} else {
if ($this->userModel->findUserByEmail($data['email'])) {
$data['email_err'] = "Email is already taken!";
}
}
}
User.php
<?php
namespace App\Models;
use Core\Database;
class User
{
private $db;
public function __construct()
{
$this->db = new Database();
}
public function findUserByEmail($email)
{
$this->db->query('SELECT * FROM users WHERE email = :email');
$this->db->bind(':email', $email);
$row = $this->db->single();
if ($this->db->rowCount() > 0) {
return true;
} else {
return false;
}
}
}
Controller.php:
<?php
namespace Core;
class Controller
{
protected $_controller;
protected $_action;
public $view;
public function __construct($controller, $action)
{
$this->_controller = $controller;
$this->_action = $action;
$this->view = new View();
}
protected function load_model($model)
{
$modelPath = 'App\Models\\' . $model;
if (class_exists($modelPath)) {
$this->{$model.'Model'} = new $modelPath();
}
}
}
I think the mistake is about $this->userModel , but I'm stuck and any help is appreciated.
The problem is that in __construct of UsersController you have:
$this->userModel = $this->load_model('User');
So you assign to userModel property the return value of load_model method.
load_model method doesn't return anything so $this->userModel is always set to NULL, doesn't matter if load_model succeeded or not.
You should just return new $modelPath(); in load_model if you want to assign it to a property by return value.
Also add throw new Exception($modelPath. 'not found'); at the end of load_model method to be sure it did load the model, and not just failed silently to find it.
Note that $this->userModel is not the same as $this->UserModel (case sensitive) and $modelPath = 'App\Models\\' . $model; - why \ after App, and two \ after Models?
I think you need to access your model in $this->UserModel, since User was passed into the load_model method.
I want to send a message to my header (which I think means all views) notification part when a record changes in my pivot table so here is my code
This is client model
public function sellmanlist() {
return $this->belongsToMany('App\User' , 'client_user','client_id');
}
This is client controller to save sellman list
public function assignsellman(Client $client) {
$user = User::all();
$client_list = Client::all();
return view('admin.client.assign',compact('client_list','user'));
}
public function assignsellmanSave(Request $request) {
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client_name = $request->input('client');
$client->sellmanlist()->attach($sellman,['client_id' =>$client_name]);
return view('admin.client.assign',compact('client_list','user'));
}
now here I want to send a notification to the user that a client is assigned to you in his profile any clue how to do that ?
You need to create notification class for notifying user about client added
php artisan make:notification ClientAdded
after that edit this file which you find in a new folder App\Notifications
namespace App\Notifications;
use Illuminate\Notifications\Notification;
class ClientAdded extends Notification
{
protected $client;
public function __construct($client)
{
$this->client = $client;
}
public function via($notifiable)
{
return ['database']; //need to create notifications table check the below link
}
public function toArray($notifiable)
{
return [
'client_id' => $this->client->id,
'client_name' => $this->client->name,
];
}
}
Add below code in your User model and be sure your User model should have used Notifiable trait
public function sendClientAddedNotification($client)
{
$this->notify(new ClientAdded($client));
}
Import these class to User model
use App\Notifications\ClientAdded;
use Illuminate\Notifications\Notifiable;
Now in controller after client saved
$user->sendClientAddedNotification($client);
Here the $user should be the user whom you want to notify
Check this for Database notification https://laravel.com/docs/5.6/notifications#database-notifications
I have a controller like this
use App\Model\User;
class UserController extends BaseController
{
protected $model;
public function __construct(User $user)
{
$this->model = $user;
}
public function updatePhone(Request $request)
{
//user id
$id = $request->id;
//new phone number
$phone = $request->phone;
}
}
The function updatePhone is used to update the phone number of the user.So I can code like this
$res = $this->model->where('id',$id)->update('phone',$phone)
In this way, I do nothing in the user model.But I get used to like this
$res = $this->model->updatePhone($id, $phone);
And I must create function updatePhone in user model
public function updatePhone($id,$phone)
{
return $this->where('id',$id)->update('phone',$phone);
}
who is the better way to update a single model? Any answers or suggestions are excepted.