Laravel Redirect

Laravel redirects are those which transport the user from one page to another. This page may be a different web page altogether or within the same website. Redirects help the users to visit other parts of the page or get relevant information about the same subject, without having to hunt for it themselves. Toggle navigation Laravel API. Classes; Namespaces; Interfaces; Traits; Index; Search; class; Illuminate Support Facades Redirect; Redirect class Redirect. 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! 画面遷移系の関数でちょくちょくこんがらがるのでまとめときます 例としてここでのルーティングは以下の通りです web.php Route::resource('users', 'UsersController'); rou. When Laravel generates a redirect response due to a validation error, the framework will automatically flash all of the request's input to the session. This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit.

  • Creating Responses
  • Redirects
  • Other Response Types

Creating Responses

Strings & Arrays

All routes and controllers should return a response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

{tip} Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

Response Objects

Typically, you won't just be returning simple strings or arrays from your route actions. Instead, you will be returning full IlluminateHttpResponse instances or views.

Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the SymfonyComponentHttpFoundationResponse class, which provides a variety of methods for building HTTP responses:

Eloquent Models & Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model's hidden attributes:

Laravel redirect to url

Attaching Headers To Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

Cache Control Middleware

Laravel includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Attaching Cookies To Responses

You may attach a cookie to an outgoing IlluminateHttpResponse instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie method:

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to 'queue' cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

Generating Cookie Instances

If you would like to generate a SymfonyComponentHttpFoundationCookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

Expiring Cookies Early

You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

If you do not yet have an instance of the outgoing response, you may use the Cookie facade's expire method to expire a cookie:

Cookies & Encryption

By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the AppHttpMiddlewareEncryptCookies middleware, which is located in the app/Http/Middleware directory:

Redirects

Laravel Redirect Back

Redirect responses are instances of the IlluminateHttpRedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:

Redirecting To Named Routes

When you call the redirect helper with no parameters, an instance of IlluminateRoutingRedirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

If your route has parameters, you may pass them as the second argument to the route method:

Populating Parameters Via Eloquent Models

If you are redirecting to a route with an 'ID' parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (/profile/{id:slug}) or you can override the getRouteKey method on your Eloquent model:

Redirecting To Controller Actions

You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method:

If your controller route requires parameters, you may pass them as the second argument to the action method:

Redirecting To External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

Redirecting With Flashed Session Data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:

Redirecting With Input

Laravel

You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:

Other Response Types

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the IlluminateContractsRoutingResponseFactorycontract is returned. This contract provides several helpful methods for generating responses.

View Responses

Laravel Redirect

If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method:

Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.

JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

File Downloads

The download method may be used to generate a response that forces the user's browser to download the file at the given path. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

{note} Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

Streamed Downloads

Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application's service providers, such as the AppProvidersAppServiceProvider service provider:

The macro function accepts a name as its first argument and a closure as its second argument. The macro's closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:

There is no way to avoid the topic of RESTful APIswhen building backend resources for a mobile application or using any of the modern JavaScript frameworks. If by chance you are unaware, an API is an interface or code in this case, that allows two software programs to communicate with each other. Notably, it does not maintain session state between requests, hence, you will need to use tokens to authenticate and authorize users of your application.

Laravel makes building such a resource easy with a predefined provision for you to secure it appropriately. This tutorial will teach you how to build and secure your Laravel back-end API using Laravel passport. When we are finished, you will have learned how to secure your new Laravel API or provide an extra layer of security to existing ones.

Prerequisites

Basic knowledge of building applications with Laravel will be of help in this tutorial. Also, you need to ensure that you have installed Composer globally to manage dependencies. Lastly, Postman will be needed to test our endpoints.

What We’ll Build

To demonstrate how to build a secure Laravel API, we’ll build an API that will be used to create a list of top tech CEOs. This application will list the following about each CEO:

  • Name
  • The year they became CEO
  • Headquarters of their company and
  • What their company does

To secure this application, we will install Laravel Passport and generate an access token for each user after authentication. This will allow such users to have access to some of the secured endpoints.

Getting Started

To begin, you can either use Composer or Laravel installer to quickly scaffold a new Laravel application on your computer. Follow the instructions here on Laravel's official website to set up the Laravel installer. Once you are done, run the following command:

To install the same application using Composer run the following command:

Depending on your preferred choice, the preceding commands will create a new folder named laravel-backend-api within the development folder, you installed Laravel and its dependencies in.

