Why broadcasting channel public not working? Laravel - laravel

I use laravel 5.3
I make routes/channels.php like this :
<?php
Broadcast::channel('messages', function() {
return true;
});
If I input the data cart and click submit, it will run this :
this.$http.post(window.BaseUrl + '/guest/add-notification', {cart_data: JSON.stringify(data)});
It will call function on the controller
The function like this :
public function addNotification(Request $request){
$input = $request->only('cart_data');
$data = json_decode($input['cart_data'], true);
event(new CartNotificationEvent($data));
}
Then it will call event
The event like this :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CartNotificationEvent
{
use InteractsWithSockets, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function broadcastWith()
{
return [
'message' => $this->data,
];
}
public function broadcastAs()
{
return 'newMessage';
}
public function broadcastOn()
{
return new Channel('messages');
}
}
On the client, I do like this :
Echo.channel('messages')
.listen('.newMessage', (message) => {
console.log('test')
console.log(message);
});
When all the code is executed, I check on the console, the console.log not display
Why is it not working?
If I see the whole code that I make, it seems the process is correct

class CartNotificationEvent implements ShouldBroadcast is missing.

Related

Laravel make validation request not working

When i submit the form is nothing happens.
here is my step.
php artisan make:request PostRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
public function messages()
{
return [
'title.required'=>['need title'],
'article.required'=>['need article'],
];
}
}
?>
App/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\PostRequest;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
public function store(PostRequest $request)
{
Post::create($request->all());
return redirect()->route('post.index');
}
}
?>
If i don't use PostRequest it work perfectly,like this.
app/Http/Controllers/PostController.php
public function store(Request $request)
{
$post=new Post;
$post->user_id=Auth::user()->id;
$post->title=$request->title;
$post->article=$request->article;
$post->image=$request->image;
$post->save();
return redirect()->route('post.index');
}
And i missing something step?
Thanks everyone.
Your rules() function has a return array.
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
Change it to
public function rules()
{
return [
'title'=>'required|max:255',
'article'=>'required',
'image'=>'image'
];
}

laravel:send notification with (data) when update a record

Problem: how can I display data with update function?
the notification is sent but witout data that I specified in this function :
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
it works with store function but it dosn't with update function
my notification class:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Booking;
class NewMessage extends Notification
{
use Queueable;
public $booking;
public function __construct(Booking $booking)
{
//
$this->booking = $booking;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
my update function :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Booking;
use App\User;
use Notification;
use App\Notifications\NewMessage;
class DispoController extends Controller
{
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
it shows just "new booking"
#foreach(Auth::user()->unreadNotifications as $not)
<li>
<a class="dropdown-item" >new booking {{$not->data['data']}}</a>
</li>
#endforeach
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage(Booking::findOrFail($id)));
// notification
return redirect()->route('info_client.index')->with(['success'=>'succés']);
}
The issue is your not capturing the saved booking, should be like so
public function update(Request $request,$id,Booking $booking)
{
//
$booking = Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So your passing in an empty booking from the function call and passing that to the notification and not the updated record.
But you can simplify the whole thing by doing this
public function update(Request $request, Booking $booking)
{
//
$booking->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So instead of passing both id and booking just pass in the booking which should automatically be found from the Route and container.

How to implement event/listeners with repository pattern in laravel 5.4

I can't make listeners trigger action update, create or delete when I user patter repository.
Addionally I have added my code in order to help my to solve my problem.
TicketController.php
namespace App\Http\Organizer\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Events\Contracts\IEvent;
use App\Entities\Event;
class TicketController extends Controller
{
protected $IEvent;
public function __construct( IEvent $IEvent )
{
$this->IEvent = $IEvent;
}
public function checkFutbolType ($activityId)
{
// I need to listen this action here
$event = $this->IEvent->update(21927, ['title'=>'new title']);
}
}
My RepoEvent.php:
<?php
namespace App\Http\Events\Repositories;
use App\Http\Events\Contracts\IEvent
;
class RepoEvent implements IEvent
{
protected $model;
public function __construct($model)
{
$this->model = $model;
}
public function update($activityId, $params)
{
return $this->model->where('id', $activityId)->update($params);
}
}
My AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Entities\Event;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//event: creating
Event::creating(function (Event $event) {
return $event->creatingEvent();
});
//event: saving
Event::saving(function (Event $event) {
return $event->savingEvent();
});
//event: updating
Event::updating(function (Event $event) {
return $event->updatingEvent();
});
}
}
My interface IEvent.php:
<?php
namespace App\Http\Events\Contracts;
interface IEvent
{
public function update($activityId, $params);
}
My ServicesOrchestration.php:
<?php
namespace App\Http\Administration\Providers;
use App\Entities\Event;
use App\Http\Administration\Repositories\RepoEvent;
use Illuminate\Support\ServiceProvider;
class ServicesOrchestration extends ServiceProvider
{
public function boot()
{
}
public function register()
{
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(new Event());
});
}
}
My model Event.php
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function creatingUser() {
\Log::info('creating event');
}
public function savingUser() {
\Log::info('saving event');
}
public function updatingUser() {
\Log::info('updating event');
}
}
thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance
Here's the relevant snipped from the docs (scroll to mass updates):
When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.
For your code to work you need to first retrieve the actual model instance like below:
public function update($activityId, $params)
{
$instance = $this->model->find($activityId);
$instance->fill($params);
$instance->save();
}
This will have an additional cost of doing two queries instead of one and only being able to update a single model at a time.
A sidenote: You're passing a model instance to the repository but what you actually want is to pass a query builder instance:
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(Event::query());
});

