This is part 1 of the “Laravel Guide”.

You can check the next post here.

Create a website using laravel

This is my personal notes on the laravel PHP framework I gathered from around the web.

Feel free to take a look, but the post won’t be explained thoroughly.

I’m publishing this guide as a reference for later on.

Also, writing posts like these help me learn quicker.

Credits

These are the sources I got the info from:

Laravel Guide - Part 1. Install and Set up

This section will cover:

  • The Laravel installation
  • Routes
  • Controller
  • Views (We will create 3 pages)
  • Css Compilation
  • Build a Menu

Prerequisites

  • Install a Lamp Stack like Xampp, wamp, Mamp.
  • Install php composer
  • Install git, gitbash
  • A text editor such as atom or VSC

Install laravel

  • install laravel from the command line:
composer create-project laravel/laravel mysitename
  • Change the default ‘public’ folder using a virtual host.

Goto: xampp -> apache -> conf -> extra -> vhost.conf files.

Add a virtual host block with “DocumentRoot” & “ServerName”,

Also add the following 2 lines:

DocumentRoot "C:/xampp/htdocs"
ServerName localhost

DocumentRoot "C:/xampp/htdocs/mysitename/public"
ServerName mysitename.test
  • Open a text editor like notepad as administrator:

C:/Windows/sys32/drivers/etc/hosts and add:

127.0.0.1 localhost
127.0.0.1 mysitename.test

Restart the apache server in wamp, xammp etc.

Now the site should be visible in the browser at: mysitename.test

some users mentioned that the .dev extension didn't work for them. I used .test :)
some users mentioned that the .dev extension didn't work for them. I used .test :)

Folder Structure

  • All models go in the App folder
  • Controllers are in app/Http/Controllers
  • Views are in resources/Views (uses blade template)
  • routes are in routes (handles the request)

Routes, Controllers, Views

The main route file is the web.php file.

The route should be set to a controller that then returns a view.

Examples of routes displaying views:

Route::get('/about', function(){
  return view('pages.about');
});

OR

Route::get('/about', function(){
  return view('pages/about');
});

OR

Route::get('/users/{id}/{name}', function($id, $name){
  return 'This is user '.$name.' with an id of '.$id;
});

Routes

What routes should look like:

add each route in the web.php file in the routes folder.

Route::get('/', 'PagesController@index');
Route::get('/about', 'PagesController@about');
Route::get('/services', 'PagesController@services');
  • Get request for site index that looks for the PagesController file’s index method.
  • Get request for about that looks for the PagesController file’s about method.
  • Get request for services that looks for the PagesController file’s services method.

Controller

Run the artisan command to create the above controller:

  • use plurals
  • use PascalCase
php artisan make:Controller PagesController

This creates the PagesController file. Let’s create methods to load the views:

public function index(){
  return view('pages.index');
}

public function about(){
  return view('pages.about');
}

public function services(){
  return view('pages.services');
}
  • This returns the index.blade.php file from the resources/pages folder.
  • This returns the about.blade.php file from the resources/pages folder.
  • This returns the services.blade.php file from the resources/pages folder.

View

Create a index.blade.php file in resources/pages and copy code from the default welcome.blade.php file for now.

We can use shortcodes to get data from the .env file.

The index, about, services template will look like this:

<!doctype html>
<html lang"{{ config('app.locale') }}">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{config('app.name', 'mysitename')}}</title>
  </head>
  <body>
    <h1>Some title</h1>
    <p>Some text</p>
  </body>
</html>

Summary

So a visitor makes a request for ‘/’.

We send it to PagesController where the index method returns pages/index.

The visitor is served the pages/index.blade.php file.

The Blade template

Create layouts in the blade template

The above three view files have repeated html markup.

We should avoid this.

Let’s create a file in views/layouts/app.blade.php for the html markup.

Add the html mark up in app.blade.php and replace the body content like so:

<!doctype html>
<html lang"{{ config('app.locale') }}">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{config('app.name', 'mysitename')}}</title>
  </head>
  <body>
    @yield('content')
  </body>
</html>

Replace the pages/index.blade.php file with:

@extends('layouts.app')
@section('content')
  <h1>Index Title</h1>
  <p>Some index text</p>
@endsection

pages/about.blade.php:

@extends('layouts.app')
@section('content')
  <h1>About</h1>
  <p>Some about text</p>
@endsection

pages/services.blade.php:

@extends('layouts.app')
@section('content')
  <h1>Services</h1>
  <p>Some services text</p>
@endsection

The @extends('layouts.app') above refers to the layouts folder’s app file.

Pass variables in the blade template

Let’s add some variables in our controller.

PagesController file:

public function index(){
  $title = 'Welcome to Laravel';
  return view('pages.index')->with('title', $title);
}