You can move into the newly created folder and run the application using the in built-in Laravel Artisan command as shown here:

Navigate to http://localhost:8000 from your browser to view the welcome page:

Create a Database and Connect to It

Now that Laravel is installed and running, the next step is to create a connection to your database. First, ensure that you have created a database and then update the values of the following variables within the .env file:

  • DB_DATABASE
  • DB_USERNAME
  • DB_PASSWORD

The database is all set, but before we start building our API, we need to install and configure Laravel Passport.

Install And Configure Laravel Passport

Laravel Passport provides a full 0Auth2 server implementation for Laravel applications. With it, you can easily generate a personal access token to uniquely identify a currently authenticated user. This token will then be attached to every request allowing each user access protected routes. To begin, stop the application from running by hitting CTRL + C on your computer’s keyboard and install Laravel Passport using Composer as shown here:

Once the installation is complete, a new migration file containing the tables needed to store clients and access tokens will have been generated for your application. Run the following command to migrate your database:

Next, to create the encryption keys needed to generate secured access tokens, run the command below:

Immediately after the installation process from the preceding command is finished, add the LaravelPassportHasApiTokens trait to your AppUser model as shown here:

One of the benefits of this trait is the access to a few helper methods that your model can use to inspect the authenticated user’s token and scopes.

Now, to register the routes necessary to issue and revoke access tokens (personal and client), you will call the Passport::routes method within the boot method of your AuthServiceProvider. To do this, open the app/Providers/AuthServiceProvider file and update its content as shown below:

After registering Passport::routes(), Laravel Passport is almost ready to handle all authentication and authorization processes within your application.

Finally, for your application to be ready to use Passport’s TokenGuard

to authenticate any incoming API requests, open the config/auth configuration file and set the driver option of the api authentication guard to passport:

Create a Migration File for the Company

Every new installation of Laravel comes with a pre-generated User model and migration file. This is useful for maintaining a standard database structure for your database. Open the app/User.php file and ensure that it is similar to this:

Also for the user migration file in database/migrations/***_create_users_table.php:

The fields specified in the file above will suffice for the credentials required from the users of our application, hence there will be no need to modify it.

Next, we will use the artisan command to create a model instance and generate a database migration file for the CEO table:

The preceding command will create a model within the app directory and a new migration file in database/migrations folder. The -m option is short for --migration and it tells the artisan command to create a migration file for our model. Next, open the newly created migration file and update its content as shown here:

Here, we included name, company_name, year, company_headquarters and what_company_does fields.

Now open the app/CEO.php file and use the following content for it:

Here, we specified the attributes that should be mass assignable, as all Eloquent models protect against mass-assignment by default.

Run the migration command again to update the database with the newly created table and fields using the following command:

Now that the database is updated, we will proceed to create controllers for the application. We will also create a couple of endpoints that will handle registration, login, and creating the details of a CEO as explained earlier.

Create controllers

Controllers accept incoming HTTP requests and redirect them to the appropriate action or methods to process such requests and return the appropriate response. Since we are building an API, most of the responses will be in JSON format. This is mostly considered the standard format for RESTful APIs.

Authentication controller

We will start by using the artisan command to generate an Authentication Controller for our application. This controller will process and handle requests for registration and login for a user into the application.

This will create a new API folder within app/Http/Controllers and then creates a new file named AuthController.php within it. Open the newly created controller file and use the following content for it:

The register method above handled the registration process for users of our application. To handle validation and ensure that all the required fields for registration are filled, we used Laravel’s validation method. This validator will ensure that the name, email, password and password_confirmation fields are required and return the appropriate feedback.

Lastly, the login method ensures that the appropriate credentials are inputted before authenticating a user. If authenticated successfully, an accessToken is generated to uniquely identify the logged in user and send a JSON response. Any subsequent HTTP requests sent to a secured or protected route will require that the generated accessToken be passed as an Authorization header for the process to be successful. Otherwise, the user will receive an unauthenticated response.

Creating the CEOController

Here, you will use the same artisan command to automatically create a new controller. This time around we will create an API resource controller. Laravel resource controllers are controllers that handle all HTTP requests for a particular Model. In this case, we want to create a controller that will handle all requests for the CEO model, which include creating, reading, updating, and deleting. To achieve this, run the following command:

The command above will generate an API resource controller that does not include the create and edit view since we are only building APIs. Navigate to app/Http/Controllers/API/CEOController.php and update its contents as shown below:

A quick view at the code snippet above shows that we created five different methods; each housing logic to carry out a particular function. Here is an overview of what each method does:

  • index: This method retrieves the entire list of CEOs from the database and returns it as a resource collection in a JSON structure. More details about the Laravel resource collection will be shared in the next section.
  • store: This method receives the instance of the HTTP request to create new CEO details via dependency injection using $request to retrieve all the values posted. It also ensures that all the required fields are not submitted as an empty request. Lastly, it returns the information of the newly created CEO details as a JSON response.
  • show: This method uniquely identifies a particular CEO and returns the details as a JSON response.
  • update: This receives the HTTP request and the particular item that needs to be edited as a parameter. It runs an update on the instance of the model passed into it and returns the appropriate response.
  • `destroy: This method receives the instance of a particular item that needs to be deleted and removes it from the database.

Some methods require a specific model ID to uniquely verify an item such as show() , update(), and destroy(). One thing to note here is that we were able to inject the model instances directly. This is due to using implicit route model binding in Laravel.

Once in place, Laravel will help to inject the instance CEO into our methods and return a 404 status code if not found. This makes it very easy to use the instance of the model directly, without necessarily running a query to retrieve the model that corresponds to that ID.

You can read more about implicit route model binding here on the official documentation of Laravel.

Create a Resource

Laravel Eloquent resources allow you to convert your models and collections into JSON format. It works as a data transformation layer between the database and the controllers. This helps provide a uniform interface that can be used wherever you need it within your application. Let’s create one for our CEO model by using the following command:

This will create a new resource file named CEOResource.php within the app/Http/Resources directory. Go ahead and open the newly created file. The content will look like this:

The parent::toArray($request) inside the toArray() method will automatically convert all visible model attributes as part of the JSON response.

Gain a deeper understanding of the benefits offered by Eloquent resources here.

Update Routes File

To complete the set up of the endpoints for the methods created within our controllers, update the routes.api.php file with the following contents:

To view the entire list of the routes created for this application, run the following command from the terminal:

You will see similar contents as shown below:

This will give you an idea of all the routes for our application.

NOTE: Please bear in mind that all the routes inside the routes/api.php file will be prefixed with /api/, hence you will need to include that when sending HTTP requests to the endpoints created earlier.

Run the Application

Laravel Redirect With Data

Now, test all the logic implemented so far by running the application with:

We will use Postman for the remainder of this tutorial to test the endpoints. Download it here if you don’t have it installed on your machine.

Register user

To register a user, send a POST HTTP request to this endpoint http://localhost:8000/api/register and input the appropriate details as shown here:

Now, your details might not be similar to this, but here is what the key and value of your requests should look like:

Login

Once the registration is successful, you can proceed to http://localhost:8000/api/login and enter your details to get authenticated:

Now, assuming that you used the same key and value specified in the previous section, your request should be similar to this:

Add Bearer token

After the login, copy the value of the access_token from the response and click on the Authorization tab and select Bearer Token from the dropdown and paste the value of the access_token copied earlier:

Create CEO

Next, create a new CEO with the details similar to the one shown below:

Fetch the list of CEOs

To retrieve the list of CEOs created so far, send a GET HTTP request to this endpoint http://localhost:8000/api/ceo as shown below:

Show CEO

View the details of a particular CEO by sending a GET HTTP request to this URL http://localhost:8000/api/ceo/1:

Please note that 1 is used for the endpoint here to specify the id of a particular record that needs to be retrieved from the database. You can target any record here using the id.

Edit CEO

Laravel Redirect Back

Delete CEO

Laravel Redirectresponse

Conclusion

In this tutorial, we have learned how to secure any RESTful API built with Laravel using Laravel Passport. The example created in this tutorial covers the basic CRUD (create, read, update and delete) processes required by most applications.

Laravel Redirect Post

I hope this gives you a solid foundation that can be improved on for your existing project and new ones. Please feel free to explore the codebase of this application by downloading it here on GitHub.

For more information about Laravel and Laravel Passport, don’t hesitate to visit the official documentation.

Olususi Oluyemi is a tech enthusiast, programming freak, and a web development junkie who loves to embrace new technology.

  • Twitter: https://twitter.com/yemiwebby
  • GitHub: https://github.com/yemiwebby
  • Website: https://yemiwebby.com.ng/