Why mail laravel not working on the staging server?

I try on the my localhost, it works
But if I try on the staging server, it does not works
My controller like this :
<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderReceivedMail;
...
class PurchaseController
{
...
public function test() {
$order = $this->order_repository->find(416);
$user = $this->user_repository->find(1);
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
}
}
My mail like this :
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $order;
public $store;
public function __construct($order, $store)
{
$this->order = $order;
$this->store = $store;
$this->subject('subject');
}
public function build()
{
$mail_company = explode(',',config('app.mail_company'));
// dd($mail_company, $this->order->number, $this->store->name, 'test');
return $this->view('vendor.notifications.mail.email-order',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($mail_company);
}
}
I try add this :
dd($mail_company, $this->order->number, $this->store->name, 'test');
on the mail
If in my localhost, the result of dd show
But if in the staging server, the result of dd not show
Seems if the staging server, it does not run this statement :
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
How can I solve this problem?
open config/mail.php, .env files and set your email driver as mail as bellow,
'driver' => env('MAIL_DRIVER', 'mail'), //you must set it in env file too
then you can send emails like bellow, note that emails.admin.member, is the path to your email template, in the example code, laravel will look for a blade template in the path, resources\views\emails\admin\member.blade.php
Mail::queue('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});
or
Mail::send('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});

Map Eloquent event to a dedicated class in Laravel does not work

I am trying to catch in Laravel 5.5 the eloquent.created event when a Post model is created, but for any reason it does not work. It looks like the event/listener mapping that is defined inside the EventServiceProvider.php does not work. My setup is as follows.
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\NotifyBlogSubscribers',
]
];
public function boot()
{
parent::boot();
//
}
}
NotifyBlogSubscribers.php listener
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyBlogSubscribers
{
public function __construct()
{
//
}
public function handle(PostWasPublished $event)
{
dd('Inside NotifyBlogSubscribers');
}
}
PostWasPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
dd('Inside PostWasPublished');
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Post.php
<?php
namespace App\Models;
use App\Events\PostWasPublished;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $events = [
'created' => PostWasPublished::class,
];
protected $fillable = ['user_id', 'title', 'body'];
public function comments() {
return $this->hasMany(Comment::class);
}
public function addComment($body) {
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function user() {
return $this->belongsTo('App\User');
}
public function scopeFilter($query, $filters) {
if (array_key_exists('month', $filters)) {
$month = $filters['month'];
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if (array_key_exists('year', $filters)) {
$year = $filters['year'];
$query->whereYear('created_at', $year);
}
}
public static function archives() {
return static::selectRaw('year(created_at) as year, monthname(created_at) as month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
How do I test?
My first approach is to use tinker in the following way:
>>> App\Models\Post::create(['user_id' => '1', 'title' => 'some title', 'body' => 'lorem ipsum'])
=> App\Models\Post {#732
user_id: "1",
title: "some title",
body: "lorem ipsum",
updated_at: "2017-08-07 05:06:32",
created_at: "2017-08-07 05:06:32",
id: 62,
}
Also, when I create a post in the front-end it does not run into the dd() methods.
Also composer dump-autoload, php artisan clear-compiled or php artisan optimize did not do the trick. Any idea what I am doing wrong?
In Laravel 5.5 you will need to define a $dispatchesEvents property instead of a $events property. ($events was used in older Laravel versions).

Resources