How to Build a Laravel Website (Basic Steps After Installation)

Basic Steps After Installing Laravel 5.4

You have successfully installed Laravel 5.4 and you have directed the domain name at the public directory and you can see then Laravel test page. What next? Assuming that you are going to be using a database to run your website, here are some basic steps in how to build a Laravel website from the Laravel test page.

For this simple example, this guide may work for Laravel 5.x but this guide is specifically for Laravel 5.4.

Contents

Useful Commands
1) The Database
2) The .env file
3) The Model
4) The Migration
5) The Route
6) The Controller
7) The View
Conclusion
Errors and Solutions

Useful Commands

If you want to clear Composer cache (-o flag means optimized)… composer dump-autoload -o

Die and dump, like var_dump($variable); would be this in Laravel… dd($variable);

List all Artisan commands help… php artisan list then look at the help file for a specific command php artisan help controller:make

Run tinker… php artisan tinker. Then, exit with “q” or CTRL-C.

1) The Database

Create the database and give it a user.

2) The .env file

Add the database login info to the .env file which should be in your root (the level below “public“).

While you’re there you may aswell update as much of the info in the .env file as you can. If the name of the website has a space in it remember to use quotes. Not using quotes will cause an error.

You can also update the config/app.php file. If you get errors after updating this file double-check the permissions and ownerships and you may need to run composer dump-autoload -o afterwards if errors persist.

3) The Model

Laravel is an MVC framework. It is designed to use Models, Controllers and Views.

In this simple example, we’re just going to list some data from a database onto the page. The data we want to display are some names. One way to make a Controller for “names” is using Artisan like this… php artisan make:controller NameController. You can make the Model and the Controller separately, but we also need a Migration, why not make all three together in Artisan like this…

php artisan make:model Name -mc

The -mc literally means to create a Migration and a Controller at the same time as the Model.

If the Model is Name (capitalized and singular), the Controller would be NameController (camelcase), the Migration would be create_names_table, and the resulting table would be names (lowercase, plural). The Models are in the app directory.

Using this method the Model is already using Laravel’s database engine, Eloquent, and because of the naming convention, the Model knows which database it is connected to so we do not have to add it manually.

The Model can contain relationships and scopes, but in this simple example, we will not alter it at all.

4) The Migration

The Migration files are created for you in Step 3, they will be in the database/migrations directory. Now, you have to modify them for the data you want to use. I only want each name to have an ID and the name itself in this example, so I can modify the Migration to look like this using Laravel’s Schema…

public function up()
{
Schema::create('names', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
}

Here, id is an incremental integer and name is a string. For more database column types you can use in Migrations see Adding Columns. You can also specify indexes, foreign keys and set a default value for a column in the Database: Migrations.

Then, php artisan migrate builds the info from the Migration tables in the database.

If you change the migrations you can rollback and then make the migrations again with

php artisan migrate:refresh

5) The Route

Once you have a Controller and Model you can make a simple route. The routes directory has a file called “web.php”…

Route::get('/', '[email protected]');

'/' means when the URL is the root domain Laravel will call the Controller and method in the second parameter.

NameController is the name of the Controller that was created in Step 3.

index is the method we want to use. There are up to 7 default behaviours that a Controller should have: index, create, store, show, edit, update, and destroy. These methods within a Controller are called actions. If you find that your controller needs more than these 7 actions it may be a good idea to create a new Controller.

6) The Controller

The Controller is the file “NameController.php” that lives in the app/Http/Controllers directory. From Step 5, we said that we wanted to use the index method because we just want to list all the names. To do this we can use Eloquent and the all() function to simply grab all the rows from the table…

use App\Name;
public function index ()
{
$names= Name::all();
return view ( 'names.index', compact('names') );
}

If you “use” the Model in this way at the top, use App\Name;, you can refer to the Model in the methods like this Name::all(); as opposed to App/Name::all();. Instead of using all() you could also use Eloquent but order the results differently using get()

$names = Name::orderBy('name', 'desc')->get();

The same thing as all() but not using Eloquent would be…

$names= \DB::table('names')->get();

The \ is needed in front of the DB because you are inside the Controller and the DB class exists outside of it. Or, just “use” DB at the top of the controller, see Queries.

Out of these two different ways to interact with the database, it is better to use Eloquent and to keep most of the database-related logic inside the Model. In more complex projects than this example, the Model would contain Scopes and Statics that can be referred to from other places, such as Controllers.

The 'names.index' is the View we want to use and compact('names') is a way to pass the $names array into the View, alternative ways are listed in Passing Data to Views, for example…

return view('names.index')->with('name', $name);

7) The View

In the Controller we said the View we wanted to use was names.index. This means that Laravel will be looking in the resources/views/names/ directory for the file: “index.blade.php“. So make this file.

The View uses the Blade templating engine so ideally, the contents will be a mixture of HTML and simple logic. You can either use normal PHP, like <?php if($names){ ?>. Or, it may be better to use the blade templating system and write it using Blade like this @if ($names). With Blade you do not have to keep opening and closing the PHP making it a lot easier to write and cleaner to look at than normal PHP mixed into the HTML would be.

We want to display all our names on the page using Blade. In step 4, we gave the table 2 columns in the migration, “id” and “name”, and, in step 6, we got all the data from the “names” database. Now, they can be displayed very simply in a list like this within HTML using Blade…

@if ($names)
<ul>
@foreach ($names as $name)
<li>{{ $name->id }} - {{ $name->name }}</li>
@endforeach
</ul>
@endif

Now, when you go to the root domain of the Laravel website the Route sends you to the correct method of the Controller, which uses the Model and the View to grab the names and display them (assuming you have also inserted some rows to the database).

Conclusion

The 7 steps of this very simple beginners tutorial use the route, model, controller and view parts of Laravel.

  • The Route links the URL with a specific control and method, and can pass variables through to them.
  • The Model just links the table in the database to the controller in this simple example. In more complex examples the Model interacts with the database more and specifies relationships.
  • The Controller does what we want the page to do, in this case, it is to fetch the list of names from the Model (database) and it also says which view will display the data.
  • The View takes the data from the Controller and displays it on the page.

Errors and Solutions

An Artisan command produces an error like this…
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

Edit your “AppServiceProvider.php” file in the app/Providers directory and add to the boot method a default string length. You also have to make sure to “use” the Schema at the top.

use Illuminate\Support\Facades\Schema;
function boot()
{
Schema::defaultStringLength(191);
}

****************************
If migrate:refresh produces an error like…

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists...

Manually drop the tables in tinker by running tinker (see Useful Commands) and running the command…
Schema::drop('users')

Now, you can now run php artisan migrate to migrate all the tables.

****************************
Pages aren’t loading at all (fatal error), looking at the logs gives the error message…
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file...

Solution, make the Laravel log files writable…
sudo chmod -R 777 storage/logs

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.