Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 22, 2022 07:09 am GMT

Laravel 8 Email Notification Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-email-notification-example

In this post, I will show you an example how to implement Laravel 8 email notifications. We know that email notifications is one of the most important functionality to implement in our web application as well as in Laravel framework. Laravel provide an easy way of sending email using Notification class that easily send to any delivery channels such as email, SMS, and Slack. The advantage of using Notification on Laravel is that this is already associated with the specified user we just put a parameter of User object value then the class will handle the sending.

In Laravel notification we can also save it to our database so that easily display in our web interface.

In this Laravel notification example we are using email to notify the User with the project assigned.

Kindly follow the following below to learn about Laravel email notification.

Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Step 2: Database Configuration

If your Laravel project is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.

.env

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=your_database_name_hereDB_USERNAME=your_database_username_hereDB_PASSWORD=your_database_password_here

Step 3: Migration Setup

Here we need to generate first the notifications table before running the migrations. Kindly run the following command:

php artisan notifications:table
php artisan migrate

Then once done let's create a seeder for our user. Run the following command:

php artisan make:seeder CreateUsersSeeder

Once our seeder is generated kindly to the database/seeders directory. Open the CreateUsersSeeder.php and you will see the following code:

<?phpnamespace Database\Seeders;use App\Models\User;use Illuminate\Database\Seeder;class CreateUsersSeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        User::create([            'name' => 'Juan',            'email' => '[email protected]',            'password' => bcrypt('password')        ]);    }}

Then run the following command:

php artisan db:seed --class=CreateUsersSeeder

Learn more about Laravel seeder here.

Step 4: Making Laravel Email Notification

Now, let's generate our Laravel email notification example we will name this as EmailNotification. Run the following command to do this.

php artisan make:notification EmailNotification

Once done, navigate App/Notifications and open EmailNotification.php then edit it. See below example:

<?phpnamespace App\Notifications;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Notifications\Notification;class EmailNotification extends Notification{    use Queueable;    /**     * @var array $project     */    protected $project;    /**     * Create a new notification instance.     *     * @return void     */    public function __construct($project)    {        $this->project = $project;    }    /**     * 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)                    ->greeting($this->project['greeting'])                    ->line($this->project['body'])                    ->action($this->project['actionText'], $this->project['actionURL'])                    ->line($this->project['thanks']);    }    /**     * Get the array representation of the notification.     *     * @param  mixed  $notifiable     * @return array     */    public function toDatabase($notifiable)    {        return [            'project_id' => $this->project['id']        ];    }    /**     * Get the array representation of the notification.     *     * @param  mixed  $notifiable     * @return array     */    public function toArray($notifiable)    {        return [            //        ];    }}

Step 4: Setting up Routes

In my example, I will create manually my crud routes. Just open the "routes/web.php" file and add the following routes.

<?phpuse Illuminate\Support\Facades\Route;/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/Route::get('/', function () {    return view('welcome');});Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Step 5: Setting Up Controller

In this section we will add our email notification in our HomeController as we set in our routes. See below complete code of our controller:

<?phpnamespace App\Http\Controllers;use Notification;use App\Models\User;use Illuminate\Http\Request;use App\Notifications\EmailNotification;class HomeController extends Controller{    public function send()     {        $user = User::first();        $project = [            'greeting' => 'Hi '.$user->name.',',            'body' => 'This is the project assigned to you.',            'thanks' => 'Thank you this is from codeanddeploy.com',            'actionText' => 'View Project',            'actionURL' => url('/'),            'id' => 57        ];        Notification::send($user, new EmailNotification($project));        dd('Notification sent!');    }}

Now our code is ready for sending notification to our user. You can test it now by running the serve command:

php artisan serve

Then run the url below to your browser to send email notification to your user.

http://127.0.0.1:8000/send

Now Laravel sent email notification. See below output:

laravel-8-email

Laravel also provide a way of sending option.

$user->notify(new EmailNotification($project));

And you can get the user notifications by using the following code.

dd($user->notifications);

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-email-notification-example if you want to download this code.

Happy coding :)


Original Link: https://dev.to/codeanddeploy/laravel-8-email-notification-example-oai

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To