Уведомления базы данных Laravel не отправляются - PullRequest
0 голосов
/ 07 июля 2019

Я пытаюсь внедрить систему, в которой когда Etudiant выбирает Theme, плакат Theme получает уведомление о том, что этот Theme был выбран этим Etudiant.В моем случае тематический плакат представляет собой конкретную Utilisateur .. Их соответствующие структуры :

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');
    }
}

Чтобы зарегистрировать все варианты Theme и Etudiant, я создал таблицу etudiantsChoixThemes со структурой ниже:

<?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');
    }
}

При создании Theme я получаю атрибуты плаката с темой, как этот

<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}}">

, а когда Etudiant выбирает Theme, я получаюзначения, подобные этому

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

в моей studentChooseTheme форме представления блэйда, отправленной с помощью 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

Это должно иметь предварительное лучшее понимание моей базы данных и того, что я пытаюсьчтобы сделать ..

Ну, моя проблема здесь с Уведомлениями, как я изложил выше.Я пытаюсь сделать уведомления базы данных.Я следовал doc и другим учебникам 1 2 , но на самом деле не понимаю полностью.Я выполнил шаги, выполнил миграцию таблицы notifications, создал файл уведомлений и настроил его в контроллере:

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));
    }
}

Но когда я отправляю, я не получаю новый экземпляр уведомления, записанный в базе данных, как мне кажется, и у меня больше нет сообщения об успехе Toastr из studentChooseTheme, которое он должен отправитьхотя это фиксирует выбор.Я что-то там не так делаю?Я впервые использую уведомления с laravel.Буду очень признателен за вашу помощь или разъяснение о вещи

1 Ответ

0 голосов
/ 07 июля 2019

Проверьте, поступают ли уведомления в очередь, тогда вам, возможно, придется запустить сервер очередей

php artisan queue:work
...