Welcome to Part 4 of our tutorial on creating the simplest CRUD (Create, Read, Update, Delete) application using Laravel. In this part, we will add authentication and authorization to our application. Additionally, we will explore deploying the application to a live server.
Step 14: Adding Authentication
Laravel makes it easy to add authentication to your application using the laravel/ui
package. This package provides a simple way to scaffold authentication views and routes.
Installing Laravel UI
First, we need to install the laravel/ui
package. Run the following command in your terminal:
composer require laravel/ui
Scaffolding Authentication
Next, scaffold the authentication views and routes by running the following command:
php artisan ui bootstrap --auth
This command will create the necessary views, routes, and controllers for authentication. After running the command, install the npm dependencies and compile the assets:
npm install && npm run dev
Migrating the Authentication Tables
Laravel’s authentication system requires some database tables to store users and password resets. Run the following command to create these tables:
php artisan migrate
Testing Authentication
Start the development server:
php artisan serve
Visit http://localhost:8000
in your web browser. You should see a login and registration link in the navigation bar. You can register a new user and log in to test the authentication system.
Step 15: Adding Authorization
Authorization ensures that only authorized users can perform certain actions. We’ll use Laravel’s built-in authorization features to restrict access to certain routes based on user roles.
Creating Middleware for Admin Role
We’ll create middleware to check if the user is an admin. Run the following command to create the middleware:
php artisan make:middleware AdminMiddleware
Open the newly created AdminMiddleware
located in the app/Http/Middleware
directory and update it as follows:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
public function handle(Request $request, Closure $next)
{
if (Auth::user() && Auth::user()->role == 'admin') {
return $next($request);
}
return redirect('home')->with('error', 'You do not have admin access.');
}
}
Registering the Middleware
Open the app/Http/Kernel.php
file and register the middleware:
protected $routeMiddleware = [
// Other middleware
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Applying the Middleware to Routes
Open the routes/web.php
file and apply the middleware to the routes you want to protect:
use App\Http\Controllers\ItemController;
Route::resource('items', ItemController::class)->middleware('admin');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Updating the User Model
To support roles, add a role
field to the users table. Create a migration to add the role
column to the users
table:
php artisan make:migration add_role_to_users_table --table=users
Update the migration file as follows:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddRoleToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('role')->default('user');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role');
});
}
}
Run the migration:
php artisan migrate
Update the User
model to include the role
field:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'role',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Setting Up Roles
To set up roles, you can manually assign the admin
role to specific users in your database. For simplicity, you can do this directly in the database using a database management tool like phpMyAdmin or by running a SQL command.
UPDATE users SET role = 'admin' WHERE email = '[email protected]';
Step 16: Deploying the Application
Deploying your Laravel application to a live server involves several steps. Here, we’ll cover the basic steps to deploy your application to a shared hosting environment.
Preparing for Deployment
- Environment Configuration: Set up your
.env
file with the production database and other configuration settings. - Database Migration: Ensure all database migrations are run on the production server.
- File Permissions: Ensure the
storage
andbootstrap/cache
directories are writable by the web server.
Uploading Files to the Server
- Zip Your Project: Zip your entire Laravel project, excluding the
vendor
andnode_modules
directories. - Upload the Zip File: Use an FTP client or your hosting control panel to upload the zip file to your server.
- Extract the Zip File: Extract the zip file in the desired directory on your server.
Setting Up the Environment
- Composer Install: Run
composer install
on the server to install the required PHP packages. - NPM Install and Build: If you have any front-end assets, run
npm install
andnpm run prod
to compile them. - Environment File: Set up your
.env
file with the correct production settings.
Configuring the Web Server
- Apache Configuration: If you are using Apache, make sure your
.htaccess
file is correctly set up. Create a virtual host configuration if necessary. - Nginx Configuration: If you are using Nginx, create a server block configuration for your site.
Running Migrations and Seeding
Run the following commands to migrate the database and seed any initial data:
php artisan migrate --force
php artisan db:seed --force
Clearing Cache
Clear the application cache to ensure everything is up to date:
php artisan config:cache
php artisan route:cache
php artisan view:cache
Testing the Application
Finally, test your application to ensure everything is working as expected. Visit your site in a web browser and check all functionality.
Conclusion
In this fourth part of the tutorial, we have added authentication and authorization to our CRUD application and explored deploying it to a live server. Your application is now more secure and ready for production.
This concludes our tutorial series on creating the simplest CRUD application in Laravel. Congratulations on making it this far! Continue exploring Laravel’s features to build even more powerful applications.