Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

takix's avatar
Level 1

laravel notify admin when user do store

How can I get an e-mail to be sent to me when the user shares a story? I tried this but failed. I want your help.I would be very grateful if you could explain in detail.I don't know much about Laravel, but I can do it if there is a detailed explanation. This is very important for my project.I'm sure a friend will help me

public function store(Request $request)
    {
        
        if(Settings::find('active_upload')->value == 0){
            toastr()->warning(__('main.new_entries_paused'));
            return redirect('/');
        }
        
        $rules = [
            'title' => 'required|string|max:255',
            'story' => 'required|string|min:'.Settings::find('minimum_characters')->value.'|max:'.Settings::find('maximum_characters')->value,
            'tags' => 'nullable',
            'category_id' => 'required',
            'genders_id' => 'required',
            'age' => 'required',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
        ];
        
        if($request->hasFile('photo')) {
            $rules['story'] = 'nullable';
        }

        Validator::make($request->all(), $rules,[
			'title.required' => 'Bir Başlık Giriniz.',
            'title.max' => 'Başlık 255 Karakterden Uzun Olamaz.',

            'story.required' => 'Boş bırakılmamalıdır.',
            'story.min' => 'Girilen Metin '.Settings::find('minimum_characters')->value.' Karakterden Fazla Olmalıdır.',
            'story.max' => 'Girilen Metin ' .Settings::find('maximum_characters')->value.' Karakterden Az Olmalıdır.',

            'category_id.required' => 'Kategori Seçmeniz Gerekiyor.',

            'photo.image' => 'Lütfen Resim Dosyası Yükleyiniz.',
            'photo.mimes' => 'Dosya Biçimi jpg,png veya jpeg olmalıdır.',
			
			
		
		])->validateWithBag('write');

  
        // if word censored is active
        if(Settings::find('words_censored')->value == 1) {
            
            $censor = new CensorWords;
            $badwords = $censor->setDictionary(base_path('/vendor/snipe/banbuilder/src/dict/dictionary.php'));
            $string = $censor->censorString($request->story)['clean'];
            
        } else {

            $string = $request->story;
        
        }
        //
        
        // create item
    	$create_item = Items::create([
            'title' => $request->title,
            'story' => $string,
            'slug' => Str::slug($request->title),
            'status' => Settings::find('new_entries')->value,
            'user_id' => Auth::id(),
            'category_id' => $request->category_id,
            'genders_id' => $request->genders_id,
            'age' => $request->age,
        ]);
        
        if ($create_item) {

            // if exists, upload photo
            if ($request->hasFile('photo')) {

                // upload original
                $path = $request->file('photo')->store('photos');

                // store photo
                $storePhoto = Photos::create([
                    'item_id' => $create_item->id,
                    'filename' => $path
                ]);

            }

            // create tags
            $tags = explode(",", $request->tags);
            $create_item->tag($tags);
            
            if(Settings::find('status_points')->value == 1){
                if(Settings::find('status_points_new_entry')->value == 1){
                    Points::create([
                        'user_id' => Auth::id(),
                        'point_type' => "new_entry",
                        'score' => Settings::find('points_new_entry')->value,
                        'item_id' => $create_item->id
                    ]);
                }
            }
            
            if(Settings::find('new_entries')->value == 1){
            
                toastr()->success(__('main.toast_your_post_has_been_posted'));
                return redirect('/');
                
            } else {
                
                toastr()->warning(__('main.toast_post_in_moderation'));
                return redirect('/');
                
            }
            
            
        } else {
            toastr()->error(__('main.toast_there_are_problems_try_again'));
            return redirect('/')->withErrors($validator, 'write')->withInput();
        }
        
    }
0 likes
19 replies
vincent15000's avatar

In the store method, you have just to send a notification to the admin.

Assuming you have only one admin among the users and the is_admin boolean field in the users table, you can do something like this.

