Laravel Controllers

In laravel framework controller plays very important role to separate business logic. When user hits the browser request it goes to a route first then it finds controller attached with route.

Controller either talks to model and get some data needed and respond via view layer. When working with laravel controller it it very important to know all the available methods and functionality that you can use while you are in a controller.

Once you know stuff that is available withing controller function then you can write efficient code. In this tutorial we will learn about things that you can use from laravel controller.

How to create a controller from terminal?

To create controller from terminal window, open the terminal and change directory to your laravel root folder. Once you are there you can run any of the following command to create controller.

# Create a simple blank controller
php artisan make:controller UserController

# Create resource full controller with CRUD methods
php artisan make:controller UserController --resource

Once you created a controller with above command a new controller file will be seen at app/Http/Controllers/UserController.php. A sample controller might look like following:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    
}

Create controller method that returns different responses

A laravel controller can contain different methods. Each method can have $request argument as a default function parameter. This is basically a request object that contains your form variables, session data or cookie information.

A controller method can respond via different response type some of them are mentioned as below:

  • Plain Text
  • Json Array
  • Html or twig view
  • XML
  • File download
  • PDF or Image output on browser directly etc...

Render plain text example

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        return "Hello, Sandip Patel";
    }
}

Render a twig view file located in resources/views folder

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        return view("dashboard");
    }
}

Render array as json or json array

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        // render array as json
        return [1, 2, 3];

        // render json array
        return response()->json([
            "name" => "Sandip Patel"
        ]);
    }
}

Render a text with extra headers

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        return response('Hello World', 200)
                ->header('Content-Type', 'text/plain');

        return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value1')
            ->header('X-Header-Two', 'Header Value2');
    }
}

Render a file or pdf

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        // render a file directly on broswer
        // i.e. image or pdf file
        return response()->file($pathToFile);
    }
}

Render file download

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        // download a file with given path
        return response()->download($pathToFile);

        // download a file with given path with different name and
        // pass some extra headers along with the new file name
        return response()->download($pathToFile, $name, $headers);

        // delete the file once download completes
        return response()->download($pathToFile)->deleteFileAfterSend();
    }
}

Redirect to internal or external urls

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        // redirect to last page with
        // submitted form data
        return back()->withInput();

        // redirect to user/dashboard page
        return redirect('user/dashboard');

        // redirect with named route
        return redirect()->route('login');

        // redirect with named route by passing variables
        return redirect()->route('profile', ['id' => 1]);


        // redirect to specific controller method
        return redirect()->action('HomeController@index');


        // redirect to external url
        return redirect()->away('https://www.google.com');

        // redirect with flash session message
        return redirect('dashboard')->with('success', 'Profile updated!');
    }
}

Working with form data, sessions and cookies

Sometimes you might have to work on sessions, cookies and form data. Below methods are available when working with sessions, cookies and forms.

Work with sessions in controller

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example(Request $request)
    {
        // get all session data
        $data = $request->session()->all();

        // get a name variable from session store
        $name = $request->session()->get('name');

        // get a name from the session store if not available return default name
        $name = $request->session()->get('name', 'Sandip Patel');

        // store provided name in session store
        $request->session()->put('name', "Sandip Patel");

        // push a new item to array in session store
        $request->session()->push('user.teams', 'developers');

        // flush the session data
        $request->session()->flush();

        // re-generate new session id
        $request->session()->regenerate();

        // delete data from the session
        $request->session()->forget('key');
        $request->session()->forget(['key1', 'key2']);

        // create a new flash session variable to use in view file
        $request->session()->flash('success', 'Task was successful!');

        // get the data from the session and delete the key afterwards
        $value = $request->session()->pull('key', 'default');

        // check to see if item present in the session
        // it returns true if item does exist with not null value
        if ($request->session()->has('users')) {
            //
        }

        // check to see if item present in the session
        // returns true if item does exists with or without null value
        if ($request->session()->exists('users')) {
            //
        }

        // get a piece of data from the session
        // using global helper function
        $name = session('name');

        // Specifying a default value...
        // using global helper function
        $name = session('name', 'default');

        // store session data
        session(['key' => 'value']);
    }
}

Working with cookies

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class UserController extends Controller
{
    function example(Request $request)
    {
        // get cookie from request
        $value = $request->cookie('name');

        // get cookie using facade
        $value = Cookie::get('name');

        // create a new cookie that lasts for next 5 minutes
        // response data with newly created cookie
        return response()->withCookie(cookie('name', 'Sandip Patel', 5));
    }
}

Working with form data

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example(Request $request)
    {
        // get all form data
        $input = $request->all();

        // get the name from the form data
        $name = $request->input('name');

        // get name field from the form and pass default value
        $name = $request->input('name', 'Sally');

        // access array key from form data
        $name = $request->input('products.0.name');
        $names = $request->input('products.*.name');

        // access json key from the request data
        $name = $request->input('user.name');

        // get all fields except credit_card field
        $input = $request->except('credit_card');

        // fetch only few keys from the form data
        $input = $request->only(['username', 'password']);

        // get all query variables
        $query = $request->query();

        // get name from querystring
        $name = $request->query('name');
        $name = $request->query('name', 'Helen');

        // The old method will pull the previously flashed input data from the session:
        $username = $request->old('username');

        // has method returns true if the value is present on the request:
        if ($request->has('name')) {
            //
        }

        // check if multiple fields are present
        if ($request->has(['name', 'email'])) {
            //
        }

        // The hasAny method returns true if any of the specified values are present:
        if ($request->hasAny(['name', 'email'])) {
            //
        }

        // If you would like to determine if a value is present on the request and is not empty
        if ($request->filled('name')) {
            //
        }

        // To determine if a given key is absent from the request
        if ($request->missing('name')) {
            //
        }

        // get file field
        $file = $request->file('photo');

        // check if file uploaded is valid file
        if ($request->file('photo')->isValid()) {
            //
        }

        // get path and extension of a file
        $path = $file->path();
        $extension = $file->extension();

        // store file in storage/images folder
        $path = $file->store('images');

        // store file with different name in storage/images
        $path = $file->storeAs('images', 'filename.jpg');
    }
}

Hope this tutorial is useful for developer seeking for quick methods. Please share your love if you like this article.