Laravel Session, File Upload/Download And Permissions

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This tutorial covers Laravel Session, file upload, download, file permission, Laravel authentication & authorization, sending emails, etc. with examples:

In the Laravel Forms And Validation Rules tutorial of the Laravel Tutorial series, we learned about different form elements with examples.

Further in this tutorial, we have also discussed how to set, get, delete session data under Laravel sessions, and how to send emails via Mailtrap in detail.

For all the examples, we have used Laravel version 7.

Laravel upload files, sessions

Prerequisites

In our previous tutorials, we have covered basic features of Laravel, database handling, and form handling, and you need to be familiar with those topics for a better understanding of this tutorial.

Let’s begin!

Laravel File Upload

Uploading files in Laravel is easy. The developer can also specify Laravel file permissions such as file types, size limits of the files that can be uploaded by the user, etc.

Laravel File Upload Example

In this example, we have created a simple form with validation to upload files.

Step 1: Run the following command in the command prompt to create a Laravel project named file-uploading-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 file-uploading-tutorial

Step 2: Add the following two routes to the routes/web.php file.

Route::get('file/upload','FileUploadController@create')->name('file.create'); 	
Route::post('file/upload','FileUploadController@store')->name('file.store');

Step 3: Run the following command in the command prompt to create FileUploadController and modify the existing code as shown below.

php artisan make:controller FileUploadController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function create() 
    
    {
        return view('create'); 
    } 
    
    public function store(Request $request)
    { 
        $request->validate(['file' => 'required|mimes:doc,docx,xlx,csv,pdf|max:1024']);

        $file_name = time().'.'.$request->file->extension();  

        $request->file->move(public_path('file uploads'), $file_name);

        return back()
            ->with('success','Successfully uploaded a file!')
            ->with('file',$file_name);
    }
}

Step 4: Create a view file named create.blade.php and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Uploading Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 </head>
<body>
    <div class="container mt-5">

        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        @if ($message = Session::get('success'))
            <div class="alert alert-success alert-block">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>{{ $message }}</strong>
            </div>
        @endif

        <h3>Laravel File Uploading</h3>

        <form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
            @csrf

            <div class="form-group">
                <label>File</label>
                <input type="file" class="form-control" name="file" id="file">
            </div>

            <input type="submit" name="submit" value="Submit" class="btn btn-dark">

        </form>
    </div>
</body>

</html>

Step 5: Create a folder named file uploads in the public folder. It is the folder where uploaded files are stored.

Step 6: Visit the following URL, and it will produce an output similar to the below screenshot.

Note: The following URL may differ from yours.

http://file-uploading-tutorial.test/file/upload

file uploads

Step 7: Now, you can upload a valid file and submit the form. Verify that the uploaded file is stored in the file uploads folder. You can also try to upload an invalid file (file with an invalid file type and/or size limit exceeded file) and submit the form to check the validation.

In the above example, the user is only allowed to submit doc, docx, xlx, csv, and pdf files with a maximum size of 1024 bytes.

Example 1: Uploading a pdf file that is less than 1024 bytes in size.

1024 bytes in size

Example 2: Uploading an image file (PNG, JPEG, etc.).

Uploading an image file

Example 3: Uploading a pdf file which is more than 1024 bytes in size.

Uploading a pdf

Laravel Session

A session is used to store user data across multiple user requests. It helps to keep track of the website users. Laravel session configuration can be done in the config/session.php file. By default, the file driver is used to handle session data.

Retrieving Laravel Session Data

First, you need to get an instance of a session that can be accessed via an HTTP request. Then, use the get() method to access data.

$session_data = $request->session()->get('key');

Storing Data In Laravel Session

There are two ways to store data in a session.

#1) Using the put() method – This method stores data via a request instance.

$request->session()->put('key', 'value');

#2) Using session helper – This method stores data via the global helper.

session(['key' => 'value']);

Deleting Laravel Session Data

