Where to add parameter to Route: verification.notice {language}/email/verify - laravel-blade

Missing required parameters for [Route: verification.notice] [URI: {language}/email/verify]
I added the laravel email verification to my project, after using localization.
But now I have the problem that the Route: verification.notice is missing a parameter. I know that I need to add/pass the app()->getLocale() parameter to the route but can't find where
I tried searching all the routes and the URLs in the project and also checked the VerificationController.php and the verify.blade.php. But I didn't find the route with the missing parameter. Also, I couldn't find someone else online with the same problem.
web.php
Route::group([
'prefix' => '{language}',
'where' => ['{language}' => '[a-Za-Z]{2}'],
'middleware' => 'SetLanguage',
],
function () {
Route::get('/', function () {
return view('welcome');
})->name('Welcome');
Auth::routes(['verify' => true]);
Route::get('/home', 'HomeController#index')->name('home');
Route::namespace('User')->group(function () {
Route::get('/profile', 'UserController#editProfile')->name('profile');
Route::put('profile', 'UserController#updateProfile');
});
Route::namespace('Admin')->group(function () {
Route::get('/dashboard', 'AdminController#index')->name('dashboard');
});
});
UserController
class UserController extends Controller
{
public function __construct()
{
$this->middleware('verified');
}
public function editProfile()
{
$user = User::where('id', Auth()->user()->id)->first();
return view('user.profile', compact('user'));
}
}
----edit----
SetLanguage.php
namespace App\Http\Middleware;
use App;
use Closure;
class SetLanguage
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
App::setLocale($request->language);
return $next($request);
}
}

