When trying to cancel a subscription with Laravel Cashier, it returns the error:
Class "App\Models\User" not found
Code:
public function cancel(Request $request) {
$subscription = Auth::user()->subscription('default');
$subscription->cancel();
}
This is likely because my user model is not located at "App\Models\User" (the new default in Laravel 8), but rather it is located at "App\User".
In the official documents, it mentions this:
If you're using a model other than Laravel's supplied App\Models\User model, you'll need to publish and alter the Cashier migrations provided to match your alternative model's table name.
But this isn't the problem. My table name is the same, but the location of my model is different.
How do I fix this?
use App\User; // this is important in your case
use Laravel\Cashier\Cashier;
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Cashier::useCustomerModel(User::class);
}
Docs: https://laravel.com/docs/8.x/billing#billable-model
Try change your providers config in config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
]
Reference https://laravel.com/docs/8.x/authentication#the-user-provider-contract
I want to use Laravel Auth::logoutOtherDevices. I added \Illuminate\Session\Middleware\AuthenticateSession::class to $middlewareGroups => web in kernal.
When I use this in login function :
public function login(Request $request)
{
Auth::attempt([
'email' => $request->input('email'),
'password' => $request->input('password')
], $request->has('remember'));
Auth::logoutOtherDevices($request->input('password'));
}
All passwords in my database change and I can't login with other accounts. :| Where is the problem?
Before getting started, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is present and un-commented in your App\Http\Kernel class' web middleware group:
'web' => [
// ...
\Illuminate\Session\Middleware\AuthenticateSession::class,
// ...
],
Then, you may use the logoutOtherDevices method provided by the Auth facade. This method requires the user to confirm their current password, which your application should accept through an input form
use Illuminate\Support\Facades\Auth;
Auth::logoutOtherDevices($currentPassword);
You should have sendLoginResponse method after attempt as it is inside of AuthenticateUsers trait, because sendLoginResponse implements $request->session()->regenerate(); in it.
A clean implementation of your purpose is to leave trait's login method intact and create authenticated method in the controller that has AuthenticateUsers trait and add below code it in.
protected function authenticated(Request $request, $user)
{
Auth::logoutOtherDevices($request->get('password'));
}
I am using Laravel 6.0 and I try to list all my routes with artisan route:list, but it fails and returns:
Illuminate\Contracts\Container\BindingResolutionException : Target
class [App\Http\Controllers\SessionsController] does not exist.
at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:806
802|
803| try {
804| $reflector = new ReflectionClass($concrete);
805| } catch (ReflectionException $e) {
> 806| throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
807| }
808|
809| // If the type is not instantiable, the developer is attempting to resolve
810| // an abstract type such as an Interface or Abstract Class and there is
Exception trace:
1 Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console{closure}(Object(Illuminate\Routing\Route))
[internal]:0
2 ReflectionException::("Class App\Http\Controllers\SessionsController does not exist")
/home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804
3 ReflectionClass::__construct("App\Http\Controllers\SessionsController")
/home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804
Up to now I just have a very simple web.php routes file:
Route::get('/', function () {
return view('index');
});
Route::prefix('app')->group(function () {
// Registration routes
Route::get('registration/create', 'RegistrationController#create')->name('app-registration-form');
});
// Templates
Route::get('templates/ubold/{any}', 'UboldController#index');
Any idea how I could debug this issue?
I was upgrading from Laravel 7 to Laravel 8 (Laravel 8 is still a few days in development) and also had this issue.
The solution was to use a classname representation of the controller in the route:
So in web.php instead of
Route::get('registration/create', 'RegistrationController#create')
it is now:
Solution 1: Classname representation
use App\Http\Controllers\RegistrationController;
Route::get('/', [RegistrationController::class, 'create']);
Solution 2: String syntax
or as a string syntax (full namespaces controller name):
Route::get('/', 'App\Http\Controllers\RegistrationController#create');
Solution 3: Return to previous behaviour
As this should issue should only happen if you upgrade your application by creating a brand new laravel project you can also just add the default namespace to the RouteServiceProvider:
app/Providers/RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/* ... */
/** ADD THIS PROPERTY
* If specified, this namespace is automatically applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* #var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace) // <-- ADD THIS
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace) // <-- ADD THIS
->group(base_path('routes/api.php'));
});
}
/* ... /*
}
See also https://laravel.com/docs/8.x/routing#basic-routing or https://laravel.com/docs/8.x/upgrade (search for "Routing").
For those who have similar issue with Illuminate\Contracts\Container\BindingResolutionException : Target class [<className>] does not exist. message, this also could be helpful:
composer dump-autoload
Run this command
php artisan config:cache
In my case it was solved by running
php artisan optimize:clear
php artisan config:cache
The optimize:clearcommands clears everything
In my case it was a matter of Linux's file name case sensitivity. For a file named IndexController, having Indexcontroller will work in windows but not in Linux
Simply add the following line in app->Providers->RouteServiceProvider.php
protected $namespace = 'App\\Http\\Controllers';
In my case same error occurred because of forward slash / but it should be backward slash \ in defining route,
it happens when you have controller in folder like as in my case controller was in api Folder, so always use backward slash \ while mentioning controller name.
see example:
Error-prone code:
Route::apiResource('categories', 'api/CategoryController');
Solution code:
Route::apiResource('categories', 'api\CategoryController');
This is the perfect answer, I think:
Option 1:
use App\Http\Controllers\HomepageController;
Route::get('/', [HomepageController::class, 'index']);
Option 2:
Route::get('/', 'App\Http\Controllers\HomepageController#index');
Alright i got similar problem, i was trying to be smart so i wrote this in my web.php
Route::group([
'middleware' => '', // Removing this made everything work
'as' => 'admin.',
'prefix' => 'admin',
'namespace' => 'Admin',
],function(){
});
All i had to do is just to remove all the unnecessary/unused option from group. That's all.
try to correct your controller name
my route was
Route::get('/lien/{id}','liensControler#show');
and my controller was
class liensController extends Controller
{
// all the methods of controller goes here.
}
I did all these
1: php artisan config:cache
2: checked for controller name spellings.
3: composer dump-autoload
4: Just changed the forward / slash to backward \ in route.
4th one worked for me.
Now You Can use controller outside controller folder
use App\Http\submit;
Route::get('/', [submit::class, 'index']);
Now my controller excited in http folder
You have to change in controller file something
<?php
namespace App\Http;
use Illuminate\Http\Request;
use Illuminate\Http\Controllers\Controller;
class submit extends Controller {
public function index(Request $req) {
return $req;
}
}
You can define a route to this controller action like so:
use App\Http\Controllers\UserController;
Route::get('user/{id}', [UserController::class, 'show']);
I am running Laravel 8.x on my pc.
This error gave me headache. To recreate the error, this is what I did:
First I created a controller called MyModelController.php
Secondly, I wrote a simple function to return a blade file containing 'Hello World', called myFunction.
Lastly, I created a Route:
Route::get('/','MyModelController#myFunction');
This did not work.
This was how I solved it.
First you would have to read the documentation on:
(https://laravel.com/docs/8.x/releases#laravel-8)
At the 'web.php' file this was the Route i wrote to make it work:
use App\Http\Controllers\MyModelController;
Route::get('/', [MyModelController::class, 'myFunction']);
on Larave 7 I had the same issue.
I checked the spelling of the controller name.
I recognize I have the wrong spelling in the "AlbumContoller" and I rename it to "AlbumController". so I forgot "r"
after I renamed the file and controller name and controller name in the web.php
Route::resource('albums', 'AlbumsController');
everything worked well
So You Don't need these two:
1- use App\Http\Controllers\IndexContoller;
2- Route::get('/', [MyModelController::class, 'myFunction']);
you have to specify full path to the class
Previously it was
Route::get('/wel','Welcome#index');
Now it has changed to
use App\Http\Controllers\Welcome;
Route::get('wel',[Welcome::class,'index']);
I had this problem while leaving an empty middleware class in my middleware groups by mistake :
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:100,1',
'bindings',
'localization',
'' // Was empty by mistake
],
];
replace-
Route::resource('/admin/UserOff','admin/UsersController');
with-
Route::resource('/admin/UserOff','admin\UsersController');
forward / with \
I had the same problem but with a middleware controller. So finally I linked that middleware in kerner.php file. It is located at app\Http\Kernel.php
I have added this line in route middleware.
'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class
];
just check web.php and see lower and upper case letters
On top of ensuring that you use the updated route syntax:
Route::get('/', [RegistrationController::class, 'create']);
make sure that at the top of your routes/web.php the controller is included in the name space like:
use App\Http\Controllers\RegistrationController;
Im having this problem when i use the command said in the title, its not finding my LoginController that i have in my auth folder.
It seams that it wants to load the controller using the wrong path.
Its weird because i never touched or moved anything from that controller i was creating a migration when i notice the error trying the route:list command as for my application it works normally except when i logout it doesn't redirect to my login view anymore it no redirects to public thus showing a 404.
I don't know what i did that it broke those things.
I tried changing the namespace of my controller to the one it shows on the error but its weird because when i change it the new error shows the correct path for the controller but since i changed it does not finds it again.
Also i tried the commands: config:cache, composer dump-autoload, composer update.
This is my controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
My web routes:
<?php
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::namespace('Admin')->prefix('admin')->middleware(['auth', 'auth.admin'])->name('admin.')->group(function(){
Route::resource('/ImagenAudioVideo', 'PlantillaController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Imagen', 'PlantillaImagenesController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Audio', 'PlantillaAudiosController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Video', 'PlantillaVideosController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/ImagenAudio', 'PlantillaImagenesAudioController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/EditarUsuario', 'EditarUsuariosController', ['except' => ['show', 'create', 'store'] ]);
Auth::routes(['register' => false]);
Route::get('/', function () {
return view('home');
});
});
The exception:
ReflectionException : Class App\Http\Controllers\Admin\Auth\LoginController does not exist
at /Applications/MAMP/htdocs/ConfiguradorIEM/vendor/laravel/framework/src/Illuminate/Container/Container.php:790
notice how it shows a different path but when i change the namespace to the path shown in the exception it throws a new error with the previous path.
You have two Auth::routes(); declarations, the second one has the namespace Admin.
This is why you get this error: you have to remove the line Auth::routes(['register' => false]); inside the Admin namespaced Route because you are adding the Admin namespace to all the Auth controllers.
Remember that Auth::routes(); are for the most named routes and the second route declaration override the first one.
If anyone is still searching for a solution for such an error.
In my case, the error showed up only because I forgot to specify the namespace for my controller which was in the Billing directory.
And as soon as I added this line at the top of my controller:
namespace App\Http\Controllers\Billing;
The issue was resolved.
I need to send a notification email only to admin when new user is registered.
When i submitting registration getting error -
Class 'app\Mail\NewUser' not found
in RegisterController.php (line 88)
Here is controller:
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use app\Mail\NewUser;
use Illuminate\Support\Facades\Mail;
protected function create(array $data)
{
$user = User::create([
'companyname' => $data['companyname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'VAT' => $data['VAT'],
'companyphone' => $data['companyphone'],
'companystreet' => $data['companystreet'],
'companycity' => $data['companycity'],
'companycountry' => $data['companycountry'],
'companypostcode' => $data['companypostcode']
]);
Mail::to('example#gmail.com')->send(new NewUser());
return $user;
}
would be great if someone help me.
Because you may not have created NewUser mailable class. You can create mailable classes by following artisan command.
php artisan make:mail NewUser
To know how to configure mali parameters like sender, from, to, subject, body etc., refer Writing Mailable here
Source
Update:
If you have created mailable and not able to find it, most probably it's composer issue. Fire following commands to clear cache and autoload files.
composer dump-autoload
php artisan config:cache