1

I'm trying to implement a system where when a Etudiant choose a Theme, the Theme poster receives a notification that this Theme has been chosen by this Etudiant. In my case, the theme poster is a specific Utilisateur.. Their respective structures :

Utilisateur

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUtilisateursTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('utilisateurs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nom');
            $table->string('prenom');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->string('fonction');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('utilisateurs');
    }
}

Etudiant

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEtudiantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('etudiants', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('utilisateur_id')->unique();
            $table->integer('matricule');
            $table->string('grade');
            $table->string('filiere');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('etudiants');
    }
}

Theme

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateThemesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('themes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('intitule')->unique();
            $table->string('description');
            $table->string('categorie');
            $table->string('cycle');
            $table->string('filiereDesiree');
            $table->integer('themePoster_id');
            $table->string('themePoster_type');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('themes');
    }
}

In order to register all the choices of Theme an Etudiant does, I've created the table etudiantsChoixThemes with the structure below :

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEtudiantsChoixThemesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('etudiantsChoixThemes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('idEtudiant');
            $table->integer('idThematique');
            $table->string('description');
            $table->string('outils');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('etudiantsChoixThemes');
    }
}

When creating a Theme, I get the attributes of the theme poster like this

<input type="hidden" id="themePoster_id" name="themePoster_id" value= "{{Auth::guard('web')->user()->id}}">
<input type="hidden" id="themePoster_type" name="themePoster_type" value= "{{Auth::guard('web')->user()->fonction}}">

and when an Etudiant is choosing a Theme, I'm getting the values like this

<input type="hidden" name="idEtudiant" value=" {{Auth::guard('web')->user()->id}} ">
<input type="hidden" name="idThematique" value=" {{$theme->id}} "> 

in my studentChooseTheme blade view form submitted with ajax

@extends('layouts.layout')
@section('content')
<body>
{{$theme->intitule}} {{$theme->categorie}}
<div class="container_fluid">
<div class="row">
<div class="alert alert-danger print-error-msg" style="display: none;">
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display: none;">
<center></center>
</div>
</div>
</div>
<form method="post" action=" {{route('registerThemeChoice', $theme->id)}} ">
    @csrf
    <fieldset>Comment comprenez-vous la thématique proposée</fieldset>
    <input type="hidden" name="idEtudiant" value=" {{Auth::guard('web')->user()->id}} ">
    <input type="hidden" name="idThematique" value=" {{$theme->id}} ">
    <textarea name="description" required>{{old('description')}}</textarea>
    <fieldset>Quels outils comptez-vous utiliser pour mener à bien le projet?</fieldset>
    <textarea name="outils" required>{{old('outils')}}</textarea>
    <input class="button-info" type="submit" name="submit" id="submit" value="Valider">
</form>
    <a  href=" {{url('themes/' .$theme->id)}} "><button class="button-danger">Annuler</button></a>

Thématique postée par {{ $themePoster_id }} {{$userThemePoster->prenom}} {{$userThemePoster->nom}}
</body>
@jquery
<script type="text/javascript">
    $(function(){

        $('#submit').on('click', function(e){
            e.preventDefault();
            var _token = $("input[name='_token']").val();
            var idEtudiant = $('input[name=idEtudiant]').val();
            var idThematique = $('input[name=idThematique]').val();
            var description = $('textarea[name=description]').val();
            var outils = $('textarea[name=outils]').val();

                var textareasbothnotEmpty = (description != '' && outils!='');

                if (textareasbothnotEmpty){
                var c = confirm('Confirmez-vous les informations entrées?');
                if(c){
                $.ajax({
                    url: "{{route('registerThemeChoice',$theme->id)}}",
                    type: 'POST',
                    data: {
                        _token:_token,
                        idEtudiant:idEtudiant,
                        idThematique:idThematique,
                        description:description,
                        outils:outils
                    },
                    success: function(data){
                        if($.isEmptyObject(data.error)){
                            // alert(data.success);
                            $('.print-error-msg').css('display','none');
                            toastr.success(" Votre choix est enregistré ");
                        }
                        else{
                            // console.log(data.error);
                            printErrorMsg(data.error);
                        }
                    }
                });
                }
                else{
                    // alert('Annulé');
                }
                }


        function printErrorMsg (msg) {

            $(".print-error-msg").find("ul").html('');

            $(".print-error-msg").css('display','block');

            $.each( msg, function( key, value ) {

                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');

            });

        }
        });
    });
