How can i add TrimString Middleware in laravel 5.3? - laravel

Just came to know that Laravel 5.4 has an awesome feature TrimString, which removes the white spaces from any input. I want this middleware in my 5.3 project, any idea how to do that?
I just copied the middleware from GitHub repo of Laravel but it is not working.
Thanks

If you want to use this feature in Laravel 5.3.
Add these two classes into your App\Http\Middleware
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php
https://github.com/laravel/laravel/blob/master/app/Http/Middleware/TrimStrings.php
Updating it's namespace to App\Http\middleware.
Like:
TransformsRequest.php
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
class TransformsRequest
{
/**
* The additional attributes passed to the middleware.
*
* #var array
*/
protected $attributes = [];
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, ...$attributes)
{
$this->attributes = $attributes;
$this->clean($request);
return $next($request);
}
/**
* Clean the request's data.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function clean($request)
{
$this->cleanParameterBag($request->query);
$this->cleanParameterBag($request->request);
if ($request->isJson()) {
$this->cleanParameterBag($request->json());
}
}
/**
* Clean the data in the parameter bag.
*
* #param \Symfony\Component\HttpFoundation\ParameterBag $bag
* #return void
*/
protected function cleanParameterBag(ParameterBag $bag)
{
$bag->replace($this->cleanArray($bag->all()));
}
/**
* Clean the data in the given array.
*
* #param array $data
* #return array
*/
protected function cleanArray(array $data)
{
return collect($data)->map(function ($value, $key) {
return $this->cleanValue($key, $value);
})->all();
}
/**
* Clean the given value.
*
* #param string $key
* #param mixed $value
* #return mixed
*/
protected function cleanValue($key, $value)
{
if (is_array($value)) {
return $this->cleanArray($value);
}
return $this->transform($key, $value);
}
/**
* Transform the given value.
*
* #param string $key
* #param mixed $value
* #return mixed
*/
protected function transform($key, $value)
{
return $value;
}
}
TrimStrings.php
namespace App\Http\Middleware;
class TrimStrings extends TransformsRequest
{
/**
* The attributes that should not be trimmed.
*
* #var array
*/
protected $except = [
//
];
/**
* Transform the given value.
*
* #param string $key
* #param mixed $value
* #return mixed
*/
protected function transform($key, $value)
{
if (in_array($key, $this->except)) {
return $value;
}
return is_string($value) ? trim($value) : $value;
}
}
And add into your App\Http\Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\TransformsRequest::class,
\App\Http\Middleware\TrimStrings::class,
];
To use it just use:
dd(request('email'));
More on it:
https://laravel-news.com/laravel-5-4-middleware

Related

error rtrim() in vendor\laravel\framework\src\Illuminate\Foundation\Application.php

