Home > OS >  How to send an email when when data is added using laravel mail package
How to send an email when when data is added using laravel mail package

Time:04-08

For my website I want the admin to be emailed when data is added.

I can send emails using a link with this

                <div >
                Let the Administrator know there is activity
                    <a href="{{route('activity')}}"  >Notify Admin</a>
            </div>

and using this route in web.php

Route::get('/activity', function(){
    Mail::to('[email protected]')->send(new Activity());
    return redirect('/dashboard');
})->name('activity');

but I want for this email to send when data is added using my crud page.

This is my crud view

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Comment Bank</title> 
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >


<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>


<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<x-app-layout>

<div >
    <x-slot name="header">
        <h2 >
            {{ __('Dashboard') }}
        </h2>
    </x-slot>


<div >


<div >
<h2>Comment Bank</h2>
</div>


<div id="message"></div>


<div ><button type="button" id="addNewCommentUser" >Add</button></div>
<div >
<table id="Table1" >
<thead>
<tr>
    <th scope ="col">Message Select</th>
<th scope="col">#</th>
<th scope="col">Comment Body</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Comment Tone</th>
<th scope="col">Comment Type</th>
<th scope="col">Verified Status</th>
</tr>
</thead>
<tbody> 


</tbody>
</table>
<input id = "btnGet" type="button" value="Get Selected" />


</div>
</div> 
<div><textarea id="messageList" rows="10" cols="100">Selection</textarea> <button type="button" id="copy">Copy</button></div>


</div>



<!-- boostrap model -->
<div  id="comments-crud-model" aria-hidden="true">
<div >
<div >
<div >
<h4  id="commentsCrudModel"></h4>
</div>
<div >


<ul id="msgList"></ul>



<form action="javascript:void(0)" id="addEditCommentFormUser" name="addEditCommentFormUser"  method="POST">
<input type="hidden" name="id" id="id">

<div >
<label for="name" >Comment Body</label>
<div >
<textarea  id="comment_body" name="comment_body" rows="4" cols="10" placeholder="Enter Comment Body"></textarea>
</div>
</div>


<div >
<label >First Name</label>
<div >
<input type="text"  id="first_name" name="first_name" placeholder="Enter First Name" value="" required="">
</div>
</div>

<div >
<label >Last Name</label>
<div >
<input type="text"  id="last_name" name="last_name" placeholder="Enter Last Name" value="" required="">
</div>
</div>


<div >
<label >Email</label>
<div >
<input type="text"  id="email" name="email" placeholder="Enter Email" value="" required="">
</div>
</div>

<div >
<label >Comment Tone</label>
<div >
<select name="comment_tone" id="comment_tone" >
                    <option value="1">Positive</option>
                    <option value="0">Negative</option>
                </select>
</div>
</div>

<div >
<label >Comment Type</label>
<div >
<select name="comment_type" id="comment_type">
                    <option value="CO">Conclusion Comments</option>
                    <option value="RO">Results Comments</option>
                </select>
</div>
</div>



<div >
<button type="submit"  id="btn-add" value="addNewCommentUser">Save
</button>
<button type="submit"  id="btn-save" value="UpdateCommentUser">Save changes
</button>
</div>
</form>
</div>
<div >
</div>
</div>
</div>
</div>
</x-app-layout>


