How to set current language in Laravel notification - php

I want to translate the notification email when a user is registering but it's always the default language that is sent. I have CustomEmailVerificationNotification class that is overwriting the default vendor / SendEmailVerificationNotification.
This project is using laravel-localization package.
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class CustomEmailVerificationNotification extends Notification
{
/**
* The callback that should be used to create the verify email URL.
*
* #var \Closure|null
*/
public static $createUrlCallback;
/**
* The callback that should be used to build the mail message.
*
* #var \Closure|null
*/
public static $toMailCallback;
/**
* Get the notification's channels.
*
* #param mixed $notifiable
* #return array|string
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$verificationUrl = $this->verificationUrl($notifiable);
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
}
return $this->buildMailMessage($verificationUrl);
}
/**
* Get the verify email notification mail message for the given URL.
*
* #param string $url
* #return \Illuminate\Notifications\Messages\MailMessage
*/
protected function buildMailMessage($url)
{
return (new MailMessage)
->greeting(Lang::get('custom_email_verification_notification_greeting'))
->subject(Lang::get('custom_email_verification_notification_subject'))
->line(Lang::get('custom_email_verification_notification_line_one'))
->action(Lang::get('custom_email_verification_notification_action'), $url)
->line(Lang::get('custom_email_verification_notification_line_two'));
}
/**
* Get the verification URL for the given notifiable.
*
* #param mixed $notifiable
* #return string
*/
protected function verificationUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable);
}
return URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
}
/**
* Set a callback that should be used when creating the email verification URL.
*
* #param \Closure $callback
* #return void
*/
public static function createUrlUsing($callback)
{
static::$createUrlCallback = $callback;
}
/**
* Set a callback that should be used when building the notification mail message.
*
* #param \Closure $callback
* #return void
*/
public static function toMailUsing($callback)
{
static::$toMailCallback = $callback;
}
}
I tried to add preferredLocale like they do in documentation:
use Illuminate\Contracts\Translation\HasLocalePreference;
class User extends Authenticatable implements MustVerifyEmail, HasLocalePreference
{
public function preferredLocale()
{
return $this->locale;
}
public function sendEmailVerificationNotification()
{
$this->notify(new CustomEmailVerificationNotification);
}
}
and then in notification to make $notificable->locale but its empty.

Try this option:
use Illuminate\Contracts\Translation\HasLocalePreference;
class User extends Model implements HasLocalePreference{
/**
* Get the user's preferred locale.
*
* #return string
*/
public function preferredLocale() {
return $this->locale;
}
}

Related

I am getting 500 server error while using database notification in laravel

this is my error
this is my code
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class VehicleRequestNotification extends Notification {
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
protected $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* 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 toArray($notifiable)
{
return [
'data' => $this->data
];
} }

Entity showing problems in symfony

