Artisan Key Generate Not Working

Posted on  by
  • Basic Controllers
  • Resource Controllers
  • Laravel Create a package with Service Provider. Php artisan is not working in lavavel5.4 in XAMPP; 400 Bad Request When Adding Member to MailChimp Li. Middleware on route and in controller; Lifespan of a class provided by Laravel Service pr. Conditionally require authentication to access rou.
  • To quickly generate an API resource controller that does not include the create or edit methods, use the -api switch when executing the make:controller command: php artisan make:controller API/PhotoController -api. Nested Resources. Sometimes you may.
  • To create a migration, use the make:migration Artisan command: php artisan make:migration createuserstable. The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations.
  • Oct 26, 2017  It has a detail, if I put any other key manually in the.env (such as base64: JYY8rk4 + k1tXELhyZ68BfpuVfoBhrHdXf5vPxyS7zAM =) and run php artisan key: generate, it works. If it does not work, it will not work.
  • The most concise screencasts for the working developer, updated daily. There's no shortage of content at Laracasts. In fact, you could watch nonstop for days upon days, and still not see everything!
  • Laravel 5.5 doesn't recognise?? When using php artisan key:generate I've been trying to use php artisan key:generate after cloning my Laravel project to a server. However, I get the following error.

Introduction

Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior using Controller classes. Controllers can group related request handling logic into a single class. Controllers are stored in the app/Http/Controllers directory.

Basic Controllers

I appreciate that this may be a stupid question but what is the App Key used for. Where and when? When I run the command artisan key:generate locally it saves it to the.env file, should. Please sign in or create an account to participate in this conversation. The most concise screencasts for the working developer, updated daily.

Defining Controllers

Below is an example of a basic controller class. Note that the controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller actions:

You can define a route to this controller action like so:

Now, when a request matches the specified route URI, the show method on the UserController class will be executed. The route parameters will also be passed to the method.

{tip} Controllers are not required to extend a base class. However, you will not have access to convenience features such as the middleware, validate, and dispatch methods.

Controllers & Namespaces

It is very important to note that we did not need to specify the full controller namespace when defining the controller route. Since the RouteServiceProvider loads your route files within a route group that contains the namespace, we only specified the portion of the class name that comes after the AppHttpControllers portion of the namespace.

If you choose to nest your controllers deeper into the AppHttpControllers directory, use the specific class name relative to the AppHttpControllers root namespace. So, if your full controller class is AppHttpControllersPhotosAdminController, you should register routes to the controller like so:

Single Action Controllers

If you would like to define a controller that only handles a single action, you may place a single __invoke method on the controller:

When registering routes for single action controllers, you do not need to specify a method:

You may generate an invokable controller by using the --invokable option of the make:controller Artisan command:

{tip} Controller stubs may be customized using stub publishing

Controller Middleware

Middleware may be assigned to the controller's routes in your route files:

However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action. You may even restrict the middleware to only certain methods on the controller class:

Controllers also allow you to register middleware using a Closure. This provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

{tip} You may assign middleware to a subset of controller actions; however, it may indicate your controller is growing too large. Instead, consider breaking your controller into multiple, smaller controllers.

Resource Controllers

Laravel resource routing assigns the typical 'CRUD' routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for 'photos' stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:

This command will generate a controller at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations.

Next, you may register a resourceful route to the controller:

This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions, including notes informing you of the HTTP verbs and URIs they handle.

You may register many resource controllers at once by passing an array to the resources method:

Actions Handled By Resource Controller

VerbURIActionRoute Name
GET/photosindexphotos.index
GET/photos/createcreatephotos.create
POST/photosstorephotos.store
GET/photos/{photo}showphotos.show
GET/photos/{photo}/editeditphotos.edit
PUT/PATCH/photos/{photo}updatephotos.update
DELETE/photos/{photo}destroyphotos.destroy

Specifying The Resource Model

If you are using route model binding and would like the resource controller's methods to type-hint a model instance, you may use the --model option when generating the controller:

Spoofing Form Methods

Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you:

Partial Resource Routes

When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:

API Resource Routes

When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as create and edit. For convenience, you may use the apiResource method to automatically exclude these two routes:

You may register many API resource controllers at once by passing an array to the apiResources method:

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

Nested Resources

Sometimes you may need to define routes to a nested resource. For example, a photo resource may have multiple comments that may be attached to the photo. To nest the resource controllers, use 'dot' notation in your route declaration:

This route will register a nested resource that may be accessed with URIs like the following:

Shallow Nesting

Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifier such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use 'shallow nesting':