</script>
@endsection

This is to have a prealable better understanding of my database and what I'm trying to do..

Well, my issue here is with the Notifications in the way I stated above. I'm trying to do Database Notifications. I've followed the doc and another tutorials 1 2 but ain't really getting totally the whole thing. I've followed the steps, did the migration of the notifications table, create the notification file and set things up in the controller :

StudentChoosedThemeNotification

<?php

namespace App\Notifications;

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

class StudentChoosedThemeNotification extends Notification
{
    use Queueable;
    protected $EtudiantsChoixTheme

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($EtudiantsChoixTheme)
    {
        $this->EtudiantsChoixTheme = $EtudiantsChoixTheme;
    }

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

    // /**
    //  * 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 toDatabase($notifiable)
    {
        return [
            'EtudiantsChoixTheme' => $this->EtudiantsChoixTheme,
        ];
    }
}

studentChooseThemeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Theme;
use App\Utilisateur;
use App\EtudiantsChoixTheme;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Notifications\StudentChoosedThemeNotification;

class studentChooseThemeController extends Controller
{
    public function index($id){
        $theme = Theme::findOrFail($id);
        $themePoster_id = $theme->themePoster_id;
        $userThemePoster = Utilisateur::where('id', '=', $themePoster_id)->first();
        return view('studentChooseTheme', compact('theme', 'themePoster_id', 'userThemePoster'));
    }

    public function etudiantChoixTheme(Request $request, $id){
        // $theme = Theme::findOrFail($id);
        $validator = Validator::make($request->all(),[
            'description' => 'required',
            'outils' => 'required',
            'idThematique' => Rule::unique('etudiantsChoixThemes')->where(function ($query) {
                return $query->where('idEtudiant', request('idEtudiant'))
                    ->where('idThematique', request('idThematique'));
            })
        ]);

        if ($validator->fails()) {

        return response()->json(['error'=>$validator->errors()->all()]);

        }
        $etudiantChoixTheme = new EtudiantsChoixTheme;
        $etudiantChoixTheme->idEtudiant = $request->input('idEtudiant');
        $etudiantChoixTheme->idThematique = $request->input('idThematique');
        $etudiantChoixTheme->description = $request->input('description');
        $etudiantChoixTheme->outils = $request->input('outils');
        $etudiantChoixTheme->save();

        $choosenTheme = Theme::where('id', '=', $etudiantChoixTheme->idThematique)->first();
        $userPoster = Utilisateur::where('id', '=', $choosenTheme->themePoster_id)->first();

        $EtudiantsChoixTheme = [
            'text' => 'Un étudiant a choisi son theme'
        ];

        Notification::send($userPoster, new StudentChoosedThemeNotification($EtudiantsChoixTheme));
    }
}

But when I submit I don't get a new notification instance recorded in the database as it should I think and I'm not having anymore the Toastr success message from the studentChooseTheme it should send although it records the choice. Am I doing something wrong there ? This is my first time using notifications with laravel. Your help or clarification about the thing would be very appreciated

1 Answer 1

2

Check if the notifications are getting queued, then you may have to run the queue server

php artisan queue:work
Sign up to request clarification or add additional context in comments.

3 Comments

@S K R how do i check that..? My StudentChoosedThemeNotification file use use Illuminate\Contracts\Queue\ShouldQueue; and Queueable. Is there another way to check if notifications are actually queued?
And please, is it like ..an absolute necessity to Queue notifications in Laravel before getting them to work
follow this documentation thoroughly. It gives step by step procedure to implement queue, execution. laravel.com/docs/5.8/queues You can check the queues in the database queue table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.