I'm creating a little QA app. I've got Entity Answer which is related to User and Question. I am trying to make a creating form for Answer. I am able to show the list of all the answers, but when it comes to creating a new, there is a problem.
the error
Here is my AnswerEntity code:
namespace App\Entity;
use App\Repository\AnswerRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=AnswerRepository::class)
* #ORM\Table(name="answers")
*/
class Answer
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $answer_text;
/**
* #ORM\ManyToOne(targetEntity=Question::class, inversedBy="answer")
* #ORM\JoinColumn(nullable=false)
*/
private $question;
public function getId(): ?int
{
return $this->id;
}
public function getAnswerText(): ?string
{
return $this->answer_text;
}
public function setAnswerText(string $answer_text): void
{
$this->answer_text = $answer_text;
}
public function getQuestion(): ?Question
{
return $this->question;
}
public function setQuestion(?Question $question): void
{
$this->question = $question;
}
}
and the code for AnswerForm
/**
* Answer type.
*/
namespace App\Form;
use App\Entity\Answer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class AnswerType.
*/
class AnswerType extends AbstractType
{
/**
* Builds the form.
*
* This method is called for each type in the hierarchy starting from the
* top most type. Type extensions can further modify the form.
*
* #see FormTypeExtensionInterface::buildForm()
*
* #param \Symfony\Component\Form\FormBuilderInterface $builder The form builder
* #param array $options The options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add(
'AnswerText',
TextType::class,
[
'label' => 'label_answertext',
'required' => true,
'attr' => ['max_length' => 200],
]
);
}
/**
* Configures the options for this type.
*
* #param \Symfony\Component\OptionsResolver\OptionsResolver $resolver The resolver for the options
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => Answer::class]);
}
/**
* Returns the prefix of the template block name for this type.
*
* The block prefix defaults to the underscored short class name with
* the "Type" suffix removed (e.g. "UserProfileType" => "user_profile").
*
* #return string The prefix of the template block name
*/
public function getBlockPrefix(): string
{
return 'answer';
}
}
and also Answer Controller
/**
* Answer Controller
*/
namespace App\Controller;
use App\Entity\Answer;
use App\Entity\Question;
use App\Form\AnswerType;
use App\Repository\AnswerRepository;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Flex\PackageFilter;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class AnswerController.
*
* #Route("/answer")
*/
class AnswerController extends AbstractController
{
private $answerRepository;
private $answer;
private $paginator;
/**
* AnswerController constructor
*
* #param \App\Repository\AnswerRepository $answerRepository Answer Repository
* #param \Knp\Component\Pager\PaginatorInterface $paginator
*/
public function __construct(AnswerRepository $answerRepository, PaginatorInterface $paginator)
{
$this->answerRepository = $answerRepository;
$this->paginator = $paginator;
}
/**
* Index action.
*
* #param \Symfony\Component\HttpFoundation\Request $request HTTP request
* #return \Symfony\Component\HttpFoundation\Response HTTP response
*
* #Route(
* "/",
* methods={"GET"},
* name="answer_index",
* )
*/
public function index(Request $request, PaginatorInterface $paginator, AnswerRepository $answerRepository): Response
{
$pagination = $paginator->paginate(
$answerRepository->queryAll(),
$request->query->getInt('page', 1),
AnswerRepository::PAGINATOR_ITEMS_PER_PAGE
);
return $this->render(
'answer/index.html.twig',
['pagination' => $pagination]
);
}
/**
* Create action.
*
* #param \Symfony\Component\HttpFoundation\Request $request HTTP request
*
* #param \App\Repository\AnswerRepository $answerRepository Answer repository
* #param \App\Entity\Answer $answer Answer Entity
*
* #return \Symfony\Component\HttpFoundation\Response HTTP response
*
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*
* #Route(
* "/create",
* methods={"GET", "POST"},
* name="answer_create",
* )
*/
public function create(Request $request, AnswerRepository $answerRepository, Answer $answer): Response
{
$answer = new Answer();
$form = $this->createForm(AnswerType::class, $answer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$answerRepository->save($answer);
$this->addFlash('success', 'answer_created_successfully');
return $this->redirectToRoute('question_index');
}
return $this->render(
'answer/create.html.twig',
['form' => $form->createView()]
);
}
}
And also, the questions is.., how to route answer/create to make it the answer to the question? I mean, I've localhost/question/{questionid} and I want to create the question here.
Thanks for your help!
Your error is a ParamConverter error. In your controller you ask symfony to give you an Answer $answer but it cannot provide it because there's no way to do it. you don't need this param in your controller's method.
Also I doubt your AnswerType will work since your property is named answer_text and your field is named AnserText. They must match.

Laravel Notification with Mailable

In my Laravel application I have a Notification that sends a Mailable when a User is deleted.
The 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\User;
use App\Mail\UserDeleted as UserDeletedEmail;
class UserDeleted extends Notification implements ShouldQueue
{
use Queueable;
/**
* The user instance being passed to the notification
*
* #var User $user
*/
protected $user;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new UserDeletedEmail($notifiable, $this->user));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'user_id' => $this->user['id'],
'user_username' => $this->user['username'],
'user_email' => $this->user['email'],
'user_full_name' => $this->user['full_name'],
];
}
}
In this case $notifiable is an instance of User but soo is $user as this is the user that has been deleted.
The Mailable looks like this:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Spatie\Permission\Models\Role;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
class UserDeleted extends Mailable
{
use Queueable, SerializesModels;
/**
* The order instance.
*
* #var User
*/
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this
->to($this->user->email)
->subject("{$this->user->full_name} been deleted from the Citibase Intranet")
->markdown('mail.user-deleted');
}
}
The issue is, as they're both instances of User I'm effectively passing the wrong instance in the subject line.
Everything is triggered through the UserObserver.
/**
* Handle the user "deleted" event.
*
* #param \App\User $user
* #return void
*/
public function deleted(User $user)
{
Log::notice("A user has been deleted: {$user->full_name} by " . optional(auth()->user())->full_name ?? "System");
User::role(['admin'])->get()
->each->notify(
(new UserDeleted($user))->delay(now()->addSeconds(10))
);
}
At the moment your UserDeleted mailables constructor is only accepting the user that should receive the email, you can add the other user as well and you will have access to both.
Something like this:
class UserDeleted extends Mailable
{
use Queueable, SerializesModels;
/**
* #var User
*/
public $admin;
/**
* #var User
*/
public $deletedUser;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $admin, User $deletedUser)
{
$this->admin = $admin;
$this->deletedUser = $deletedUser;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this
->to($this->admin->email)
->subject("{$this->deletedUser->full_name} been deleted from the Citibase Intranet")
->markdown('mail.user-deleted');
}
}

