ErrorException Undefined variable $employee - laravel

Using Database Notification I have stored notification in the notification table.
But now I want to display the notification in the blade template.
I have faced an undefined error.
Controller
$data=Employee::create([
'first_name'=>$request->input('first_name'),
'last_name'=>$request->input('last_name'),
'username'=>$request->input('username'),
'email'=>$request->input('email'),
'password'=>$request->input('password'),
'confirm_password'=>$request->input('confirm_password'),
]);
$admin=Employee::find(1);
$admin->notify(new NotifyAdmin($data));
NotifyAdmin class
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
use App\Models\Employee;
class NotifyAdmin extends Notification implements ShouldQueue
{
use Queueable, Notifiable;
private $val;
public function __construct(Employee $employee)
{
$this->val=$employee;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'username'=> $this->val->username
];
}
}
After doing this, the notification is stored in the notification table.
Now I want to display this notification
<div class="media-body">
#foreach($employee->notifications as $row)
<p class="noti-details"><span class="noti-title">Admin</span> added new doctor <span class="noti-title">{{$row->data['username']}}</span></p>
<p class="noti-time"><span class="notification-time">4 mins ago</span></p>
#endforeach
</div>

this is my controller
<?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;
use App\helpers\helper;
use App\Notifications\NotifyAdmin;
class EmployeeController extends Controller
{
public function InsertEmployees(Request $request)
{
$data=Employee::create([
'first_name'=>$request->input('first_name'),
'last_name'=>$request->input('last_name'),
'username'=>$request->input('username'),
'email'=>$request->input('email'),
'password'=>$request->input('password'),
'confirm_password'=>$request->input('confirm_password'),
'phone'=>$request->input('phone'),
'nid_number'=>$request->input('nid_number'),
'status'=>$request->input('status'),
'roles'=>$request->input('roles'),
'join_date'=>$request->input('join_date'),
]);
$admin=Employee::find(1);
$admin->notify(new NotifyAdmin($data));

Related

Class "App\Http\Controllers\Auth\Mail" not found

How can I resolve this error? I am trying to customize the default email template on laravel. This is the code for the controller that sends the email.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use App\Models\User;
use Illumunate\Auth;
class EmailVerificationNotificationController extends Controller
{
public function store(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(RouteServiceProvider::HOME);
}
Mail::send('email.template', $request->user(), function($mail) use($data){
$mail->to($request->user()->email, 'no-reply')->subject("Verify Email Address");
$mail->from('admin#raketlist.com','testing');
});
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}
Add use Illuminate\Support\Facades\Mail; to other uses.

Laravel Job not queued?

I'm new in Laravel and i want to import a Csv file and store the data in DB with Maatwebsite\Excel. I'm trying to achieve that using jobs in laravel. When i run php artisan queue:work i don't see the job in the queue.
I've set my routes :
Route::get('/import', 'UserImportController#getImport')->name('import');
Route::post('/import_process', 'UserImportController#fileImport')->name('import_process');
I have my controller like this :
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\CsvImportRequest;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\UsersImport;
class UserImportController extends Controller
{
public function getImport()
{
return view('import');
}
public function fileImport(Request $request)
{
$request->validate([
'import_file' => 'required',
]);
Excel::import(new UsersImport, request()->file('import_file'));
return back()->withStatus('Import done!');
}
}
I've configured my .env like this:
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
I've created a Job:
<?php
namespace App\Jobs;
use App\Imports\UsersImport;
use Illuminate\Bus\Queueable;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Maatwebsite\Excel\Facades\Excel;
class ImportJob implements ShouldQueue
{
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $uploadFile;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($uploadFile)
{
$this->uploadFile = $uploadFile;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Excel::import(new UsersImport, $this->uploadFile);
}
}
I created a Livewire component and view:
<?php
namespace App\Http\Livewire;
use App\Jobs\ImportJob;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Storage;
class Import extends Component
{
use WithFileUploads;
public $batchId;
public $importFile;
public $importing = false;
public $importFilePath;
public $importFinished = false;
public function import()
{
$this->validate([
'importFile' => 'required',
]);
$this->importing = true;
$this->importFilePath = $this->importFile->store('imports');
$batch = Bus::batch([
new ImportJob($this->importFilePath),
])->dispatch();
$this->batchId = $batch->id;
}
public function getImportBatchProperty()
{
if (!$this->batchId) {
return null;
}
return Bus::findBatch($this->batchId);
}
public function updateImportProgress()
{
$this->importFinished = $this->importBatch->finished();
if ($this->importFinished) {
Storage::delete($this->importFilePath);
$this->importing = false;
}
}
public function render()
{
return view('livewire.import');
}
}
<div>
<form wire:submit.prevent="import" enctype="multipart/form-data">
#csrf
<input type="file" wire:model="importFile" class="#error('import_file') is-invalid #enderror">
<button class="btn btn-outline-secondary">Import</button>
#error('import_file')
<span class="invalid-feedback" role="alert">{{ $message }}</span>
#enderror
</form>
#if($importing && !$importFinished)
<div wire:poll="updateImportProgress">Importing...please wait.</div>
#endif
#if($importFinished)
Finished importing.
#endif
</div>
But when i click on import button nothing happens the import function isn't called and the job is not queued. I don't know what the issue ?

How to change the subject of email in mailable class in laravel

How to change the subject of email in mailable class in laravel 6. The subject on email showing is 'Send Email'. email is sending properly. the only problem is I am not able to change the subject of the email.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendEmail extends Mailable
{
use Queueable, SerializesModels;
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function build()
{
return $this->view('mails.verify_account')->with([
'email_token' => $this->user->email_token,
]);
}
}
You may use subject method:
public function build()
{
return $this->subject('Your subject')
->view('mails.verify_account')
->with([
'email_token' => $this->user->email_token,
]);
}
Check Laravel docs for more info.
in your __construct, add: $this->subject('bla bla');

laravel:send notification with (data) when update a record

Problem: how can I display data with update function?
the notification is sent but witout data that I specified in this function :
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
it works with store function but it dosn't with update function
my notification class:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Booking;
class NewMessage extends Notification
{
use Queueable;
public $booking;
public function __construct(Booking $booking)
{
//
$this->booking = $booking;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
my update function :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Booking;
use App\User;
use Notification;
use App\Notifications\NewMessage;
class DispoController extends Controller
{
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
it shows just "new booking"
#foreach(Auth::user()->unreadNotifications as $not)
<li>
<a class="dropdown-item" >new booking {{$not->data['data']}}</a>
</li>
#endforeach
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage(Booking::findOrFail($id)));
// notification
return redirect()->route('info_client.index')->with(['success'=>'succés']);
}
The issue is your not capturing the saved booking, should be like so
public function update(Request $request,$id,Booking $booking)
{
//
$booking = Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So your passing in an empty booking from the function call and passing that to the notification and not the updated record.
But you can simplify the whole thing by doing this
public function update(Request $request, Booking $booking)
{
//
$booking->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So instead of passing both id and booking just pass in the booking which should automatically be found from the Route and container.

Call to undefined method Illuminate\Notifications\Notification::send()

I am trying to make a notification system in my project.
These are the steps i have done:
1-php artisan notifications:table
2-php artisan migrate
3-php artisan make:notification AddPost
In my AddPost.php file i wrote this code:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class AddPost extends Notification
{
use Queueable;
protected $post;
public function __construct(Post $post)
{
$this->post=$post;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'data'=>'We have a new notification '.$this->post->title ."Added By" .auth()->user()->name
];
}
}
In my controller I am trying to save the data in a table and every thing was perfect.
This is my code in my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
//use App\Notifications\Compose;
use Illuminate\Notifications\Notification;
use DB;
use Route;
class PostNot extends Controller
{
public function index(){
$posts =DB::table('_notification')->get();
$users =DB::table('users')->get();
return view('pages.chat',compact('posts','users'));
}
public function create(){
return view('pages.chat');
}
public function store(Request $request){
$post=new Post();
//dd($request->all());
$post->title=$request->title;
$post->description=$request->description;
$post->view=0;
if ($post->save())
{
$user=User::all();
Notification::send($user,new AddPost($post));
}
return redirect()->route('chat');
}
}
Everything was good until I changed this code:
$post->save();
to this :
if ($post->save())
{
$user=User::all();
Notification::send($user,new AddPost($post));
}
It started to show an error which is:
FatalThrowableError in PostNot.php line 41: Call to undefined method
Illuminate\Notifications\Notification::send()
How can i fix this one please??
Thanks.
Instead of:
use Illuminate\Notifications\Notification;
you should use
use Notification;
Now you are using Illuminate\Notifications\Notification and it doesn't have send method and Notification facade uses Illuminate\Notifications\ChannelManager which has send method.
Using this
use Illuminate\Support\Facades\Notification;
instead of this
use Illuminate\Notifications\Notification;
solved the problem for me.
Hope this helps someone.
using this is better
use Notification
Instead of
use Illuminate\Support\Facades\Notification
this makes the send() not accessible [#Notification Databse]

Resources