$admin = User::where('is_admin', true)->first();
$admin->notify(new NewStoryCreated(auth()->user()));

You need to create a notification.

php artisan make:notification NewStoryCreated

https://laravel.com/docs/9.x/notifications#generating-notifications

And customize the content of your notification.

public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('A new story has been created')
        ->greeting('Hello !')
        ->line($this->user->name.' has created a new story.');
}
takix's avatar
Level 1

@vincent15000 $admin = User::where('is_admin', true)->first(); $admin->notify(new NewStoryCreated(auth()->user()));

this part

1 like
takix's avatar
Level 1

@vincent15000 In my system everyone is the same but separated as roles. For example 1.user 2.admin 3.moderator

1 like
takix's avatar
Level 1

@vincent15000 user.php

public function isAdministrator() {
        return $this->roles()->where('name', 'admin')->exists();
    }
1 like
vincent15000's avatar

@takix Have you created the notification ? Have you an is_admin field in the users table ?

takix's avatar
Level 1
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewStoryCreated extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

1 like
takix's avatar
Level 1

@vincent15000 The admin role does not appear in the users table. I have a table called "roles" and I set it from there.

1 like
takix's avatar
Level 1

@vincent15000

yes

MAIL_MAILER=smtp
MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
MAIL_USERNAME=(secret)@hotmail.com
MAIL_PASSWORD=(secret)
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=(secret)@hotmail.com
MAIL_FROM_NAME="Site Name"
1 like
takix's avatar
Level 1

@vincent15000

I don't know how to do this here and where to integrate the codes

$admin = User::where('is_admin', true)->first();
1 like
vincent15000's avatar

@takix Have you already checked if email can be sent ? no error with the configuration ?

vincent15000's avatar

@takix I would add it inside your condition if ($create_item).

I frequently use notifications and I know that I sometime have trouble not with notifications but with the email configuration. So be sure that you email configuration is correct. Because the problem is perhaps not with notification, but with email.

takix's avatar
Level 1

@vincent15000 #### When the user writes a story, I enabled the mail to be sent with "php artisan make:mail", but this time the toastr does not work and does not send it to the homepage.

<?php

use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
use App\Mail\Hello;

/*
|--------------------------------------------------------------------------
| 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('/', [HomeController::class, 'index'])
                ->name('index');
                
Route::get('viral', [HomeController::class, 'viral'])
                ->name('viral');

Route::get('random', [HomeController::class, 'random'])
                ->name('random');

Route::get('search', [HomeController::class, 'search'])
                ->name('search');

Route::get('view/{id}/{slug}', [HomeController::class, 'show'])
                ->name('show');

Route::get('/testemail', function () {
        Mail::to(['[email protected]'])->send(new Hello);
        });
                
Route::group(['middleware' => ['auth','verified']], function () {
    
    Route::post('write', [HomeController::class, 'store'])
                ->name('store');
    
    Route::post('save_like', [HomeController::class, 'save_like'])
                ->name('save_like');
    
    Route::post('save_favorite', [HomeController::class, 'save_favorite'])
                ->name('save_favorite');
    
    Route::get('post/delete/{id}', [HomeController::class, 'delete_user_post'])
                ->name('delete_user_post');
    
    // report
    Route::get('report/{id}', [HomeController::class, 'report'])
                ->name('report');
    Route::post('write', function () {
                    Mail::to(['[email protected]'])->send(new Hello);
    });
});

require __DIR__.'/gender.php';
require __DIR__.'/points.php';
require __DIR__.'/comments.php';
require __DIR__.'/categories.php';
require __DIR__.'/pages.php';
require __DIR__.'/tags.php';
require __DIR__.'/admin.php';
require __DIR__.'/auth.php';
1 like
Snapey's avatar

You have two choices. Have a setting somewhere which tells the code who is the admin, or you check your roles and pull out all users that have admin role.

Until you say how you manage roles, its impossible to advise.

1 like

Please or to participate in this conversation.