Laravel 5.8 From Scratch: Intro, Setup , MVC Basics, and Views.

Laravel 5.

8 From Scratch: Intro, Setup , MVC Basics, and Views.

Sagar MaheshwaryBlockedUnblockFollowFollowingApr 5In this series, We will make a basic (but rich in functionality) todo application with Laravel 5.

8.

The main purpose of this series is to get started with Laravel.

You will be learning all the basic and important parts of this framework.

Let’s get started.

What You Will Learn In This SeriesInstalling and setting up Laravel locally.

Models, Views, and Controllers (MVC).

Database, Migrations, and Eloquent ORM.

Authentication.

Email verification and Password reset.

IntroductionLaravel is the most popular PHP framework built by Taylor Otwell and community.

It uses MVC architecture pattern.

It provides a lot of features like a complete Authentication System, Database Migrations , A Powerful ORM, Pagination, and so on.

Before creating the application, you will need to have PHP 7.

2 and MySQL (we are not using apache in this series) and composer installed.

I use xampp which is a package that comes with PHP, MySQL, and Apache.

Composer is a dependency manager for PHP.

It’s similar to npm which is a dependency manager for Javascript.

Also, read the server requirements for laravel if you run into installation errors.

InstallationLaravel provides an installer which can be used for creating Laravel projects.

It can be install with composer:composer global require "laravel/installer"Now we can create our laravel project with:laravel new myappAbove command will create our project.

We can also use composer to create a laravel project (which I do):composer create-project laravel/laravel myappMVCA Model is used to interact with the database and of course it does not have to be a database.

It could be a JSON File or some other resource.

A Controller contains the logic e.

g how to validate form data and save a resource to the database by interacting through Model.

View is the User Interface (UI) of the application that contains HTML or the presentation markup.

It can also have logic e.

g loops and conditionals.

Template engines are used to embed logic in Views.

Laravel has Blade template engine that is used for adding logic inside the views.

you can read more about MVC at wikipedia.

Directory StructureLet’s look at the basic folder structure of laravel application e.

g where are Views, Models, and Controllers etc.

RoutesIn laravel, there are two routes file web.

php and api.

php.

web.

php file is used for registering all the web routes like mywebsite.

com/about or mywebsite.

com/contact.

api.

php is used for registering all the routes related to an api.

We are only using web routes so don’t worry about any api routes.

Controllers and ModelsModels are stored in app directory and there is a default user model that comes with laravel for authentication purposes.

appHttpControllers has all the controllers and there are some default controllers for authentication.

ViewsViews can be found in resources/views and welcome.

blade.

php is a default view provided by laravel.

Laravel views have a .

blade.

php extension so whenever you create a view don’t forget to add the blade extension.

resources/sass has all sass files and js has vuejs components and bootstrap files (we won’t talk about that).

Other DirectoriesYou can put your css, js, and all other static assets in public directory.

Config directory has all the configuration files related to our application like database, session, and other configurations (we will talk about config in the next tutorial).

There are other directories but you don’t need to worry about that.

Starting the Development ServerSince the root directory of the project is public, we will have to create a virtual host but instead of creating a virtual host, I want to make it simple by using Laravel development server with command (you should be inside the root of your project directory):php artisan serveThis will start the development server on port 8000.

By any chance, if you can’t use that port then you can use — port flag to specify a different port:php artisan serve –port=8080Routes and ControllersRouting is a mechanism by which requests (as specified by a URL and HTTP method) are routed to the code that handles them and that code in MVC is a controller method.

e.

g / will be your home and /about will be your about page.

If you open up the web.

php file, you will see just one route:<?phpRoute::get('/', function () { return view('welcome');});We have a ‘/’ route that uses a callback/closure making a GET request that returns a view named welcome.

In a route, the first parameter is the url and the second parameter can be a callback or controller action.

Let’s create a controller named PagesController and update our route.

In laravel, we have the ability to name our routes which comes in handy when you change the url later on.

We will define two routes for our index page and about page:<?php// syntax: 'ControllerName@MethodName'Route::get('/','PagesController@index')->name('pages.

index');Route::get('/about','PagesController@about')->name('pages.

about');GET method is used for retrieving data from the server.

In our case we will always use GET routes for displaying a plain view or a view with data.

With GET method we can pass data to the query string e.

g search term or date range for a report but you should not insert sensitive data like email or password since it’s visible in the URL.

For passing sensitive data to the server (when we submit a form), we use POST method because the data is sent in the request body.

