skip to Main Content

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

I can send emails using a link with this

                <div class="p-6 bg-white border-b border-gray-200">
                Let the Administrator know there is activity
                    <a href="{{route('activity')}}" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md" >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 class="container mt-2">
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>


<div class="row">


<div class="col-md-12 card-header text-center font-weight-bold">
<h2>Comment Bank</h2>
</div>


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


<div class="col-md-12 mt-1 mb-2"><button type="button" id="addNewCommentUser" class="btn btn-success">Add</button></div>
<div class="col-md-12">
<table id="Table1" class="table">
<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 class="modal fade" id="comments-crud-model" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="commentsCrudModel"></h4>
</div>
<div class="modal-body">


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



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

<div class="form-group">
<label for="name" class="col-sm-4 control-label">Comment Body</label>
<div class="col-sm-12">
<textarea class="form-control" id="comment_body" name="comment_body" rows="4" cols="10" placeholder="Enter Comment Body"></textarea>
</div>
</div>


<div class="form-group">
<label class="col-sm-4 control-label">First Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter First Name" value="" required="">
</div>
</div>

<div class="form-group">
<label class="col-sm-4 control-label">Last Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter Last Name" value="" required="">
</div>
</div>


<div class="form-group">
<label class="col-sm-4 control-label">Email</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="email" name="email" placeholder="Enter Email" value="" required="">
</div>
</div>

<div class="form-group">
<label class="col-sm-4 control-label">Comment Tone</label>
<div class="col-sm-12">
<select name="comment_tone" id="comment_tone" class="form-control">
                    <option value="1">Positive</option>
                    <option value="0">Negative</option>
                </select>
</div>
</div>

<div class="form-group">
<label class="col-sm-4 control-label">Comment Type</label>
<div class="col-sm-12">
<select name="comment_type" id="comment_type">
                    <option value="CO">Conclusion Comments</option>
                    <option value="RO">Results Comments</option>
                </select>
</div>
</div>



<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-add" value="addNewCommentUser">Save
</button>
<button type="submit" class="btn btn-primary" id="btn-save" value="UpdateCommentUser">Save changes
</button>
</div>
</form>
</div>
<div class="modal-footer">
</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 AppHttpControllers;

use AppModelsComment;

use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;
use IlluminateSupportFacadesAuth;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    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  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    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  IlluminateHttpRequest  $request
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    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  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    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  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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  IlluminateHttpRequest  $request
     * @param  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    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  AppProduct  $product
     * @return IlluminateHttpResponse
     */
    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

3

Answers


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

    Login or Signup to reply.
  2. On your comment model,

    class Comment extends 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());
            });
        }
    }
    
    Login or Signup to reply.
  3. Just put this code to where you want to send email:

    Mail::to('[email protected]')->send(new Activity());
    

    You say you want to put this "when data is added", maybe put this code on store and storeUser method in the controller

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search