<!-- end bootstrap model -->
<script>
$(document).ready(function($){


fetchCommentUser(); // Get the table from the dB to start


$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function fetchCommentUser()
{
// ajax
$.ajax({
type:"GET",
url: "fetch-comments-user",
dataType: 'json',
success: function(res){
// console.log(res);
$('tbody').html("");
$.each(res.comments, function (key, item) {
$('tbody').append('<tr>\
<td><input type="checkbox" name="comments_to_copy" id="comments_to_copy'  item.id '"/></td>\
<td>'   item.id   '</td>\
<td>'   item.comment_body   '</td>\
<td>'   item.first_name   '</td>\
<td>'   item.last_name   '</td>\
<td>'   item.email   '</td>\
<td>'   item.comment_tone   '</td>\
<td>'   item.comment_type   '</td>\
</tr>');
});
},
complete: function(){
isChecked();
}
});
}


$('#addNewCommentUser').click(function (evt) {
evt.preventDefault();



$('#addEditCommentFormUser').trigger("reset");
$('#commentsCrudModel').html("Add Comment");
$('#btn-add').show();
$('#btn-save').hide();
$('#comments-crud-model').modal('show');
});


$('body').on('click', '#btn-add', function (event) {
event.preventDefault();
var comment_body = $("#comment_body").val();
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var comment_tone = $("#comment_tone").val();
var comment_type = $("#comment_type").val();
var verified_status = 0
$("#btn-add").html('Please Wait...');
$("#btn-add").attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "save-comment-user",
data: {
comment_body:comment_body,
first_name:first_name,
last_name:last_name,
email: email,
comment_tone: comment_tone,
comment_type: comment_type,
verified_status: verified_status,
},
dataType: 'json',
success: function(res){
console.log(res);
if (res.status == 400) {
$('#msgList').html("");
$('#msgList').addClass('alert alert-danger');
$.each(res.errors, function (key, err_value) {
$('#msgList').append('<li>'   err_value   '</li>');
});
$('#btn-save').text('Save changes');
} else {
$('#message').html("");
$('#message').addClass('alert alert-success');
$('#message').text(res.message);
fetchCommentUser();
}
},
complete: function(){
$("#btn-add").html('Save');
$("#btn-add").attr("disabled", false);
$("#btn-add").hide();
$('#comments-crud-model').modal('hide');
$('#message').fadeOut(4000);
}
});
});
$('body').on('click', '.edit', function (evt) {
evt.preventDefault();
var id = $(this).data('id');


// ajax
$.ajax({
type:"GET",
url: "edit-comment-user/" id,
dataType: 'json',
success: function(res){
console.dir(res);
$('#commentsCrudModel').html("Edit Comment");
$('#btn-add').hide();
$('#btn-save').show();
$('#comments-crud-model').modal('show');
if (res.status == 404) {
$('#msgList').html("");
$('#msgList').addClass('alert alert-danger');
$('#msgList').text(res.message);
} else {
// console.log(res.book.xxx);
$('#comment_body').val(res.comment.comment_body);
$('#first_name').val(res.comment.first_name);
$('#last_name').val(res.comment.last_name);
$('#email').val(res.comment.email);
$('#comment_tone').val(res.comment.comment_tone);
$('#comment_type').val(res.comment.comment_type);
$('#verified_status').val(res.comment.verified_status);
$('#id').val(res.comment.id);
}
}
});
});
$('body').on('click', '.delete', function (evt) {
evt.preventDefault();
if (confirm("Delete Comment?") == true) {
var id = $(this).data('id');
// ajax
$.ajax({
type:"DELETE",
url: "delete-comment-user/" id,
dataType: 'json',
success: function(res){
// console.log(res);
if (res.status == 404) {
$('#message').addClass('alert alert-danger');
$('#message').text(res.message);
} else {
$('#message').html("");
$('#message').addClass('alert alert-success');
$('#message').text(res.message);
}
fetchCommentUser();
}
});
}
});
$('body').on('click', '#btn-save', function (event) {
event.preventDefault();
var id = $("#id").val();
var comment_body = $("#comment_body").val();
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var comment_tone = $("#comment_tone").val();
var comment_type = $("#comment_type").val();
var verified_status = $("#verified_status").val();
// alert("id=" id " title = "   title);
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type:"PUT",
url: "update-comment-user/" id,
data: {
comment_body:comment_body,
first_name:first_name,
last_name:last_name,
email: email,
comment_tone: comment_tone,
comment_type: comment_type,
verified_status: verified_status,
},
dataType: 'json',
success: function(res){
console.log(res);
if (res.status == 400) {
$('#msgList').html("");
$('#msgList').addClass('alert alert-danger');
$.each(res.errors, function (key, err_value) {
$('#msgList').append('<li>'   err_value   '</li>');
});
$('#btn-save').text('Save changes');
} else {
$('#message').html("");
$('#message').addClass('alert alert-success');
$('#message').text(res.message);
fetchCommentUser();
}
},
complete: function(){
$("#btn-save").html('Save changes');
$("#btn-save").attr("disabled", false);
$('#comments-crud-model').modal('hide');
$('#message').fadeOut(4000);
}
});
});
$("#btnGet").click(function () {
var message = "";


//Loop through all checked CheckBoxes in GridView.
$("#Table1 input[type=checkbox]:checked").each(function () {
var row = $(this).closest("tr")[0];
// message  = row.cells[2].innerHTML;
message  = " "   row.cells[2].innerHTML;
// message  = " "   row.cells[4].innerHTML;
message  = "\n-----------------------\n";
});


//Display selected Row data in Alert Box.
$("#messageList").html(message);
return false;
});


$("#copy").click(function(){
$("#messageList").select();
document.execCommand("copy"); 
alert("Copied On clipboard");
});


function isChecked(){
$("#Table1 input[type=checkbox]").each(function () {
if ($(this).val() == 1)
{
$(this).prop("checked", true);
}
else
{
$(this).prop("checked", false);
}
});
}
});

</script>
</body>
</html>

and my CommentController

<?php

namespace App\Http\Controllers;