The route definition above will define the following routes:

VerbURIActionRoute Name
GET/photos/{photo}/commentsindexphotos.comments.index
GET/photos/{photo}/comments/createcreatephotos.comments.create
POST/photos/{photo}/commentsstorephotos.comments.store
GET/comments/{comment}showcomments.show
GET/comments/{comment}/editeditcomments.edit
PUT/PATCH/comments/{comment}updatecomments.update
DELETE/comments/{comment}destroycomments.destroy

Naming Resource Routes

By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:

Naming Resource Route Parameters

By default, Route::resource will create the route parameters for your resource routes based on the 'singularized' version of the resource name. You can easily override this on a per resource basis by using the parameters method. The array passed into the parameters method should be an associative array of resource names and parameter names:

The example above generates the following URIs for the resource's show route:

Localizing Resource URIs

By default, Route::resource will create resource URIs using English verbs. If you need to localize the create and edit action verbs, you may use the Route::resourceVerbs method. This may be done in the boot method of your AppServiceProvider:

Once the verbs have been customized, a resource route registration such as Route::resource('fotos', 'PhotoController') will produce the following URIs:

Supplementing Resource Controllers

If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to Route::resource; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

{tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers.

Dependency Injection & Controllers

Constructor Injection

The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance:

You may also type-hint any Laravel contract. If the container can resolve it, you can type-hint it. Depending on your application, injecting your dependencies into your controller may provide better testability.

Method Injection

In addition to constructor injection, you may also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the IlluminateHttpRequest instance into your controller methods:

If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. For example, if your route is defined like so:

You may still type-hint the IlluminateHttpRequest and access your id parameter by defining your controller method as follows:

Route Caching

{note} Closure based routes cannot be cached. To use route caching, you must convert any Closure routes to controller classes.

If your application is exclusively using controller based routes, you should take advantage of Laravel's route cache. Using the route cache will drastically decrease the amount of time it takes to register all of your application's routes. In some cases, your route registration may even be up to 100x faster. To generate a route cache, just execute the route:cache Artisan command:

After running this command, your cached routes file will be loaded on every request. Remember, if you add any new routes you will need to generate a fresh route cache. Because of this, you should only run the route:cache command during your project's deployment.

You may use the route:clear command to clear the route cache:

  • Introduction
  • Authentication Quickstart
  • Manually Authenticating Users
  • HTTP Basic Authentication
  • Logging Out
  • Adding Custom Guards
  • Adding Custom User Providers

Introduction

{tip} Want to get started fast? Install the laravel/ui Composer package and run php artisan ui vue --auth in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!

Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services.

At its core, Laravel's authentication facilities are made up of 'guards' and 'providers'. Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.

Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent and the database query builder. However, you are free to define additional providers as needed for your application.

Artisan Key Generate Not Working At Home

Don't worry if this all sounds confusing now! Many applications will never need to modify the default authentication configuration.

Database Considerations

By default, Laravel includes an AppUserEloquent model in your app directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database authentication driver which uses the Laravel query builder.

When building the database schema for the AppUser model, make sure the password column is at least 60 characters in length. Maintaining the default string column length of 255 characters would be a good choice.

Also, you should verify that your users (or equivalent) table contains a nullable, string remember_token column of 100 characters. This column will be used to store a token for users that select the 'remember me' option when logging into your application.

Authentication Quickstart

Routing

Laravel's laravel/ui package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:

This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController will also be generated to handle post-login requests to your application's dashboard.

The laravel/ui package also generates several pre-built authentication controllers, which are located in the AppHttpControllersAuth namespace. The RegisterController handles new user registration, the LoginController handles authentication, the ForgotPasswordController handles e-mailing links for resetting passwords, and the ResetPasswordController contains the logic to reset passwords. Each of these controllers uses a trait to include their necessary methods. For many applications, you will not need to modify these controllers at all.

{tip} If your application doesn’t need registration, you may disable it by removing the newly created RegisterController and modifying your route declaration: Auth::routes(['register' => false]);.

Creating Applications Including Authentication

If you are starting a brand new application and would like to include the authentication scaffolding, you may use the --auth directive when creating your application. This command will create a new application with all of the authentication scaffolding compiled and installed:

Views

As mentioned in the previous section, the laravel/ui package's php artisan ui vue --auth command will create all of the views you need for authentication and place them in the resources/views/auth directory.

The ui command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

Authenticating

Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.

Path Customization

When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

If you need more robust customization of the response returned when a user is authenticated, Laravel provides an empty authenticated(Request $request, $user) method that may be overwritten if desired:

Username Customization

By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:

Guard Customization

You may also customize the 'guard' that is used to authenticate and register users. To get started, define a guard method on your LoginController, RegisterController, and ResetPasswordController. The method should return a guard instance:

Validation / Storage Customization

To modify the form fields that are required when a new user registers with your application, or to customize how new users are stored into your database, you may modify the RegisterController class. This class is responsible for validating and creating new users of your application.

The validator method of the RegisterController contains the validation rules for new users of the application. You are free to modify this method as you wish.

The create method of the RegisterController is responsible for creating new AppUser records in your database using the Eloquent ORM. You are free to modify this method according to the needs of your database.

Retrieving The Authenticated User

You may access the authenticated user via the Auth facade:

Alternatively, once a user is authenticated, you may access the authenticated user via an IlluminateHttpRequest instance. Remember, type-hinted classes will automatically be injected into your controller methods:

Determining If The Current User Is Authenticated

To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

{tip} Even though it is possible to determine if a user is authenticated using the check method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes.

Protecting Routes

Route middleware can be used to only allow authenticated users to access a given route. Laravel ships with an auth middleware, which is defined at IlluminateAuthMiddlewareAuthenticate. Since this middleware is already registered in your HTTP kernel, all you need to do is attach the middleware to a route definition:

If you are using controllers, you may call the middleware method from the controller's constructor instead of attaching it in the route definition directly:

Redirecting Unauthenticated Users

When the auth middleware detects an unauthorized user, it will redirect the user to the loginnamed route. You may modify this behavior by updating the redirectTo function in your app/Http/Middleware/Authenticate.php file:

Specifying A Guard

When attaching the auth middleware to a route, you may also specify which guard should be used to authenticate the user. The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file:

Password Confirmation

Sometimes, you may wish to require the user to confirm their password before accessing a specific area of your application. For example, you may require this before the user modifies any billing settings within the application.

To accomplish this, Laravel provides a password.confirm middleware. Attaching the password.confirm middleware to a route will redirect users to a screen where they need to confirm their password before they can continue:

After the user has successfully confirmed their password, the user is redirected to the route they originally tried to access. By default, after confirming their password, the user will not have to confirm their password again for three hours. You are free to customize the length of time before the user must re-confirm their password using the auth.password_timeout configuration option.

Login Throttling

If you are using Laravel's built-in LoginController class, the IlluminateFoundationAuthThrottlesLogins trait will already be included in your controller. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user's username / e-mail address and their IP address.

Manually Authenticating Users

Note that you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly. Don't worry, it's a cinch!

We will access Laravel's authentication services via the Authfacade, so we'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:

The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array. You should not hash the password specified as the password value, since the framework will automatically hash the value before comparing it to the hashed password in the database. If the two hashed passwords match an authenticated session will be started for the user.

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

Specifying Additional Conditions

If you wish, you may also add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as 'active':

{note} In these examples, email is not a required option, it is merely used as an example. You should use whatever column name corresponds to a 'username' in your database.

Accessing Specific Guard Instances

You may specify which guard instance you would like to utilize using the guard method on the Auth facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

Logging Out

To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session:

Remembering Users

If you would like to provide 'remember me' functionality in your application, you may pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. Your users table must include the string remember_token column, which will be used to store the 'remember me' token.

{tip} If you are using the built-in LoginController that is shipped with Laravel, the proper logic to 'remember' users is already implemented by the traits used by the controller.

If you are 'remembering' users, you may use the viaRemember method to determine if the user was authenticated using the 'remember me' cookie:

Other Authentication Methods

Authenticate A User Instance

If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the IlluminateContractsAuthAuthenticatablecontract. The AppUser model included with Laravel already implements this interface:

You may specify the guard instance you would like to use:

Authenticate A User By ID

To log a user into the application by their ID, you may use the loginUsingId method. This method accepts the primary key of the user you wish to authenticate:

Authenticate A User Once

You may use the once method to log a user into the application for a single request. No sessions or cookies will be utilized, which means this method may be helpful when building a stateless API:

HTTP Basic Authentication

HTTP Basic Authentication provides a quick way to authenticate users of your application without setting up a dedicated 'login' page. To get started, attach the auth.basicmiddleware to your route. The auth.basic middleware is included with the Laravel framework, so you do not need to define it:

Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will use the email column on the user record as the 'username'.

A Note On FastCGI

If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your .htaccess file:

Stateless HTTP Basic Authentication

You may also use HTTP Basic Authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication. To do so, define a middleware that calls the onceBasic method. If no response is returned by the onceBasic method, the request may be passed further into the application:

Next, register the route middleware and attach it to a route:

Logging Out

Key Generator

To manually log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session:

Invalidating Sessions On Other Devices

Laravel also provides a mechanism for invalidating and 'logging out' a user's sessions that are active on other devices without invalidating the session on their current device. This feature is typically utilized when a user is changing or updating their password and you would like to invalidate sessions on other devices while keeping the current device authenticated.

Before getting started, you should make sure that the IlluminateSessionMiddlewareAuthenticateSession middleware is present and un-commented in your app/Http/Kernel.php class' web middleware group:

Then, you may use the logoutOtherDevices method on the Auth facade. This method requires the user to provide their current password, which your application should accept through an input form:

When the logoutOtherDevices method is invoked, the user's other sessions will be invalidated entirely, meaning they will be 'logged out' of all guards they were previously authenticated by.

Free Key Generate Software

{note} When using the AuthenticateSession middleware in combination with a custom route name for the login route, you must override the unauthenticated method on your application's exception handler to properly redirect users to your login page.

Adding Custom Guards

You may define your own authentication guards using the extend method on the Auth facade. You should place this call to extend within a service provider. Since Laravel already ships with an AuthServiceProvider, we can place the code in that provider:

As you can see in the example above, the callback passed to the extend method should return an implementation of IlluminateContractsAuthGuard. This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may use this guard in the guards configuration of your auth.php configuration file:

Closure Request Guards

The simplest way to implement a custom, HTTP request based authentication system is by using the Auth::viaRequest method. This method allows you to quickly define your authentication process using a single Closure.

To get started, call the Auth::viaRequest method within the boot method of your AuthServiceProvider. The viaRequest method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a Closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null:

Once your custom authentication driver has been defined, you use it as a driver within guards configuration of your auth.php configuration file:

Adding Custom User Providers

If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the provider method on the Auth facade to define a custom user provider:

Understand that English isn't everyone's first language so be lenient of badspelling and grammar. Read the question carefully. If a question is poorly phrased then either ask for clarification, ignore it, oredit the question and fix the problem.

After you have registered the provider using the provider method, you may switch to the new user provider in your auth.php configuration file. First, define a provider that uses your new driver:

Finally, you may use this provider in your guards configuration:

The User Provider Contract

The IlluminateContractsAuthUserProvider implementations are only responsible for fetching a IlluminateContractsAuthAuthenticatable implementation out of a persistent storage system, such as MySQL, Riak, etc. These two interfaces allow the Laravel authentication mechanisms to continue functioning regardless of how the user data is stored or what type of class is used to represent it.

Let's take a look at the IlluminateContractsAuthUserProvider contract:

The retrieveById function typically receives a key representing the user, such as an auto-incrementing ID from a MySQL database. The Authenticatable implementation matching the ID should be retrieved and returned by the method.

The retrieveByToken function retrieves a user by their unique $identifier and 'remember me' $token, stored in a field remember_token. As with the previous method, the Authenticatable implementation should be returned.

The updateRememberToken method updates the $user field remember_token with the new $token. A fresh token is assigned on a successful 'remember me' login attempt or when the user is logging out.

The retrieveByCredentials method receives the array of credentials passed to the Auth::attempt method when attempting to sign into an application. The method should then 'query' the underlying persistent storage for the user matching those credentials. Typically, this method will run a query with a 'where' condition on $credentials['username']. The method should then return an implementation of Authenticatable. This method should not attempt to do any password validation or authentication.

The validateCredentials method should compare the given $user with the $credentials to authenticate the user. For example, this method should probably use Hash::check to compare the value of $user->getAuthPassword() to the value of $credentials['password']. This method should return true or false indicating on whether the password is valid.

The Authenticatable Contract

Now that we have explored each of the methods on the UserProvider, let's take a look at the Authenticatable contract. Remember, the provider should return implementations of this interface from the retrieveById, retrieveByToken, and retrieveByCredentials methods:

Artisan Key Generate Not Working On Mac

This interface is simple. The getAuthIdentifierName method should return the name of the 'primary key' field of the user and the getAuthIdentifier method should return the 'primary key' of the user. In a MySQL back-end, again, this would be the auto-incrementing primary key. The getAuthPassword should return the user's hashed password. This interface allows the authentication system to work with any User class, regardless of what ORM or storage abstraction layer you are using. By default, Laravel includes a User class in the app directory which implements this interface, so you may consult this class for an implementation example.

Events

Laravel raises a variety of events during the authentication process. You may attach listeners to these events in your EventServiceProvider: