Post Top Ad

Friday, June 21, 2019

Laravel 5.8 CRUD Tutorials



Related image



Laravel 5.8 21-June-2019




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

@Khem Puthea June 2019

What You Will Learn In This Series

  • Installing and setting up Laravel locally.
  • Models, Views, and Controllers (MVC).
  • Database, Migrations, and Eloquent ORM.
  • Authentication.
  • Email verification and Password reset.

Installation

We can use composer to create a laravel project :

  composer create-project laravel/laravel myapp

MVC

A 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 Structure

Let’s look at the basic folder structure of laravel application e.g where are Views, Models, and Controllers etc.

Routes

In laravel, there are two routes file web.php and api.php. web.php file is used for registering all the web routes like localhost.com/about or localhost.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 Models

Models are stored in app directory and there is a default user model that comes with laravel for authentication purposes. app\Http\Controllers has all the controllers and there are some default controllers for authentication.

Views

Views 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.

Other Directories

You 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.

Starting the Development Server

Since 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

  php artisan serve

This 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=8080

Routes and Controllers

Routing is a mechanism by which requests 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:

    <?php

    Route::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. The 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 PagesController

Laravel 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/LoginController

Above 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 app\Http\Controllers:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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:list

Views

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
  @endsection

index.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>
  @endsection

And 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>
@endsection

As 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.

No comments:

Post a Comment