The forgot() method is used to delete specific data from the session.

$request->session()->forget(key);

The flush() method is used to delete all data from the session.

Flash Data Using Laravel Session

The flash() method is also used to store data in a session but available for the next HTTP request only.

$request->session()->flash('status', Successful!');

Laravel Session Example

Let’s learn how to set, get, and delete session data by using a simple session example.

Step 1: Run the following command in the command prompt to create a Laravel project named session-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 session-tutorial

Step 2: Add the following three routes in the routes/web.php file.

Route::get('session/set','SessionController@store')->name('session.store');
Route::get('session/get','SessionController@index')->name('session.index');
Route::get('session/delete','SessionController@delete')->name('session.delete');

Step 3: Run the following command in the command prompt to create SessionController and modify the existing code as shown below:

php artisan make:controller SessionController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SessionController extends Controller
{
    public function index(Request $request) {
        if($request->session()->has('username'))
           echo $request->session()->get('username');
        else
           echo 'No session data.';
     }

     public function store(Request $request) {
        $request->session()->put('username','User A');
        echo "Session data stored.";
     }

     public function delete(Request $request) {
        $request->session()->forget('username');
        echo "Session data deleted.";
     }
}

Step 4: Visit the following URLs in the given order to set, get, and delete session data.

Note: The following URLs may differ from yours.

#1) Visit the following URL to set session data.

http://session-tutorial.test/session/set

It will produce an output similar to the below screenshot.

set session data

#2) Visit the following URL to get session data.

http://session-tutorial.test/session/get

It will produce an output similar to the below screenshot.

get session data

#3) Visit the following URL to delete session data.

http://session-tutorial.test/session/delete

It will produce an output similar to the below screenshot.

delete session data

#4) After deleting the session data, revisit the following URL.

http://session-tutorial.test/session/get

It will produce an output similar to the below screenshot.

session get repeat

Laravel Authentication

Laravel Authentication is simple. It is used to identify users. Usually, it is achieved by identifying the username and password of the user. If the user credentials are identified as valid, then the user is said to be an authenticated user.

The config/auth.php file is the authentication configuration file. Laravel authentication consists of guards and providers.

Guards: It defines how users are authenticated for each request.

Providers: It defines how users are retrieved from your persistent storage.

Further, you can also define additional providers as necessary. However, it need not change the default authentication configuration.

Please note that we have not discussed guards and providers in detail in this tutorial.

Authentication Example

In this example, we have created a simple Laravel 7 auth system.

Step 1: Run the following command in the command prompt to create a Laravel project named auth-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 auth-tutorial

Step 2: Connect your project to the database and run the following command in the command prompt to run default migrations.

php artisan migrate

Step 3: Run the following command in the command prompt to install the Laravel UI package.

composer require laravel/ui

Step 4: Next step is to generate auth scaffolding with Bootstrap, Vue, or React. You can run one of the following commands to create auth scaffolding.

Run the following command in the command prompt to generate auth scaffolding with Bootstrap.

php artisan ui bootstrap --auth

Run the following command in the command prompt to generate auth scaffolding with Vue.

php artisan ui vue --auth

Run the following command in the command prompt to generate auth scaffolding with React.

php artisan ui react --auth

Step 5: Run the following two commands in the command prompt to compile the fresh scaffolding by installing npm dependencies.

npm install
npm run dev

Step 6: Visit the following URLs to test authentication by creating a new user (registering a new user) and logging into the system. You can try both valid and invalid data to test authentication.

Note: The following URLs may differ from yours.

First, you need to register a new user. Visit the following URL to register a new user, and it will produce an output similar to the below screenshot.

http://auth-tutorial.test/register

Register

After registering a new user, login into the system by visiting the following URL, and it will produce an output similar to the below screenshot.

http://auth-tutorial.test/login

After registering a new user

A successful login will redirect the user to the home page/dashboard as shown below.

dashboard

Laravel Authorization

In simple terms, authorization verifies whether the authenticated users have the necessary permission to access the requested resources.

Authorization Example

In this example, we have created a simple Laravel 7 authorization system.

Step 1: Run the following command in the command prompt to create a Laravel project named authorization-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 authorization-tutorial

Step 2: Connect your project to the database.

Step 3: Run the following command in the command prompt to create the add_role_column_to_users_table migration and modify the existing code as shown below:

php artisan make:migration add_role_column_to_users_table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddRoleColumnToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->enum('role',  ['admin', 'manager', 'user'])->default('user');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

Step 4: Run the following command in the command prompt to run all the migrations.

php artisan migrate

Step 5: Add sample data to the Users table using tinker as shown below:

C:\laragon\www\authorization-tutorial
php artisan tinker
Psy Shell v0.10.4 (PHP 7.2.19 — cli) by Justin Hileman
>>> $user = new App\User;
=> App\User {#3260}
>>> $user->name = 'User A';
=> "User A"
>>> $user->email = 'admina@user.com';
=> "admina@user.com"
>>> $user->password = bcrypt('user123');
=> "$2y$10$E5hDEej0Cue1U5AY..tmR.Wd/YCo9LXN0kbqvX1por8Cdfi.NhGv6"
>>> $user->role = 'admin';
=> "admin"
>>> $user->save();
=> true

Step 6: Run the following command in the command prompt to install the Laravel UI package.

composer require laravel/ui

Step 7: Next step is to generate auth scaffolding with Bootstrap, Vue, or React. You can run one of the following commands to create auth scaffolding.

Run the following command in the command prompt to generate auth scaffolding with Bootstrap.

php artisan ui bootstrap --auth

Run the following command in the command prompt to generate auth scaffolding with Vue.

php artisan ui vue --auth

Run the following command in the command prompt to generate auth scaffolding with React.

php artisan ui react --auth

Step 8: Run the following two commands in the command prompt to compile the fresh scaffolding by installing npm dependencies.

npm install
npm run dev

Step 9: Open the AuthServiceProvider.php file at App/Providers and modify the existing code as shown below:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AppServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [

    ];

    public function boot()
    {
        $this->registerPolicies();

        Gate::define('isAdmin', function($user) {
           return $user->role == 'admin';

        });

        Gate::define('isManager', function($user) {
            return $user->role == 'manager';
        });

        Gate::define('isUser', function($user) {
            return $user->role == 'user';

        });      
    }
}

Step 10: Modify the existing code in the home.blade.php file as shown below:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div>

                <div class="card-body">
                @if (session('status'))
                    <div class="alert alert-success" role="alert">
                        {{ session('status') }}
                    </div>
                @endif

                @can('isAdmin')
                    <div class="btn btn-danger">
                        I am an admin.
                    </div>

                @elsecan('isManager')

                    <div class="btn btn-warning">
                        I am a manager.
                    </div>

                @else

                    <div class="btn btn-primary">
                        I am a user.
                    </div>

                @endcan

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 11: Visit the following URL, and it will produce an output similar to the below screenshot. Then, log into the system as an admin, a manager, and a user one at a time.

Note: The following URLs may differ from yours.

http://authorization-tutorial.test/login

authorization

  • Admin login

If you are logged in as an admin, then the output will be similar to the following screenshot.

admin

  • Manager login

If you are logged in as a manager, then the output will be similar to the following screenshot.

manager

  • User login

If you are logged in as a user, then the output will be similar to the following screenshot.

user

Sending Emails In Laravel

What Is Mailtrap

There are several free online tools available to test emails in Laravel, and Mailtrap is one such tool. Mailtrap uses a fake SMTP server to test emails. It accepts emails from the local host that allows the developer or tester to test how emails are going to be shared before sending them to real inboxes.

Sending Emails Example

Let’s do a simple example using Mailtrap.

Step 1: Run the following command in the command prompt to create a Laravel project named email-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 email-tutorial

Step 2: Visit the URL and create a new Mailtrap account or login into the Mailtrap account if you already have one.

Step 3: After login into the Mailtrap account,

#1) Click on Demo Inbox.

Demo Inbox

#2) Identify the Username and Password under SMTP. This username and password are unique, and we will use them in the next step.

Username and Password under SMTP

Note: Visit the URL to know more about Mailtrap.

Step 4: Open the .env file and enter your Mailtrap username and password.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME= enter your Mailtrap username here
MAIL_PASSWORD= enter your Mailtrap password here
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

Step 5: Add the following two routes to the routes/web.php file.

Route::get('/contact', 'ContactController@contact')->name('contact');
Route::post('/contact', 'ContactController@sendContactForm')->name('contact.send');

Step 6: Run the following command in the command prompt to create FileUploadController and modify the existing code as shown below.

php artisan make:controller ContactController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactMail;

class ContactController extends Controller
{
    public function contact()
    {
        return view('contact');
    }

    public function sendContactForm(Request $request)
    {
        $this->validate($request, [
            'name'    => 'required',
            'email'   => 'required|email',
            'subject' => 'required',
            'message' => 'required',
        ]);

        $data = array(
            'name'      =>  $request->name,
            'email'      =>  $request->email,
            'subject'      =>  $request->subject,
            'message'   =>   $request->message,
        );

        Mail::to('user@test.com')->send(new ContactMail($data));

        return redirect()->back()->with('success', 'Your message was submitted successfully. Thank you!');
    }
}

Step 7: Run the following command in the command prompt to create ContactMail class. This command will create a file named ContactMail.php in the App/Mail directory.

php artisan make:mail ContactMail

Step 8: Modify the existing code in the ContactMail.php file as shown below.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ContactMail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->data['email'])
            ->subject('Contact Form')
            ->view('contact-template')->with('data', $this->data);
    }
}