There are other request methods but the most commonly used are GET and POST.

PUT method is used for updating data and DELETE for deleting data.

We need to create that PagesController and we can do that by typing this command:php artisan make:controller PagesControllerLaravel uses autoloading and all the classes are namespaced so if you want to create a controller inside a sub-directory then you should use artisan(It will create the directory if it does not exist):php artisan make:controller Admin/LoginControllerAbove command will create a LoginController inside a sub-directory called Admin.

Most of the stuff can be done through artisan which is a command line tool that comes with laravel.

You can create models, controllers, migrations and other files with artisan.

Let’s open the PagesController located in appHttpControllers:<?phpnamespace AppHttpControllers;use IlluminateHttpRequest;class PagesController extends Controller{ //}It has a class PagesController that’s extending Controller class which will provide us all the controller functionality.

It also has a Request class imported with “use” statement which is used to access form data and validation.

In this controller, we need two methods namely index and about, both will return views.

let’s add them:public function index(){ return view('pages.

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

about');}Index method is returning index view stored inside the pages folder and about method is returning a view named about.

In laravel, you don’t have to specify view extension and if you have a view inside a folder e.

g index view inside posts folder then use dots like view(‘posts.

index’).

Also If you want to see the list of all the registered routes in your application then type the below artisan command:php artisan route:listViewsFirst of all, we will create a layout file which will have all the markup that gets repeated by views e.

g doctype, head, and body tags.

Usually, layout files are stored in layouts folder in views directory, named app (you can name it whatever you want).

let’s create an app.

blade.

php file after creating layouts folder and add this markup:<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.

0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{{asset('css/app.

css')}}"> {{– <- bootstrap css –}} <title>@yield('title','Laravel 5.

8 Basics')</title></head><body> {{– That's how you write a comment in blade –}} @include('inc.

navbar') <main class="container mt-4"> @yield('content') </main> @include('inc.

footer') <script src="{{asset('js/app.

js')}}"></script> {{– <- bootstrap and jquery –}} </body></html>Blade directives start with “@” symbol.

@include() is used for including a separate view file.

As you can see inc is the name of the folder and navbar is the name of the view.

@yield() will output the content of the view section that’s extending this layout.

Double curly braces “{{}}” are used for echoing a variable or calling a helper function.

Asset() helper is used for generating URLs to public assets stored in public directory like CSS, Images, and Javascript.

Note that laravel comes with bootstrap 4 and that’s what we are including.

Let’s create navbar.

blade.

php in inc folder and add the markup:<nav class="navbar navbar-expand-md navbar-light navbar-laravel"> <div class="container"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.

name', 'Laravel') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!– Left Side Of Navbar –> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a href="{{route('pages.

index')}}" class="nav-link">Home</a> </li> <li class="nav-item"> <a href="{{route('pages.

about')}}" class="nav-link">About</a> </li> </ul> <!– Right Side Of Navbar –> <ul class="navbar-nav ml-auto"> </ul> </div> </div></nav>Inside the navbar we are using url() helper which is used for generating application urls.

route() function is used to generate urls of named routes.

config() is used for retrieving values from files inside the config folder, app.

name will return “name” value from the app.

php config file, second parameter is a fallback value or else it will return null.

You can use dot syntax for accessing values inside of an array e.

g config(‘file.

array.

string’,’fallback value’).

Now whenever you create a view just add the below lines of code.

All the content of your page will be inside the @section directive.

@extends('layouts.

app')@section('content') My Page Content@endsectionIndex.

blade.

php view inside the pages folder will have the following markup:@extends('layouts.

app')@section('content') <h2 class="mt-5 mb-3 text-center">Laravel 5.

8 For Beginners!</h2> <p class="text-center">Lorem ipsum dolor sit amet consectetur adipisicing elit Aut.

</p>@endsectionAnd for the about.

blade.

php view:@extends('layouts.

app')@section('title')Laravel 5.

8 Basics | About Page@endsection@section('content') <h3>About Page</h3> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.

</p>@endsectionAs you have noticed, we have a @yield directive inside the title html tag and we are defining the section inside our about view so when you will access the about page from the browser you will see that the title on the browser tab is changed.

In the next tutorial, we will talk about accessing and updating config values from .

env file then we will create, read, update, and delete todos with MySQL database.

Link to the next tutorial HERESource code till this tutorial HERE | complete project HERE.. More details

Leave a Reply