Simply : override the middleware: EnsureEmailIsVerified
Create a new middleware with same name and insert : app()->getLocale();
public function handle($request, Closure $next, $redirectToRoute = null)
{
if (! $request->user() ||
($request->user() instanceof MustVerifyEmail &&
! $request->user()->hasVerifiedEmail())) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
: Redirect::route($redirectToRoute ?: 'verification.notice', app()->getLocale());
}
return $next($request);
}
Modify App\Http\Kernel.php and replace :
\Illuminate\Auth\Middleware\EnsureEmailIsVerified
by
\App\Http\Middleware\EnsureEmailIsVerified::class
Finally, you can have also a problem with the verification.verify route
Override this route with a new notification class like this :
Note : URL::temporarySignedRoute can pass parameters like language
<?php
namespace App\Notifications;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Config;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class VerifyEmail extends Notification
{
/**
* 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 (new MailMessage)
->subject(Lang::get('Activer mon compte client'))
->line(Lang::get('Veuillez cliquer sur le bouton ci-dessous pour activer votre compte client.'))
->action(Lang::get('Activer mon compte client'), $verificationUrl)
->line(Lang::get('Si vous n\'avez pas demandé la création d\'un compte client '.config('app.name').', ignorez simplement cet e-mail.'));
}
/**
* Get the verification URL for the given notifiable.
*
* #param mixed $notifiable
* #return string
*/
protected function verificationUrl($notifiable)
{
return URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'language' => app()->getLocale(),
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
}
/**
* 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;
}
}
And add the declaration into user model :
// OVERRIDE
/**
* Send email verification.
* #call function
*/
public function sendEmailVerificationNotification() {
$this->notify(new VerifyEmail);
}

I faced the same problem before like yours.
As you said you didn't add {language}/ before the some path in your views
check your path in all view and alter it to be like this:
href="{{ route('somePath', app()->getLocale() ) }}"
make sure to alter all the pages to contain the correct path with language prefix in your views.

The workaround is to leave it as it is, but change only url to "after verification" page.
You can do it by storing user's locale while creating new user and then in VerificationController in verify method you do sth like:
$this->redirectTo = ($user->locale == 'pl') ? 'https://example.net/pl/dziekujemy' : 'https://example.net/en/thank-you';

Related

Laravel 5.8 Custom Email and password Columns

I have a WordPress running application, which I would like to access using a separate interface that uses Laravel 5.8.(don't worry about the hashing)
As such, instead of cloning passwords back and forth, I would like to use the user_email and user_pass columns in the Laravel User model instead.
I have tried what the official docs say :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*
* #param \Illuminate\Http\Request $request
*
* #return Response
*/
public function authenticate(Request $request)
{
$credentials = $request->only('user_email', 'user_pass');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
I then edited the blade files, but no avail. Any pointers?
Laravel provides a way to change the default columns for auth (email, password) by overriding some functions.
In your User model add this function that overrides the default column for password:
App/User.php
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->user_pass;
}
And, in your LoginController change from email to user_email
App/Http/Controllers/Auth/LoginController.php
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'user_email';
}
Now you have overridden the default columns used by Laravel's Auth logic. But you are not finished yet.
LoginController has a function that validates the user's input and the password column is hardcoded to password so in order to change that, you also need to add these functions in LoginController:
App/Http/Controllers/Auth/LoginController.php
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'user_pass' => 'required|string',
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'user_pass');
}
Next step is to create a custom Provider, let's call it CustomUserProvider that will be used instead of the default one EloquentUserProvider and where you will override the password field.
App/Providers/CustomUserProvider.php
<?php
namespace App\Providers;
class CustomUserProvider extends EloquentUserProvider
{
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('user_pass', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'user_pass')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['user_pass'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
}
Now that you extended the default provider you need to tell Laravel to use this one instead of EloquentUserProvider. This is how you can do it.
App/Providers/AuthServiceProvider.php
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
$this->app->auth->provider('custom', function ($app, $config) {
return new CustomUserProvider($app['hash'], $config['model']);
});
}
Finally update the config information config/auth.php and change the driver from eloquent to custom (that's how I named it above; you can change it to whatever you want). So the config/auth.php file should have this bit:
'providers' => [
'users' => [
'driver' => 'custom',
'model' => App\User::class,
],
],
Hope it helps!
Regards
It would be up and working, If you can just use sessions here instead of using Auth::attempt just like working on core PHP.

Trying Multiple User Auth, it keep saying wrong instance of argument passed

I'm getting this error while trying to log in multiple users with guards and unable to understand what instance it needs to be passed:
Argument 1 passed to
Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an
instance of Illuminate\Contracts\Auth\Authenticatable, instance of
App\Employs given, called in /var/www/html/crmproject/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php on line 379
This is my Auth Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class EmploysLoginController extends Controller
{
use AuthenticatesUsers;
protected $guard = 'Employs';
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/Employs';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('auth.employe-login');
}
public function login(Request $request)
{
if (auth()->guard('Employs')->attempt(['email' => $request->email, 'password' => $request->password])) {
dd(auth()->guard('Employs')->user());
}
return back()->withErrors(['email' => 'Email or password are wrong.']);
}
}
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
// use Illuminate\Contracts\Auth\Authenticatable as
AuthenticatableContract;
class Employs extends Model// implements AuthenticatableContract
{
protected $primaryKey = 'employ_id';
}
i tried many solution provided online/stackoverflow but i'm constantly getting this error, and if you find this question has ambiguity please ask before doing down vote i'm trying this out last time here.
You should create a model like this:
Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Employs extends Authenticatable
{
use Notifiable;
protected $guard = 'Employs';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
I hope this work for you.

Laravel - Emails not including data when sent via Queue

I'm trying to set up a Contact Form and all is going well. Set up my Controller with ->send(), all works fine (takes a bit of time). When I set it up to work with ->queue(), seems to work fine (no delay), job is set up, mail is sent when I dispatch. But this time my mail template does not include the data sent to the Mailer.
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\Contact;
use Illuminate\Support\Facades\Mail;
class PagesController extends Controller
{
public function sendContact(Request $request)
{
Mail::to('webform#email.com')
->queue(new Contact($request));
return redirect('/contact')->with('status', 'Message sent. Thanks!');
}
}
My Mailer (App\Mail\Contact):
class Contact extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
}
/**
* Build the message.
*
* #return $this
*/
public function build(Request $request)
{
$subject = 'Web Message from: ' . $request->name;
return $this->from('myemail#email.com')
->subject($subject)
->view('emails.contact-template')
->with([
'name' =>$request->name,
'email' => $request->email,
'message' => $request->message,
'date' => $request->date,
]);
}
}
The problem was that I needed to declare the variables as public. Below is the solution that eventually worked:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Http\Request;
use Illuminate\Contracts\Queue\ShouldQueue;
class Contact extends Mailable
{
use Queueable, SerializesModels;
public $request;
public $name;
public $from;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(Request $request)
{
$this->request = $request->all();
$this->name = $request->name;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$subject = 'Webform messsage from: ' . $this->name;
$from = 'webform#mail.com';
return $this
->from( $from )
->subject($subject)
->view('emails.contact-template');
}
}