public function about(){
  $title = 'About Us';
  return view('pages.about')->with('title', $title);
}

public function services(){
  $data = array(
    'title' => 'Services',
    'services' => ['Web Design', 'Programming', 'SEO']
  );
  return view('pages.services')->with($data);
}

We added some variables to pass into the views. We can also pass multiple variables.

The pages/index.blade.php file:

@extends('layouts.app')
@section('content')
    <div class="jumbotron">
        <div class="container">
            <h1>{{$title}}</h1>
            <p>This is the Laravel application to test Magento Object Oriented Programming.</p>
            <p><a class="btn btn-primary btn-lg" href="/login" role="button">Login</a> <a class="btn btn-success btn-lg" href="/register" role="button">Register</a></p>
        </div>
    </div>
@endsection

We added some bootstrap html markup above since Laravel already uses bootstrap.

The pages/about.blade.php file:

@extends('layouts.app')
@section('content')
  <h1>{{$title}}</h1>
  <p>Some index text</p>
@endsection

The pages/services.blade.php file:

@extends('layouts.app')
@section('content')
  <h1>{{$title}}</h1>
  @if(count($services) > 0 )
    <ul>
      @foreach($services as $service)
        <li>{{$service}}</li>
      @endforeach
    </ul>
  @endif
@endsection

Here we check if we have any $services, then we loop through each service.

Compiling CSS - using SASS (optional)

You might notice that we have the css folder in the public folder and a sass folder in the resources/assets/sass folder.

So what is SASS and why should we use it instead of css?

SASS files (or .scss) are like css but you can use cool stuff like variables, nests & mixins etc.

They can help organize code in a neat manner.

Take a look at the _variables.scss & app.scss files for example.

Compilation

Saved changes we make in a scss file aren’t applied to our website immediately.

We need to compile it so it gets converted into a regular css file.

For this we need to have nodejs installed.

Once you have installed nodejs on your pc, install the npm by running:

npm install

This should create a node_modules folder.

You can also look at the package.json file to see what dependencies are being used by laravel.

Create a new .scss file

We will create a new file called _custom.scss in the resources/assets/sass.

This is where we can add all our new css code.

We will include this file in the bottom of the app.scss file:

// Fonts
@import url("https://fonts.googleapis.com/css?family=Raleway:300,400,600");

// Variables
@import "variables";

// Bootstrap
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

// Custom Css
@import "custom";

We don’t need to add the underscore in the front nor the extension.

Include the css in our application

Now in the layouts/app.blade.php file, we will include the app.css file:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="{{asset('css/app.css')}}">
        <title>{{config('app.name', 'LSAPP')}}</title>
    </head>
    <body>
        @include('inc.navbar')
        <div class="container">
            @yield('content')   
        </div>
    </body>
</html>

Why did we add the app.css file from the public folder?

Because once we make the changes in the .scss files and compile it, it will be saved to this app.css file.

Now let’s make our first change in the .scss file.

Edit our .scss file

we can add some css changes in our _custom.scss:

h1,h2,h3,h4,h5,h6,p{
  color: pink;
  /* because pink is pretty */
}

To compile this, we go in our terminal and run:

npm run dev

Now the changes should be added to the app.css file and applied to the website.

We have to run this command each time though.

Instead we can run:

npm run watch

Now the process will run live in the background and automatically compile the files when we save them.

If you don’t want to use SASS now, you can just make changes directly to a css file.

Laravel make use of bootstrap’s css so let’s make our services look better in the services.blade.php:

@extends('layouts.app')

@section('content')
    <h1>{{$title}}</h1>
    @if(count($services) > 0)
        <ul class="list-group">    
            @foreach($services as $service)
                <li class="list-group-item">{{$service}}</li>
            @endforeach
        </ul>
    @endif
@endsection

We added some class to the ul and li tags.

Let’s create a Navigation Bar

Create a new folder & file: views/inc/navbar.blade.php

We’ll paste in some html samples from the bootstrap’s website in this new file (we’re using getbootstrap version 3 here):

<nav class="navbar navbar-inverse">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">{{config('app.name', 'LSAPP')}}</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li><a href="/services">Services</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>

We removed some elements and updated the links to match our website’s pages.

Including the navbar file

Include this file in the app.blade.php file:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="{{asset('css/app.css')}}">
        <title>{{config('app.name', 'LSAPP')}}</title>
    </head>
    <body>
        @include('inc.navbar')
        <div class="container">
            @yield('content')   
        </div>
    </body>
</html>

We can also add a div.container for the content.

We should now have a working Navigation bar for our new website.

Laravel with the bootstrap menu
Laravel with the bootstrap menu

I think we will end this section here.

In the next post we’ll cover the database, data & forms.