Google+ authentication with FOSUserBundle

i was learning OAuth2 in order to login an account with Google+ , Facebook, etc. on a web site.
I have followed a tutorial about it, and i have an issue when i clicked on my button "Connect with Google+" :
In the tutorial, he created a User.php but i had already one with FOS User.
Here is my code :
User.php :
<?php
// src/AppBundle/Entity/User.php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $nom;
/**
* #ORM\Column(type="string")
*/
protected $prenom;
/**
* #ORM\Column(type="string")
*/
protected $nationalite;
/**
* #ORM\Column(type="datetime")
*/
protected $birthday;
/**
* #ORM\Column(type="string")
*/
protected $sexe;
/**
* #ORM\OneToOne(targetEntity="App\Entity\AnnonceColocation", mappedBy="User", cascade={"persist", "remove"})
*/
private $annonceColocation;
/**
* #ORM\OneToOne(targetEntity="App\Entity\AnnonceColocataire", mappedBy="User", cascade={"persist", "remove"})
*/
private $annonceColocataire;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="expediteur", orphanRemoval=true)
*/
private $sendMessage;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="destinataire", orphanRemoval=true)
*/
private $receivedMessage;
public function __construct()
{
parent::__construct();
$this->sendMessage = new ArrayCollection();
$this->receivedMessage = new ArrayCollection();
// your own logic
}
/**
* #return mixed
*/
public function getNom()
{
return $this->nom;
}
/**
* #param mixed $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* #return mixed
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* #param mixed $prenom
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
}
public function getNationalite()
{
return $this->nationalite;
}
/**
* #param mixed $nationalite
*/
public function setNationalite($nationalite)
{
$this->nationalite = $nationalite;
}
public function getBirthday()
{
return $this->birthday;
}
/**
* #param mixed $birthday
*/
public function setBirthday($birthday)
{
$this->birthday = $birthday;
}
public function getSexe()
{
return $this->sexe;
}
/**
* #param mixed $sexe
*/
public function setSexe($sexe)
{
$this->sexe = $sexe;
}
public function getPicture()
{
return $this->picture;
}
/**
* #param mixed $picture
*/
public function setPicture($picture)
{
$this->picture = $picture;
}
public function getAnnonceColocation(): ?AnnonceColocation
{
return $this->annonceColocation;
}
public function setAnnonceColocation(AnnonceColocation $annonceColocation): self
{
$this->annonceColocation = $annonceColocation;
// set (or unset) the owning side of the relation if necessary
$newUser = $annonceColocation === null ? null : $this;
if ($newUser !== $annonceColocation->getUser()) {
$annonceColocation->setUser($newUser);
}
return $this;
}
public function getAnnonceColocataire(): ?AnnonceColocataire
{
return $this->annonceColocataire;
}
public function setAnnonceColocataire(?AnnonceColocataire $annonceColocataire): self
{
$this->annonceColocataire = $annonceColocataire;
// set (or unset) the owning side of the relation if necessary
$newUser = $annonceColocataire === null ? null : $this;
if ($newUser !== $annonceColocataire->getUser()) {
$annonceColocataire->setUser($newUser);
}
return $this;
}
/**
* #return Collection|Message[]
*/
public function getSendMessage(): Collection
{
return $this->sendMessage;
}
public function addSendMessage(Message $sendMessage): self
{
if (!$this->sendMessage->contains($sendMessage)) {
$this->sendMessage[] = $sendMessage;
$sendMessage->setExpediteur($this);
}
return $this;
}
public function removeSendMessage(Message $sendMessage): self
{
if ($this->sendMessage->contains($sendMessage)) {
$this->sendMessage->removeElement($sendMessage);
// set the owning side to null (unless already changed)
if ($sendMessage->getExpediteur() === $this) {
$sendMessage->setExpediteur(null);
}
}
return $this;
}
/**
* #return Collection|Message[]
*/
public function getReceivedMessage(): Collection
{
return $this->receivedMessage;
}
public function addReceivedMessage(Message $receivedMessage): self
{
if (!$this->receivedMessage->contains($receivedMessage)) {
$this->receivedMessage[] = $receivedMessage;
$receivedMessage->setDestinataire($this);
}
return $this;
}
public function removeReceivedMessage(Message $receivedMessage): self
{
if ($this->receivedMessage->contains($receivedMessage)) {
$this->receivedMessage->removeElement($receivedMessage);
// set the owning side to null (unless already changed)
if ($receivedMessage->getDestinataire() === $this) {
$receivedMessage->setDestinataire(null);
}
}
return $this;
}
public function getRoles()
{
return array('ROLE_USER');
}
/**
* Returns the password used to authenticate the user.
*
* This should be the encoded password. On authentication, a plain-text
* password will be salted, encoded, and then compared to this value.
*
* #return string The password
*/
public function getPassword()
{
return null;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
return null;
}
/**
* Returns the username used to authenticate the user.
*
* #return string The username
*/
public function getUsername()
{
return $this->email;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
return null;
}
}
UserProvider.php :
<?php
/**
* Created by IntelliJ IDEA.
* User: mert
* Date: 12/18/17
* Time: 12:58 PM
*/
namespace App\Security;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class UserProvider implements UserProviderInterface
{
private $entityManager;
/**
* UserProvider constructor.
* #param EntityManagerInterface $entityManager
* #internal param Client $httpClient
* #internal param UserOptionService $userOptionService
* #internal param ProjectService $projectService
* #internal param SessionService $sessionService
* #internal param Session $session
* #internal param UserOptionService $userOptionsService
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* Loads the user for the given username.
*
* This method must throw UsernameNotFoundException if the user is not
* found.
*
* #param string $username The username
*
* #return UserInterface
*
* #throws \Doctrine\ORM\NonUniqueResultException
*/
public function loadUserByUsername($username)
{
return $this->entityManager->createQueryBuilder('u')
->where('u.email = :email')
->setParameter('email', $username)
->getQuery()
->getOneOrNullResult();
}
/**
* Refreshes the user.
*
* It is up to the implementation to decide if the user data should be
* totally reloaded (e.g. from the database), or if the UserInterface
* object can just be merged into some internal array of users / identity
* map.
*
* #param UserInterface $user
* #return UserInterface
*
*/
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $user;
}
/**
* Whether this provider supports the given user class.
*
* #param string $class
*
* #return bool
*/
public function supportsClass($class)
{
return $class === 'App\Security\User';
}
}
GoogleController.php :
<?php
namespace App\Controller;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class GoogleController extends AbstractController
{
/**
* Link to this controller to start the "connect" process
*
* #Route("/connect/google", name="connect_google")
* #param ClientRegistry $clientRegistry
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function connectAction(ClientRegistry $clientRegistry)
{
return $clientRegistry
->getClient('google')
->redirect();
}
/**
* Facebook redirects to back here afterwards
*
* #Route("/connect/google/check", name="connect_google_check")
* #param Request $request
* #return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
*/
public function connectCheckAction(Request $request)
{
if (!$this->getUser()) {
return new JsonResponse(array('status' => false, 'message' => "User not found!"));
} else {
return $this->redirectToRoute('default');
}
}
}
and my GoogleAuthenticator.php :
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
use League\OAuth2\Client\Provider\GoogleUser;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Created by IntelliJ IDEA.
* User: mert
* Date: 12/18/17
* Time: 12:00 PM
*/
class GoogleAuthenticator extends SocialAuthenticator
{
private $clientRegistry;
private $em;
private $router;
public function __construct(ClientRegistry $clientRegistry, EntityManagerInterface $em, RouterInterface $router)
{
$this->clientRegistry = $clientRegistry;
$this->em = $em;
$this->router = $router;
}
public function supports(Request $request)
{
return $request->getPathInfo() == '/connect/google/check' && $request->isMethod('GET');
}
public function getCredentials(Request $request)
{
return $this->fetchAccessToken($this->getGoogleClient());
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
/** #var GoogleUser $googleUser */
$googleUser = $this->getGoogleClient()
->fetchUserFromToken($credentials);
$email = $googleUser->getEmail();
$user = $this->em->getRepository('App:User')
->findOneBy(['email' => $email]);
if (!$user) {
$user = new User();
$user->setEmail($googleUser->getEmail());
$user->setFullname($googleUser->getName());
$user->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
$this->em->persist($user);
$this->em->flush();
}
return $user;
}
/**
* #return \KnpU\OAuth2ClientBundle\Client\OAuth2Client
*/
private function getGoogleClient()
{
return $this->clientRegistry
->getClient('google');
}
/**
* Returns a response that directs the user to authenticate.
*
* This is called when an anonymous request accesses a resource that
* requires authentication. The job of this method is to return some
* response that "helps" the user start into the authentication process.
*
* Examples:
* A) For a form login, you might redirect to the login page
* return new RedirectResponse('/login');
* B) For an API token authentication system, you return a 401 response
* return new Response('Auth header required', 401);
*
* #param Request $request The request that resulted in an AuthenticationException
* #param \Symfony\Component\Security\Core\Exception\AuthenticationException $authException The exception that started the authentication process
*
* #return \Symfony\Component\HttpFoundation\Response
*/
public function start(Request $request, \Symfony\Component\Security\Core\Exception\AuthenticationException $authException = null)
{
return new RedirectResponse('/login');
}
/**
* Called when authentication executed, but failed (e.g. wrong username password).
*
* This should return the Response sent back to the user, like a
* RedirectResponse to the login page or a 403 response.
*
* If you return null, the request will continue, but the user will
* not be authenticated. This is probably not what you want to do.
*
* #param Request $request
* #param \Symfony\Component\Security\Core\Exception\AuthenticationException $exception
*
* #return \Symfony\Component\HttpFoundation\Response|null
*/
public function onAuthenticationFailure(Request $request, \Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
{
// TODO: Implement onAuthenticationFailure() method.
}
/**
* Called when authentication executed and was successful!
*
* This should return the Response sent back to the user, like a
* RedirectResponse to the last page they visited.
*
*
If you return null, the current request will continue, and the user
* will be authenticated. This makes sense, for example, with an API.
*
* #param Request $request
* #param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token
* #param string $providerKey The provider (i.e. firewall) key
*
* #return void
*/
public function onAuthenticationSuccess(Request $request, \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token, $providerKey)
{
// TODO: Implement onAuthenticationSuccess() method.
}
}
Hope some of you could help on this. Thanks a lot.
Since Google plus doesn't exist anymore you need to change the Google API for the login. Check the official Google Oauth2.0 for Google APIs (https://developers.google.com/identity/protocols/googlescopes). For this you need to change the scope inside the config.yml file. Instead of "https://www.googleapis.com/auth/plus.login" you can use "https://www.googleapis.com/auth/cloud-platform" or you can use scope: "openid". That at least works for me.

Laravel notification Broadcasting 500 internal server error occurs

I am trying to broadcast a notification in laravel 5.3 when i write
public function via($notifiable)
{
return ['broadcast','database'];
}
error occurs in console 500 internal server error and when i remove broadcast error removes please help here is my notification code
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\BroadcastMessage;
class userLiked extends Notification implements ShouldBroadcast, ShouldQueue
{
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 ['broadcast','database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'status'=>'liked',
'user'=>auth()->user(),
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array|BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return new BroadcastMessage(array(
'status'=>'liked',
'user'=>auth()->user(),
));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Here is my cotroller code where i am calling notification
$like = new like();
$like->userId = $request['userId'];
$like->crushId = $request['crushId'];
$like->liked = true;
$like->save();
User::find($like->crushId)->notify(new userLiked());
And here is my user model
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function likes(){
$this->hasMany('App\like');
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* #return string
*/
public function receivesBroadcastNotificationsOn()
{
return 'user.'.$this->id;
}
}
Please help i am sick of it

Categories