Step 9: Create the following view files and add the codes.

#1) Create the contact.blade.php file and add the following code.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Contact Us</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">

        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        @if ($message = Session::get('success'))
            <div class="alert alert-success alert-block">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>{{ $message }}</strong>
            </div>
        @endif

        <h3>Contact Us</h3>

        <form action="{{ route('contact.send') }}" method="POST">
            @csrf

            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control" name="name" value="{{ old('name') }}" required>
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email" value="{{ old('email') }}" required>
            </div>

            <div class="form-group">
            <label>Subject</label>
                <input type="text" class="form-control" name="subject" value="{{ old('subject') }}" required>
            </div>

            <div class="form-group">
                <label>Message</label>
                <textarea class="form-control" name="message" rows="5" required>{{ old('message') }}</textarea>
            </div>
            <div>
                <button type="submit" class="btn btn-dark">Send</button>
            </div>
        </form>
    </div>  
</body>
</html>

#2) Create the contact-template.blade.php file and add the following code.

<p>Name: {{ $data['name'] }}</p>

<p>Subject: {{ $data['subject'] }}</p>

<p>Message: {{ $data['message'] }}</p>

Step 10: Visit the following URL, and it will produce an output similar to the below screenshot.

Note: The following URL may differ from yours.

http://email-tutorial.test/contact

contact

Step 11: Fill the form and submit.

Step 12: Now, visit your Mailtrap account and check the inbox. You will see a new message in your inbox similar to the below screenshot.

test email

Conclusion

Laravel file upload is easy, and the developer can also set Laravel file permissions. Laravel provides an easy way to set, get, and delete session data. Laravel authentication helps to identify users while Laravel authorization verifies whether the authenticated users have the permission to access the requested resources.

We can use tools like Mailtrap to test emails before sending them to actual inboxes.

We hope you found this tutorial helpful! Hope to see you again in the next tutorial where we will discuss Laravel forge and collections.

Happy learning!

<< PREV Tutorial | NEXT Tutorial>>

Was this helpful?

Thanks for your feedback!

Leave a Comment