/*When I try to view the output of my project on the browser, I am redirected to the following error
"ErrorException (E_WARNING)rtrim () expects the parameter 1 to be
string, given the object ".
Can someone help me?
*/
i find the problem in following function public function setBasePath($basePath ){
below the code Application.php:
<?php
namespace Illuminate\Foundation;
use Closure;
use RuntimeException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Container\Container;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Log\LogServiceProvider;
use Illuminate\Support\ServiceProvider;
use Illuminate\Events\EventServiceProvider;
use Illuminate\Routing\RoutingServiceProvider;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Contracts\Foundation\Application as ApplicationContract;
class Application extends Container implements ApplicationContract, HttpKernelInterface
{
/**
* The Laravel framework version.
*
* #var string
*/
const VERSION = '5.6.39';
/**
* The base path for the Laravel installation.
*
* #var string
*/
protected $basePath;
/**
* Indicates if the application has been bootstrapped before.
*
* #var bool
*/
protected $hasBeenBootstrapped = false;
/**
* Indicates if the application has "booted".
*
* #var bool
*/
protected $booted = false;
/**
* The array of booting callbacks.
*
* #var array
*/
protected $bootingCallbacks = [];
/**
* The array of booted callbacks.
*
* #var array
*/
protected $bootedCallbacks = [];
/**
* The array of terminating callbacks.
*
* #var array
*/
protected $terminatingCallbacks = [];
/**
* All of the registered service providers.
*
* #var array
*/
protected $serviceProviders = [];
/**
* The names of the loaded service providers.
*
* #var array
*/
protected $loadedProviders = [];
/**
* The deferred services and their providers.
*
* #var array
*/
protected $deferredServices = [];
/**
* The custom database path defined by the developer.
*
* #var string
*/
protected $databasePath;
/**
* The custom storage path defined by the developer.
*
* #var string
*/
protected $storagePath;
/**
* The custom environment path defined by the developer.
*
* #var string
*/
protected $environmentPath;
/**
* The environment file to load during bootstrapping.
*
* #var string
*/
protected $environmentFile = '.env';
/**
* The application namespace.
*
* #var string
*/
protected $namespace;
/**
* Create a new Illuminate application instance.
*
* #param string|null $basePath
* #return void
*/
public function __construct($basePath = null)
{
if ($basePath) {
$this->setBasePath($basePath);
}
$this->registerBaseBindings();
$this->registerBaseServiceProviders();
$this->registerCoreContainerAliases();
}
/**
* Get the version number of the application.
*
* #return string
*/
public function version()
{
return static::VERSION;
}
/**
* Register the basic bindings into the container.
*
* #return void
*/
protected function registerBaseBindings()
{
static::setInstance($this);
$this->instance('app', $this);
$this->instance(Container::class, $this);
$this->instance(PackageManifest::class, new PackageManifest(
new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
));
}
/**
* Register all of the base service providers.
*
* #return void
*/
protected function registerBaseServiceProviders()
{
$this->register(new EventServiceProvider($this));
$this->register(new LogServiceProvider($this));
$this->register(new RoutingServiceProvider($this));
}
/**
* Run the given array of bootstrap classes.
*
* #param array $bootstrappers
* #return void
*/
public function bootstrapWith(array $bootstrappers)
{
$this->hasBeenBootstrapped = true;
foreach ($bootstrappers as $bootstrapper) {
$this['events']->fire('bootstrapping: '.$bootstrapper, [$this]);
$this->make($bootstrapper)->bootstrap($this);
$this['events']->fire('bootstrapped: '.$bootstrapper, [$this]);
}
}
/**
* Register a callback to run after loading the environment.
*
* #param \Closure $callback
* #return void
*/
public function afterLoadingEnvironment(Closure $callback)
{
return $this->afterBootstrapping(
LoadEnvironmentVariables::class, $callback
);
}
/**
* Register a callback to run before a bootstrapper.
*
* #param string $bootstrapper
* #param \Closure $callback
* #return void
*/
public function beforeBootstrapping($bootstrapper, Closure $callback)
{
$this['events']->listen('bootstrapping: '.$bootstrapper, $callback);
}
/**
* Register a callback to run after a bootstrapper.
*
* #param string $bootstrapper
* #param \Closure $callback
* #return void
*/
public function afterBootstrapping($bootstrapper, Closure $callback)
{
$this['events']->listen('bootstrapped: '.$bootstrapper, $callback);
}
/**
* Determine if the application has been bootstrapped before.
*
* #return bool
*/
public function hasBeenBootstrapped()
{
return $this->hasBeenBootstrapped;
}
/**
* Set the base path for the application.
*
* #param string $basePath
* #return $this
*/
public function setBasePath($basePath )
{
$this->basePath = rtrim($basePath, '\/');
$this->bindPathsInContainer();
return $this;
}
/**
* Bind all of the application paths in the container.
*
* #return void
*/
protected function bindPathsInContainer()
{
$this->instance('path', $this->path());
$this->instance('path.base', $this->basePath());
$this->instance('path.lang', $this->langPath());
$this->instance('path.config', $this->configPath());
$this->instance('path.public', $this->publicPath());
$this->instance('path.storage', $this->storagePath());
$this->instance('path.database', $this->databasePath());
$this->instance('path.resources', $this->resourcePath());
$this->instance('path.bootstrap', $this->bootstrapPath());
}
/**
* Get the path to the application "app" directory.
*
* #param string $path Optionally, a path to append to the app path
* #return string
*/
public function path($path = '')
{
return $this->basePath.DIRECTORY_SEPARATOR.'app'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
/**
* Get the base path of the Laravel installation.
*
* #param string $path Optionally, a path to append to the base path
* #return string
*/
public function basePath($path = '')
{
return $this->basePath.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
/**
* Get the path to the bootstrap directory.
*
* #param string $path Optionally, a path to append to the bootstrap path
* #return string
*/
public function bootstrapPath($path = '')
{
return $this->basePath.DIRECTORY_SEPARATOR.'bootstrap'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
/**
* Get the path to the application configuration files.
*
* #param string $path Optionally, a path to append to the config path
* #return string
*/
public function configPath($path = '')
{
return $this->basePath.DIRECTORY_SEPARATOR.'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
/**
* Get the path to the database directory.
*
* #param string $path Optionally, a path to append to the database path
* #return string
*/
public function databasePath($path = '')
{
return ($this->databasePath ?: $thi`enter code here`s->basePath.DIRECTORY_SEPARATOR.'database').($path ? DIRECTORY_SEPARATOR.$path : $path);
}
Can you check you .env for APP_BASE_PATH?
The Application is initialized in bootstrap/app.php file
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
As you can see it looks APP_BASE_PATH environment variable and if this is not set it uses the path to your root application folder.
dirname(__DIR__) returns the path to the parent folder.
Based on the details you posted it looks like the problem can be with the value you set for APP_BASE_PATH
This response assumes you are using the latest version of Laravel, 5.8

Laravel Nova: TypeError: Cannot read property 'status' of undefined

A bunch of my Nova ressources stopped working. When trying to create them, I get the following error in the console:
Uncaught (in promise) TypeError: Cannot read property 'status' of undefined
at a.<anonymous> (app.js?id=7319bf5027431449796c:1)
at y (app.js?id=7319bf5027431449796c:1)
at Generator._invoke (app.js?id=7319bf5027431449796c:1)
at Generator.e.(anonymous function) [as next] (http://url/vendor/nova/app.js?id=7319bf5027431449796c:1:460720)
at o (app.js?id=7319bf5027431449796c:1)
at app.js?id=7319bf5027431449796c:1
at new Promise (<anonymous>)
at new t (app.js?id=7319bf5027431449796c:1)
at a.<anonymous> (app.js?id=7319bf5027431449796c:1)
at a.<anonymous> (app.js?id=7319bf5027431449796c:1)
Nothing shows up in the error log at all. Any pointers to where I should be looking? Only affects some ressources, others are working fine.
Edit: Here is one of the affected Nova ressources:
<?php
namespace App\Nova;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
use Naxon\NovaFieldSortable\Concerns\SortsIndexEntries;
use Naxon\NovaFieldSortable\Sortable;
class Unterprodukt extends Resource
{
use SortsIndexEntries;
public static $defaultSortField = 'order';
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\Unterprodukt';
/**
* Get the displayble label of the resource.
*
* #return string
*/
public static function label()
{
return 'Unterprodukte';
}
/**
* Get the displayble singular label of the resource.
*
* #return string
*/
public static function singularLabel()
{
return 'Unterprodukt';
}
/**
* The logical group associated with the resource.
*
* #var string
*/
public static $group = 'Versicherung';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'name';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
'name',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()
->sortable()
->hideFromIndex(),
Text::make('Name', 'name')
->sortable(),
BelongsTo::make('Produkt', 'produkt', 'App\Nova\Produkt')
->sortable(),
Sortable::make('Reihenfolge', 'id')
->sortable(),
HasMany::make('Dokumente', 'dokumente', 'App\Nova\Dokument'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
The quick fix for this is this way
Sortable::make('Order', 'id')->exceptOnForms()
I had this problem too, and it was because I had an incoherence between nova fields and migrations fields.
Now, another possible way to fix it is:
php artisan nova:publish
php artisan view:clear
Check this issue for more details: https://github.com/laravel/nova-issues/issues/1735

Laravel, Show(), Edit (), update functions not working

In the code below methods show, edit update are not working.
<?php
namespace App\Http\Controllers\admins;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\contact;
use Image;
use Auth;
use Storage;
use File;
class ContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$contact = Contact::orderby('created_at', 'desc')->paginate(5);
//$agent=Agent::orderby('id','desc')->paginate(5);
return view('admin.messages.index', ['contacts' => $contact]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return back()->with('success', 'Message can only be created by Users end.');
}
/** * Display the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function edit(contact $contact)
{
return view('admin.messages.edit', compact('contact'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function update(Request $request, contact $contact)
{
dd($request);
}
/**
* Remove the specified resource from storage.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function destroy(contact $contact)
{
return back()->with('success', 'Message history can not be Deleted. ');
}
}
Assuming you are using a slug in a route like contacts/{ slugĀ }
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
Receives an id not a contact... you are initializing/declaring in the function parameter as contact thats why it somehow gets casted to a contact... but it's an id you should do something like:
public function show($id)
{
$contact = Contact::findOrFail($id);
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}

How to change Password column Field for Laravel 5.2 password reset

I have a project being developed in laravel 5.2, I currently am having troubles with the password reset to work. At the moment I have it looking for the correct email field and to let the user request a password reset email with link to reset it, then after the user clicks the link in the email the user will be presented with the form to change their password. When they submit their new password they are presented with this error:
QueryException in Connection.php line 729:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'password_confirmation' in 'where clause' (SQL: select * from all_user where user_email = ...#hotmail.com and password_confirmation = 123456 limit 1)
I dont know why its checking in the sql statement for a field called password_confirmation. This error is getting caused by trying to get the user so it can perform the password reset. This is in the PasswordBroker.php file and the getUser function. More specifically the line $user = $this->users->retrieveByCredentials($credentials);
My current code I modified so far:
ResetsPasswords.php
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
trait ResetsPasswords
{
use RedirectsUsers;
/**
* Get the name of the guest middleware.
*
* #return string
*/
protected function guestMiddleware()
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function getEmail()
{
return $this->showLinkRequestForm();
}
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function showLinkRequestForm()
{
if (property_exists($this, 'linkRequestView')) {
return view($this->linkRequestView);
}
if (view()->exists('auth.passwords.email')) {
return view('auth.passwords.email');
}
return view('auth.password');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
return $this->sendResetLinkEmail($request);
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function sendResetLinkEmail(Request $request)
{
$request['user_email'] = $request['email'];
$this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();
$response = Password::broker($broker)->sendResetLink(
$this->getSendResetLinkEmailCredentials($request),
$this->resetEmailBuilder()
);
return dd($request);
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->getSendResetLinkEmailSuccessResponse($response);
case Password::INVALID_USER:
default:
return $this->getSendResetLinkEmailFailureResponse($response);
}
}
/**
* Validate the request of sending reset link.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateSendResetLinkEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
}
/**
* Get the needed credentials for sending the reset link.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getSendResetLinkEmailCredentials(Request $request)
{
return $request->only('user_email');
}
/**
* Get the Closure which is used to build the password reset email message.
*
* #return \Closure
*/
protected function resetEmailBuilder()
{
return function (Message $message) {
$message->subject($this->getEmailSubject());
};
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* #return string
*/
protected function getEmailSubject()
{
return property_exists($this, 'subject') ? $this->subject : 'Your Password Reset Link';
}
/**
* Get the response for after the reset link has been successfully sent.
*
* #param string $response
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function getSendResetLinkEmailSuccessResponse($response)
{
return redirect()->back()->with('status', trans($response));
}
/**
* Get the response for after the reset link could not be sent.
*
* #param string $response
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function getSendResetLinkEmailFailureResponse($response)
{
return redirect()->back()->withErrors(['email' => trans($response)]);
}
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #param string|null $token
* #return \Illuminate\Http\Response
*/
public function getReset(Request $request, $token = null)
{
return $this->showResetForm($request, $token);
}
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #param string|null $token
* #return \Illuminate\Http\Response
*/
public function showResetForm(Request $request, $token = null)
{
if (is_null($token)) {
return $this->getEmail();
}
$email = $request->input('email');
if (property_exists($this, 'resetView')) {
return view($this->resetView)->with(compact('token', 'email'));
}
if (view()->exists('auth.passwords.reset')) {
return view('auth.passwords.reset')->with(compact('token', 'email'));
}
return view('auth.reset')->with(compact('token', 'email'));
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postReset(Request $request)
{
return $this->reset($request);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function reset(Request $request)
{
$request['user_email'] = $request['email'];
$request['user_password'] = $request['password'];
$this->validate(
$request,
$this->getResetValidationRules(),
$this->getResetValidationMessages(),
$this->getResetValidationCustomAttributes()
);
$credentials = $this->getResetCredentials($request);
$broker = $this->getBroker();
//return dd($credentials);
$response = Password::broker($broker)->reset($credentials, function ($user, $password) {
return dd($password);
$this->resetPassword($user, $password);
});
//return dd($request);
switch ($response) {
case Password::PASSWORD_RESET:
return $this->getResetSuccessResponse($response);
default:
return $this->getResetFailureResponse($request, $response);
}
}
/**
* Get the password reset validation rules.
*
* #return array
*/
protected function getResetValidationRules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
];
}
/**
* Get the password reset validation messages.
*
* #return array
*/
protected function getResetValidationMessages()
{
return [];
}
/**
* Get the password reset validation custom attributes.
*
* #return array
*/
protected function getResetValidationCustomAttributes()
{
return [];
}
/**
* Get the password reset credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getResetCredentials(Request $request)
{
return $request->only(
'user_email', 'user_password', 'password_confirmation', 'token'
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->forceFill([
'user_password' => bcrypt($password),
'remember_token' => Str::random(60),
])->save();
Auth::guard($this->getGuard())->login($user);
}
/**
* Get the response for after a successful password reset.
*
* #param string $response
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function getResetSuccessResponse($response)
{
return redirect($this->redirectPath())->with('status', trans($response));
}
/**
* Get the response for after a failing password reset.
*
* #param Request $request
* #param string $response
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function getResetFailureResponse(Request $request, $response)
{
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
/**
* Get the broker to be used during password reset.
*
* #return string|null
*/
public function getBroker()
{
return property_exists($this, 'broker') ? $this->broker : null;
}
/**
* Get the guard to be used during password reset.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
CanResetPassword.php
<?php
namespace Illuminate\Auth\Passwords;
trait CanResetPassword
{
/**
* Get the e-mail address where password reset links are sent.
*
* #return string
*/
public function getEmailForPasswordReset()
{
return $this->user_email;
}
}
PasswordBroker.php
<?php
namespace Illuminate\Auth\Passwords;
use Closure;
use Illuminate\Support\Arr;
use UnexpectedValueException;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Mail\Mailer as MailerContract;
use Illuminate\Contracts\Auth\PasswordBroker as PasswordBrokerContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class PasswordBroker implements PasswordBrokerContract
{
/**
* The password token repository.
*
* #var \Illuminate\Auth\Passwords\TokenRepositoryInterface
*/
protected $tokens;
/**
* The user provider implementation.
*
* #var \Illuminate\Contracts\Auth\UserProvider
*/
protected $users;
/**
* The mailer instance.
*
* #var \Illuminate\Contracts\Mail\Mailer
*/
protected $mailer;
/**
* The view of the password reset link e-mail.
*
* #var string
*/
protected $emailView;
/**
* The custom password validator callback.
*
* #var \Closure
*/
protected $passwordValidator;
/**
* Create a new password broker instance.
*
* #param \Illuminate\Auth\Passwords\TokenRepositoryInterface $tokens
* #param \Illuminate\Contracts\Auth\UserProvider $users
* #param \Illuminate\Contracts\Mail\Mailer $mailer
* #param string $emailView
* #return void
*/
public function __construct(TokenRepositoryInterface $tokens,
UserProvider $users,
MailerContract $mailer,
$emailView)
{
$this->users = $users;
$this->mailer = $mailer;
$this->tokens = $tokens;
$this->emailView = $emailView;
}
/**
* Send a password reset link to a user.
*
* #param array $credentials
* #param \Closure|null $callback
* #return string
*/
public function sendResetLink(array $credentials, Closure $callback = null)
{
// First we will check to see if we found a user at the given credentials and
// if we did not we will redirect back to this current URI with a piece of
// "flash" data in the session to indicate to the developers the errors.
$user = $this->getUser($credentials);
if (is_null($user)) {
return static::INVALID_USER;
}
// Once we have the reset token, we are ready to send the message out to this
// user with a link to reset their password. We will then redirect back to
// the current URI having nothing set in the session to indicate errors.
//return dd($credentials);
$token = $this->tokens->create($user);
$this->emailResetLink($user, $token, $callback);
return static::RESET_LINK_SENT;
}
/**
* Send the password reset link via e-mail.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $token
* #param \Closure|null $callback
* #return int
*/
public function emailResetLink(CanResetPasswordContract $user, $token, Closure $callback = null)
{
// We will use the reminder view that was given to the broker to display the
// password reminder e-mail. We'll pass a "token" variable into the views
// so that it may be displayed for an user to click for password reset.
$view = $this->emailView;
return $this->mailer->send($view, compact('token', 'user'), function ($m) use ($user, $token, $callback) {
$m->to($user->getEmailForPasswordReset());
if (! is_null($callback)) {
call_user_func($callback, $m, $user, $token);
}
});
}
/**
* Reset the password for the given token.
*
* #param array $credentials
* #param \Closure $callback
* #return mixed
*/
public function reset(array $credentials, Closure $callback)
{
// If the responses from the validate method is not a user instance, we will
// assume that it is a redirect and simply return it from this method and
// the user is properly redirected having an error message on the post.
//return dd($credentials);
$user = $this->validateReset($credentials);
if (! $user instanceof CanResetPasswordContract) {
return $user;
}
$pass = $credentials['user_password'];
// Once we have called this callback, we will remove this token row from the
// table and return the response from this callback so the user gets sent
// to the destination given by the developers from the callback return.
call_user_func($callback, $user, $pass);
$this->tokens->delete($credentials['token']);
return static::PASSWORD_RESET;
}
/**
* Validate a password reset for the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\CanResetPassword
*/
protected function validateReset(array $credentials)
{
if (is_null($user = $this->getUser($credentials))) {
return static::INVALID_USER;
}
if (! $this->validateNewPassword($credentials)) {
return static::INVALID_PASSWORD;
}
if (! $this->tokens->exists($user, $credentials['token'])) {
return static::INVALID_TOKEN;
}
return $user;
}
/**
* Set a custom password validator.
*
* #param \Closure $callback
* #return void
*/
public function validator(Closure $callback)
{
$this->passwordValidator = $callback;
}
/**
* Determine if the passwords match for the request.
*
* #param array $credentials
* #return bool
*/
public function validateNewPassword(array $credentials)
{
list($password, $confirm) = [
$credentials['user_password'],
$credentials['password_confirmation'],
];
if (isset($this->passwordValidator)) {
return call_user_func(
$this->passwordValidator, $credentials) && $password === $confirm;
}
return $this->validatePasswordWithDefaults($credentials);
}
/**
* Determine if the passwords are valid for the request.
*
* #param array $credentials
* #return bool
*/
protected function validatePasswordWithDefaults(array $credentials)
{
list($password, $confirm) = [
$credentials['user_password'],
$credentials['password_confirmation'],
];
return $password === $confirm && mb_strlen($password) >= 6;
}
/**
* Get the user for the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\CanResetPassword
*
* #throws \UnexpectedValueException
*/
public function getUser(array $credentials)
{
$credentials = Arr::except($credentials, ['token']);
//$credentials = Arr::except($credentials, ['password_confirmation']);
//return dd($credentials);
$user = $this->users->retrieveByCredentials($credentials);
//return dd($credentials);
//$credentials = $credentials['password_confirmation'];
if ($user && ! $user instanceof CanResetPasswordContract) {
throw new UnexpectedValueException('User must implement CanResetPassword interface.');
}
return $user;
}
/**
* Create a new password reset token for the given user.
*
* #param CanResetPasswordContract $user
* #return string
*/
public function createToken(CanResetPasswordContract $user)
{
return $this->tokens->create($user);
}
/**
* Delete the given password reset token.
*
* #param string $token
* #return void
*/
public function deleteToken($token)
{
$this->tokens->delete($token);
}
/**
* Validate the given password reset token.
*
* #param CanResetPasswordContract $user
* #param string $token
* #return bool
*/
public function tokenExists(CanResetPasswordContract $user, $token)
{
return $this->tokens->exists($user, $token);
}
/**
* Get the password reset token repository implementation.
*
* #return \Illuminate\Auth\Passwords\TokenRepositoryInterface
*/
public function getRepository()
{
return $this->tokens;
}
}

ERR_TOO_MANY_REDIRECTS in Laravel

I am learning Laravel. I have a problem with the very basics. I get a ERR_TOO_MANY_REDIRECTS.
my routes.php:
Route::get('/','WelcomeController#index');
index function:
public function index(){
return view('welcome');
}
The URL gets an additional part, I don't know why.
From http://localhost/dev.todoparrot.com/public to http://localhost/dev.todoparrot.com/public/home
<?php
namespace todoparrot\Http\Controllers;
use Illuminate\Http\Request;
use todoparrot\Http\Requests;
use todoparrot\Http\Controllers\Controller;
class WelcomeController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(){
return view('welcome');
}
public function contact(){
echo "we are in contacts";
return view('welcome');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Resources