use App\Models\Comment;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(Auth::user()->hasRole('user')){
            return view('user-view');
       }elseif(Auth::user()->hasRole('administrator')){
            return view('comments-crud');
       }
    }
    
    public function fetchComment()
    {
        $comments = Comment::all();
        return response()->json([
            'comments'=>$comments,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'comment_body'=>'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'email'=>'required',
            'comment_tone'=>'required',
            'comment_type'=>'required',
            'verified_status'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'status'=>400,
                'errors'=>$validator->messages()
            ]);
        }
        else
        {
            $comment = new Comment;
            $comment->comment_body = $request->input('comment_body');
            $comment->first_name = $request->input('first_name');
            $comment->last_name = $request->input('last_name');
            $comment->email = $request->input('email');
            $comment->comment_tone = $request->input('comment_tone');
            $comment->comment_type = $request->input('comment_type');
            if ($request->has('verified_status')){
                $comment->verified_status = 1;
            }
            else{
                $comment->verified_status = 0;

            }
            
            $comment->save();
            return response()->json([
                'status'=>200,
                'message'=>'Comment Added Successfully.'
            ]);
        }
    }
      
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $comment = Comment::find($id);
        if($comment)
        {
            return response()->json([
                'status'=>200,
                'comment'=> $comment,
            ]);
        }
        else
        {
            return response()->json([
                'status'=>404,
                'message'=>'No Comment Found.'
            ]);
        }
    }

    /**
     * Update an existing resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'comment_body'=>'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'email'=>'required',
            'comment_tone'=>'required',
            'comment_type'=>'required',
            'verified_status'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'status'=>400,
                'errors'=>$validator->messages()
            ]);
        }
        else
        {
            $comment = comment::find($id);
            if($comment)
            {
                $comment->comment_body = $request->input('comment_body');
                $comment->first_name = $request->input('first_name');
                $comment->last_name = $request->input('last_name');
                $comment->email = $request->input('email');
                $comment->comment_tone = $request->input('comment_tone');
                $comment->comment_type = $request->input('comment_type');
                $comment->verified_status = $request->input('verified_status');
                $comment->update();
                return response()->json([
                    'status'=>200,
                    'message'=>'Comment with id:'.$id. ' Updated Successfully.'
                ]);
            }
            else
            {
                return response()->json([
                    'status'=>404,
                    'message'=>'No Comment Found.'
                ]);
            }

        }
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $comment = Comment::find($id);
        if($comment)
        {
            $comment->delete();
            return response()->json([
                'status'=>200,
                'message'=>'Comment Deleted Successfully.'
            ]);
        }
        else
        {
            return response()->json([
                'status'=>404,
                'message'=>'No Comment Found.'
            ]);
        }
    }


    ///////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////
    //USER FUNCTIONS
    ////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////

    public function fetchCommentUser()
    {
        $comments = Comment::where('verified_status', 1)->get();

        return response()->json([
            'comments' => $comments,
        ]);
    }

   
        /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storeUser(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'comment_body'=>'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'email'=>'required',
            'comment_tone'=>'required',
            'comment_type'=>'required',
            'verified_status'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'status'=>400,
                'errors'=>$validator->messages()
            ]);
        }
        else
        {
            $comment = new Comment;
            $comment->comment_body = $request->input('comment_body');
            $comment->first_name = $request->input('first_name');
            $comment->last_name = $request->input('last_name');
            $comment->email = $request->input('email');
            $comment->comment_tone = $request->input('comment_tone');
            $comment->comment_type = $request->input('comment_type');
            if ($request->has('verified_status')){
                $comment->verified_status = 0;
            }
            else{
                $comment->verified_status = 1;

            }
            
            $comment->save();
            return response()->json([
                'status'=>200,
                'message'=>'Comment Added Successfully.'
            ]);
        }
    }
      


    /**
     * Update an existing resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function updateUser(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'comment_body'=>'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'email'=>'required',
            'comment_tone'=>'required',
            'comment_type'=>'required',
            'verified_status'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'status'=>400,
                'errors'=>$validator->messages()
            ]);
        }
        else
        {
            $comment = comment::find($id);
            if($comment)
            {
                $comment->comment_body = $request->input('comment_body');
                $comment->first_name = $request->input('first_name');
                $comment->last_name = $request->input('last_name');
                $comment->email = $request->input('email');
                $comment->comment_tone = $request->input('comment_tone');
                $comment->comment_type = $request->input('comment_type');
                $comment->verified_status = $request->input('verified_status');
                $comment->update();
                return response()->json([
                    'status'=>200,
                    'message'=>'Comment with id:'.$id. ' Updated Successfully.'
                ]);
            }
            else
            {
                return response()->json([
                    'status'=>404,
                    'message'=>'No Comment Found.'
                ]);
            }

        }
    }

        /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function editUser($id)
    {   
        $comment = Comment::find($id);
        if($comment)
        {
            return response()->json([
                'status'=>200,
                'comment'=> $comment,
            ]);
        }
        else
        {
            return response()->json([
                'status'=>404,
                'message'=>'No Comment Found.'
            ]);
        }
    }
}

I understand this may be easiest to accomplish in the controller but i don't know how

CodePudding user response:

the best way to do this is by using Observers, when any record is added to your model the method created in the Observer model will trigger

check this

https://laravel.com/docs/9.x/eloquent#observers

I hope it's helpful

CodePudding user response:

On your comment model,

/**
 * At the top of your comment model.
 */
public static function boot(){
    parent::boot();

    static::created(function ($instance){
        // If you want to trigger the email on only new comments add it here.
        Mail::to('[email protected]')->send(new Activity());
    });
    static::updated(function ($instance){
        // If you want to trigger it on update also 
        Mail::to('[email protected]')->send(new Activity());
    });
}
  • Related