Introduction
This guide is dedicated to people interested in learning and working with the popular PHP framework Laravel.
It's assumed you understand these basic concepts before starting this guide...
- Object-oriented programming
- Basic PHP code
- HTML
- CSS
If you aren't familiar with any of the above then it's best to read up on them.
This guide is aimed at beginners to the Laravel PHP framework and will briefly cover the following concepts...
- Controller
- Routing
- Environment variables
- HTTP Client
- Blade templates
MySQL won't be covered to keep this guide simple so it's quick and easy to create this Laravel website. MySQL will be covered in future Laravel guides as there are a few features that Laravel provides that require going into depth.
In terms of data, an API is used to retrieve it to show in this project.
Creating the Laravel project
To begin you need to create the Laravel application.
There are multiple ways how this can be done.
Laragon
Laragon provides a way to create and set up a Laravel application by selecting the Laravel option in the Quick Tools menu.
For the name enter devsites and submit.
Wait for the setup process to finish and you should be able to access the Laravel site by going to http://devsites.test.
Terminal
The alternative method to set up Laravel would be to use a terminal. For Windows, it would be Git Bash and for Mac OS / Linux the default terminal would suffice.
The PHP package manager Composer is also required to set up Laravel.
Open the terminal, and go to the directory to add the Laravel codebase. For example, you could use the directory ~/dev with the dev folder used to contain all your projects. After you have changed to directory then use the following command below.
composer create-project laravel/laravel devsites
Coding with Laravel
Now that Laravel has been added switch to the directory.
cd devsites
Now use the serve command to start up the Laravel app.
php artisan serve
Go http://localhost:8000 and the Laravel website should load up, you should see the following screen.
Environment variable
The first thing to do is add a configuration variable. Open the Sublime Text editor (or whichever code editor you prefer) and open the .env file.
The .env file is to store sensitive data which is separate from the rest of the codebase. When the code is transferred to GitHub the .env won't be sent to GitHub as the data should remain a secret.
Add the following new configuration entry to the end of the .env file.
PUSHDEV_API_URL="https://api.devpushprojects.com"
This environment variable holds the URL for the API that will be used to retrieve the data to show on the website.
Now go to the config folder and open the configs/app.php file. Go to the end of the file and add the following.
'devpush_api_url' => env('PUSHDEV_API_URL', 'https://api.devpushprojects.com')
How the env method works is it will read the DEVPUSH_API_URL value from the .env file and if there is no value set then it will use the second value passed into the env method which is https://api.devpushprojects.com.
To get this URL inside the code the config method should be used. The parameter references the app.php inside the config folder and devpush_api_url matching the same key setup inside the file.
$apiUrl = config('app.devpush_api_url');
Controller class
Create a new file inside of app/Http/Controllers, call it SiteController.php.
Add the following code to the SiteController file.
<?php
namespace App\Http\Controllers;
use Illuminate\View\View;
use Illuminate\Support\Facades\Http;
class SiteController extends Controller
{
public function showAllSites(): View
{
// Get DevPush API Url from config/app.php file
$apiUrl = config('app.devpush_api_url');
// Send a request to DevPush API to get dev site categories
$response = Http::get($apiUrl . '/devsites/categories');
// Convert the site category JSON data to a PHP array
$categories = $response->json()['data'];
// Send a request to DevPush API to get dev sites
$response = Http::get($apiUrl . '/api/devsites/sites');
// Convert the site JSON data to a PHP array
$sites = $response->json()['data'];
// Gets and processes index.blade.php in resources/views folder
return view(
'index',
[
'categories' => $categories,
'sites' => $sites
]
);
}
public function showCategorySites(int $categoryId): View
{
// Get DevPush API Url from config/app.php file
$apiUrl = config('app.devpush_api_url');
// Send a request to DevPush API to get dev site categories
$response = Http::get($apiUrl . '/devsites/categories');
// Convert the site category JSON data to a PHP array
$categories = $response->json()['data'];
// Send a request to DevPush API to get dev sites
$response = Http::get($apiUrl . '/devsites/categorized/' . $categoryId);
// Convert the site category JSON data to a PHP array
$sites = $response->json()['data'];
// Gets and processes index.blade.php in resources/views folder
return view(
'index',
[
'categories' => $categories,
'sites' => $sites
]
);
}
}
Each line of code has a comment explaining what each line is doing, it's best to go through each line although here is a summary of the above code.
In the showAllSites method, the DevPush API URL is retrieved from the config file and used to send requests to the DevPush API. Two API requests will be made to get the developer websites and categories which are returned in the response. The data from both API requests are converted from JSON to PHP arrays. Finally, the developer websites and categories are passed into the Laravel blade template files where the data is output as HTML.
Routes
The routes for these methods aren't set so we need to add them for the SiteController methods.
Go to the routes/web.php file and replace the content with the following.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SiteController;
Route::get('/', [SiteController::class, 'showAllSites']);
Route::get('/category/{id}', [SiteController::class, 'showCategorySites']);
When the application starts the URL http://localhost:8000/ will call SiteController showAllSites method. The second link is slightly different as the {id} part will represent a number that can be passed in so the following links will connect to the SiteController showCategorySites.
Blade view templates
This file requires the blade template files for this to work so that will be the next thing to add.
The first file to add is the layout file which represents the main HTML structure used for every page accessed in the website.
Go to the resources/views folder and then create a layouts folder. Now within the layouts folder create an app.blade.php file and add the following layout code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>App Name - @yield('title')</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{{ asset('css/style.css') }}" rel="stylesheet">
</head>
<body>
<header>
<h1>DevSites</h1>
<div>Technologies and services related to PHP development</div>
</header>
<main>
@yield('content')
@section('sidebar')
<div class="categories">
<h2>Categories</h2>
<a class="category" href={{ url('/') }}>All</a>
@foreach ($categories as $category)
<a class="category" href={{ url('/category/' . $category['id']) }}>
{{ $category['name'] }}
</a>
@endforeach
</div>
@show
</main>
</body>
</html>
The @yield('content') line is where the content for each page is set, the same as the @yield('title') which sets the page title.
The @section('sidebar') allows the HTML code to be modified on each page.
Next, go to the resources/views folder and create an index.blade.php file with the following content.
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@section('content')
<div class="sites">
@foreach ($sites as $site)
<a class="site" href="{{ $site['url'] }}" target=”_blank” class="">
<img class="" src={{ $site['image_url'] }} alt="" />
<div class="site-name">{{ $site['name'] }}</div>
</a>
@endforeach
</div>
@endsection
The index file will loop through the websites returned from the API and display the website URL, image URL, and name for each looped developer website.
CSS
Go to the public folder and create a css folder, next create a file named style.css.
Inside of the style.css file add the following content.
html, body {
font-family: ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";
}
body {
width: 1200px;
margin: 0 auto;
}
a {
color: #000;
text-decoration: none;
}
header {
padding: 5px 0 40px;
}
main {
display: flex;
}
h1 {
font-weight: 800;
}
img {
width: 238px;
height: 149px;
}
.sites {
display: flex;
flex-wrap: wrap;
gap: 40px;
width: 1000px;
}
.site {
width: 238px;
padding: 24px;
border-radius: 5px;
border: 1px solid #D1D5DB;
background-color: #F8FAFC;
box-shadow: 2px 2px 8px 1px #DDD;
}
.site-name {
margin-top: 10px;
font-weight: bold;
}
.categories {
display: flex;
flex-direction: column;
width: 200px;
}
.category {
display: inline-block;
margin-bottom: 20px;
}
.category:hover {
text-decoration: underline;
}
The above CSS will be used to format the website so it' appears presentable.
Now it's time to check the website out.
Go to http://localhost:8000 and the Laravel app should load the developer websites and categories as shown below.
The main URL will call the showAllSites method of the SiteController file.
Try clicking the links on the right categories menu. You will notice the URL change as you click the links that use the showCategorySites method of the SiteController controller.
The number in the URL signifies the category ID used to filter the developer websites by their category.
You now have a simple Laravel website that displays developer-related website and category data.
If you want the finalized version of this example you can find it on the GitHub DevSites page.
To download the code click on the green Code button and click on the Download zip link.
Alternatively, you can use the terminal to git clone the project.
git clone https://github.com/devpushprojects/devsites-laravel.git
Conclusion
After following this guide you will have set up a Laravel application and created a simple website that shows a list of developer-related websites with a categories menu to filter those dev sites.
You will have added an environment variable to represent the API URL. Added a controller class with two class methods: one method gets all the developer websites and the other class method gets developer websites by the passed-in category ID. Both methods get all categories so the menu can display them all.
Two routes will have been added in the routes web file to connect the app URLs to the controller methods. View and layout pages are added to show the templates that make up the Laravel project when loading it within the web browser. Finally, the style CSS file was added to make the templates presentable.
Hopefully, this guide will lead you to more programming PHP with the Laravel framework by exploring more features that the Laravel framework provides.