In this tutorial, we will build our tour guide application. We will not do anything complicated so we can rapidly get to adding multilingual support. We will build the base application and make it work without any additional language or region support. In chapters following, we will look at adding all of that support.
In the part 1, we looked at what an international application should be like. We covered some fundamental issues to consider when building an international application. We differentiated between what a multilingual application is and what a multi-regional application is. We also addressed what to do when building any of such applications.
We are going to build a simple tour guide that will help users book our services. This service rendered will help users take a tour of our city. It will allow them to set a time and date they want the tour and how many persons they will come with.
The application will have a simple dashboard that serves as mission control for the administrator. It will let the admin see who booked a tour when they want the tour and where they want to tour.
Finally, it will have a page that lists all the destinations users can tour. Users will also be able to click a link to see more information about their desired destination.
To begin, we need to create a Laravel application. We will use the Laravel installer to make it easy and fast. Run the following command:
1$ laravel new tourGuide 2 $ cd tourGuide
It will create the Laravel application, make the .env
file and set the application. If you run php artisan serve
, your application will come up right away.
We will use SQLite
as our database. Create the SQLite
database with the following command:
$ touch database/database.sqlite
Then, update your .env
file to use SQLite
1// replace 2 DB_CONNECTION=mysql 3 DB_HOST=127.0.0.1 4 DB_PORT=3306 5 DB_DATABASE=homestead 6 DB_USERNAME=homestead 7 DB_PASSWORD=secret 8 9 // with 10 DB_CONNECTION=sqlite 11 DB_DATABASE=/absolute/path/to/database.sqlite
Next thing we want to do is make the models and accompanying migrations for the database our application will use. It is important to plan this ahead of time to reduce the number of changes we will make to our application later.
For the tour guide, we want the following:
Now that we are clear on what we want to make, let us create the model, controller and migrations for them:
1$ php artisan make:model Destination -mr 2 $ php artisan make:model Booking -mr
There is a
User
model that ships with Laravel, so we will use it. It also comes with a migration file as well. Since we only register users, we will not need aUser
controller.
Next, we edit the migration files. Open the users migration file in ./database/migrations
and replace with this:
1// database/migrations/<timestamp>_create_users_table.php 2 <?php 3 4 use Illuminate\Support\Facades\Schema; 5 use Illuminate\Database\Schema\Blueprint; 6 use Illuminate\Database\Migrations\Migration; 7 8 class CreateUsersTable extends Migration 9 { 10 public function up() 11 { 12 Schema::create('users', function (Blueprint $table) { 13 $table->increments('id'); 14 $table->string('name'); 15 $table->string('email')->unique(); 16 $table->string('country'); 17 $table->string('phone'); 18 $table->boolean('is_admin')->default(false); 19 $table->string('password'); 20 $table->rememberToken(); 21 $table->timestamps(); 22 }); 23 } 24 25 public function down() 26 { 27 Schema::dropIfExists('users'); 28 } 29 }
Open the destinations migration file and replace with this:
1// database/migrations/<timestamp>_create_destinations_table.php 2 <?php 3 4 use Illuminate\Support\Facades\Schema; 5 use Illuminate\Database\Schema\Blueprint; 6 use Illuminate\Database\Migrations\Migration; 7 8 class CreateDestinationsTable extends Migration 9 { 10 public function up() 11 { 12 Schema::create('destinations', function (Blueprint $table) { 13 $table->increments('id'); 14 $table->string('name'); 15 $table->string('image'); 16 $table->json('description'); 17 $table->string('location'); 18 $table->timestamps(); 19 }); 20 } 21 22 public function down() 23 { 24 Schema::dropIfExists('destinations'); 25 } 26 }
Open the bookings migration file and replace with this:
1// database/migrations/<timestamp>_create_bookings_table.php 2 <?php 3 4 use Illuminate\Support\Facades\Schema; 5 use Illuminate\Database\Schema\Blueprint; 6 use Illuminate\Database\Migrations\Migration; 7 8 class CreateBookingsTable extends Migration 9 { 10 public function up() 11 { 12 Schema::create('bookings', function (Blueprint $table) { 13 $table->increments('id'); 14 $table->unsignedInteger('destination_id'); 15 $table->unsignedInteger('user_id'); 16 $table->unsignedInteger('number_of_tourists'); 17 $table->datetime('visit_date'); 18 $table->timestamps(); 19 }); 20 } 21 22 public function down() 23 { 24 Schema::dropIfExists('bookings'); 25 } 26 }
Our migration files are now ready. We made them mirror the information we want to store. Next, we will edit the models to make them access our database correctly.
Open the User
model in ./app
and replace with the following:
1// app/User.php 2 <?php 3 4 namespace App; 5 6 use Illuminate\Notifications\Notifiable; 7 use Illuminate\Foundation\Auth\User as Authenticatable; 8 9 class User extends Authenticatable 10 { 11 use Notifiable; 12 13 protected $fillable = [ 14 'name', 'email', 'country', 'phone', 'password', 15 ]; 16 17 protected $hidden = [ 18 'password', 'remember_token', 19 ]; 20 21 public function bookings() 22 { 23 return $this->hasMany(Booking::class); 24 } 25 }
Open the Destination
model and edit:
1// app/Destination.php 2 <?php 3 4 namespace App; 5 6 use Illuminate\Database\Eloquent\Model; 7 8 class Destination extends Model 9 { 10 protected $fillable = [ 11 'name', 'image', 'location', 'description' 12 ]; 13 14 public function bookings() 15 { 16 return $this->hasMany(Booking::class); 17 } 18 }
Open the Booking
model and edit:
1// app/Booking.php 2 <?php 3 4 namespace App; 5 6 use Illuminate\Database\Eloquent\Model; 7 8 class Booking extends Model 9 { 10 protected $fillable = [ 11 'user_id', 'destination_id', 'number_of_tourists', 'visit_date' 12 ]; 13 14 protected $dates = [ 15 'created_at', 16 'updated_at', 17 'visit_date' 18 ]; 19 20 public function user() 21 { 22 return $this->belongsTo(User::class); 23 } 24 25 public function destination() 26 { 27 return $this->belongsTo(Destination::class); 28 } 29 }
And that is all the edits needed for our models now, we will update them as we progress.
Run the following command to create the database tables:
$ php artisan migrate
For the controllers, we need to keep it very simple. In subsequent chapters, we will extend the controllers to serve content based on the language a user requests. All the controllers can be found in ./app/Http/Controllers
directory.
The first thing we want to do is edit the RegisterController
to include the phone
and country
fields. Open Auth/RegisterController.php
and edit:
1<?php 2 3 namespace App\Http\Controllers\Auth; 4 [...] 5 6 class RegisterController extends Controller 7 { 8 [...] 9 10 protected function validator(array $data) 11 { 12 return Validator::make($data, [ 13 'name' => 'required|string|max:255', 14 'email' => 'required|string|email|max:255|unique:users', 15 'phone' => 'required|string|unique:users', 16 'country' => 'required|string|max:255', 17 'password' => 'required|string|min:6|confirmed', 18 ]); 19 } 20 21 protected function create(array $data) 22 { 23 return User::create([ 24 'name' => $data['name'], 25 'email' => $data['email'], 26 'phone' => $data['phone'], 27 'country' => $data['country'], 28 'password' => Hash::make($data['password']), 29 ]); 30 } 31 }
Storing countries as a string means each user will type in their country. This is not very efficient because it will leave our database with a lot of redundant data. For this tutorial, we will ignore that since we will not be going live with it. If you intend to go live with it, please consider creating a table with countries and link them using their
id
. Learn about database normalization.
In our destination controller, we want to list all the destinations we tour. We also want to give users the ability to click on a destination and see more information on it. So, we are going to create a few methods to return the data we want.
Open the DestinationController
and replace with the following:
1// app/Http/Controllers/DestinationController.php 2 <?php 3 4 namespace App\Http\Controllers; 5 6 use App\Destination; 7 use Illuminate\Http\Request; 8 9 class DestinationController extends Controller 10 { 11 public function index() 12 { 13 $destinations = Destination::all(); 14 return view('destination.index', compact('destinations')); 15 } 16 17 public function show(Destination $destination) 18 { 19 return view('destination.show', compact('destination')); 20 } 21 }
We will seed our destination table so there will be no need to create methods for creating, updating or deleting destination records. This is to keep it simple.
The booking controller should show us what users booked and also help users book tours. Open the controller and replace with the following:
1// app/Http/Controllers/BookingController.php 2 <?php 3 4 namespace App\Http\Controllers; 5 6 use App\Booking; 7 use Illuminate\Http\Request; 8 use Illuminate\Support\Facades\Validator; 9 use Carbon\Carbon; 10 use Auth; 11 12 class BookingController extends Controller 13 { 14 public function __construct() 15 { 16 $this->middleware('auth'); 17 $this->middleware('admin')->only(['index']); 18 } 19 20 public function index() 21 { 22 $bookings = Booking::with(['destination','user'])->get(); 23 return view('booking.index',compact('bookings')); 24 } 25 26 public function create(\App\Destination $destination) 27 { 28 return view('booking.create',compact('destination')); 29 } 30 31 public function store(Request $request) 32 { 33 $validator = Validator::make($request->all(), [ 34 'destination_id' => 'required|integer', 35 'number_of_tourists' => 'required|integer', 36 'visit_date' => 'required' 37 ]); 38 $validator->validate(); 39 $input = $request->only(['destination_id', 'number_of_tourists', 'visit_date']); 40 $input['user_id'] = Auth::id(); 41 $input['visit_date'] = Carbon::createFromFormat('m/d/Y',$input['visit_date'])->toDateTimeString(); 42 43 $booking = Booking::create($input); 44 return redirect('/home'); 45 } 46 47 public function userPage() 48 { 49 $bookings = Auth::user()->bookings()->with('destination')->get(); 50 return view('booking.userpage', compact('bookings')); 51 } 52 }
Our booking controller has a constructor that defines a middleware for checking each request to it. We defined the auth
middleware to ensure that only logged in users can access the pages linked to this controller.
We then defined an admin
middleware to be sure ONLY admin users can see the page tied to the index
method. We will define the admin middleware below.
Middlewares are called in Laravel in the order which they are placed like first, second, … If the execution of a middleware is dependent on say
auth
, you have to place theauth
middleware before it. This also applies to using route groups and adding middlewares to it.
In our index
method, we are fetching all bookings and eager loading the users and destinations tied to them. This is a good option since we intend to use the data. It saves us some time with the number of queries we have to run and will make our application faster.
The create
method returns the form for making a booking with information on the destination the user had clicked on from the previous page.
The store
method stores the booking a user made. Because we set bootstrap datepicker to return the date in a format that is easy for users to read, we are doing a second conversion to a format that our application stores.
The userPage
method returns the bookings the logged in user made with the destination information eager loaded.
We will use Laravel’s authentication scaffolding. To generate it, run the following command:
$ php artisan make:auth
This will publish the authentication routes in routes/web.php
and also create the view files for different authentication actions like registration, login and more. They are all connected to the respective controllers handling them so we will not worry about setting that up anymore.
When we use the scaffolding, it makes the /home
route, which is where logged in users are redirected to. We can change this to what we want in the LoginController
. For this app, we are going to set the route as the default for regular users and redirect admin users.
First, open .app/Http/Controllers/Auth/LoginController.php
and add the following:
1[...] 2 use Illuminate\Http\Request; 3 4 class LoginController extends Controller 5 { 6 [...] 7 protected function authenticated(Request $request, $user) 8 { 9 if ($user->is_admin) { 10 return redirect('/dashboard'); 11 } 12 } 13 }
Now, when an admin user logs in, they get redirected to dashboard
. We are going to make a middleware to restrict access to the dashboard page.
Middleware in Laravel provides a convenient mechanism for filtering HTTP requests entering our application. This middleware is going to check if a logged in user has an administrator account or not. This is important since we use a single users table for both regular users and administrators.
Run the following command to create the middleware:
$ php artisan make:middleware IsAdmin
Then open the IsAdmin
middleware file in ./app/Http/Middleware
and add the following:
1<?php 2 3 namespace App\Http\Middleware; 4 5 use Closure; 6 7 class IsAdmin 8 { 9 public function handle($request, Closure $next) 10 { 11 if (!$request->user()->is_admin) { 12 abort(404); 13 } 14 return $next($request); 15 } 16 }
Next, we register the route in ./app/Http/Kernel.php
:
1protected $routeMiddleware = [ 2 'admin' => \App\Http\Middleware\IsAdmin::class, 3 [...] 4 ];
We used this middleware in our booking controller to protect the index
method. This middleware will only allow admin users to see the page containing all bookings while other non-admin users are directed to a lovely 404 page.
We have looked at what an international application is and different things to consider when making the application. We also got started on a simple application for tourists to book a tour guide service.
In the part 3, we will make the views for all of our pages. We will make the styles for multi-language support and make the pages as well. Then, we can proceed to adding content in multiple languages and see how to show content based on the users language.
The source code to the application in this article is available on GitHub.