am new with symfony and i need some advices

I have a problem regarding a Symfony application, I want to take as input the "username" or "id" for my controller , and receive information that is in my table "user" and also 2 other table for example : A user has one or more levels , and also it has points must earn points to unlock a level , I want my dan Home page display the username and the level and extent that it has , I jn am beginner and not come to understand the books symfony that I use, I work with PARALLEL " symfony_book " and " symfony_cook_book " and also tutorial youtube May I blocks , here is the code for my cotroler
"
/**
* #Route("/{id}")
* #Template()
* #param $id=0
* #return array
*/
public function getUserAction($id)
{
$username = $this->getDoctrine()
->getRepository('voltaireGeneralBundle:FosUser')
->find($id);
if (!$username) {
throw $this->createNotFoundException('No user found for id '.$id);
}
//return ['id' => $id,'username' => $username];
return array('username' => $username);
}
and I have to use the relationship among classes
use Doctrine\Common\Collections\ArrayCollection;
class Experience {
/**
* #ORM\OneToMany(targetEntity="FosUser", mappedBy="experience")
*/
protected $fosUsers;
public function __construct()
{
$this->fosUsers = new ArrayCollection();
}
}
and
class FosUser {
/**
* #ORM\ManyToOne(targetEntity="Experience", inversedBy="fosUsers")
* #ORM\JoinColumn(name="experience_id", referencedColumnName="id")
*/
protected $fosUsers;
}
and i have always an error
In Symfony you cannot return an array in Action function!, Action function must always return a Response object...So if you want to return data to browser in Symfony, Action function have to return a string wrapped up in Response object.
In your controller code, to return the array to browser, You can serialize an array to JSON and send it back to browser:
public function getUserAction($id)
{
$username = $this->getDoctrine()
->getRepository('voltaireGeneralBundle:FosUser')
->find($id);
if (!$username) {
throw $this->createNotFoundException('No user found for id '.$id);
}
return new Response(json_encode(array('username' => $username)));
}
I suggest you to read more about HTTP protocol , PHP, and Symfony.

Inserting a form into a block in Drupal?

Is there any command or method that I can use to insert the contents of a form (e.g. the user registration form) into a block?
In Drupal 7, it looks like this:
function yourmodule_block_view($delta='')
{
switch($delta) {
case 'your_block_name':
$block['subject'] = null; // Most forms don't have a subject
$block['content'] = drupal_get_form('yourmodule_form_function');
break;
}
return $block;
}
The form array returned by drupal_get_form will be automatically rendered.
yourmodule_form_function is a function (in your module or an existing Drupal module) that returns the form array;
drupal_get_form($form_id) - put it in a module's hook_block ($op=='view') or even... shudder... inside a block with PHP filter on.
You need to find the form id first - look for a hidden input with the name form_id within the form. Its value should be the the form id.
Also, you could simply use the Form Block module.
Drupal 8+ solution
Create the form. Then, to create the block use something like this:
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\my_module\Form\MyForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides the My Block block.
*
* #Block(
* id = "my_block",
* admin_label = #Translation("My Block")
* )
*/
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The form builder.
*
* #var \Drupal\Core\Form\FormBuilder
*/
protected $formBuilder;
/**
* Constructs a new MyBlock object.
*
* #param array $configuration
* A configuration array containing information about the plugin instance.
* #param string $plugin_id
* The plugin_id for the plugin instance.
* #param mixed $plugin_definition
* The plugin implementation definition.
* #param \Symfony\Component\DependencyInjection\ContainerInterface $container
* Our service container.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ContainerInterface $container) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->formBuilder = $container->get('form_builder');
}
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container
);
}
/**
* {#inheritdoc}
*/
public function build() {
$form = $this->formBuilder->getForm(MyForm::class);
return $form;
// // Or return a render array.
// // in mytheme.html.twig use {{ form }} and {{ data }}.
// return [
// '#theme' => 'mytheme',
// "#form" => $form,
// "#data" => $data,
// ];
}
}

Resources