Skip to content

Latest commit

 

History

History
789 lines (716 loc) · 20.8 KB

README.md

File metadata and controls

789 lines (716 loc) · 20.8 KB

Laravel

TOC

No Day Total Topics
1 day1 10
2 day2 7

Day1

No Topics
1 laravel-introduction
2 Laravel setup Laravel Herd
3 laravel-installation
4 Folder Structure
5 routing-basics
6 routing-parameters
7 Laravel Named Route
8 Laravel Blade
9 Laravel Blade II
10 Laravel Blade III

1.Laravel Introduction

    • Laravel is a free, open-source and one of the more popular PHP web Framework based on MVC architectural pattern.
    • created by Taylor Otwell in june 2011
    • Laravel Followes MVC Pattern

Uses of Laravel

    • Create Web Apps
    • Create APIs

What is MVC Pattern?

    • Model
      • Database Related Task
      • SQL Queries
    • View
      • User interface
      • HTML,CSS
    • Controller
      • Business Logic
      • Mediator between Model and View
    • MVC Principle
      • Separation of concerns.
      • Code Organization

MVC Pattern Work Flow

  • img

How to code in MVC Framework?

    • Controller (controllers/my_controller.php)
    function total_frogs(){
    Sthis->load->model("frogs");
    Snumber_of_frogs= Sthis->frogs->count_frogs();
    $data['froggies']=$number_of_frogs;
    $this->load->view("frog_view", $data);
    
    }
    • Model (models/frogs.php)
    function count_frogs(){
    Sthis->db->where("type","frog");
    Sthis->db->from("animals"); &
    Squery = Sthis->db->get();
    return $query->numb_rows();
    
    }
    • View (views/frog_view.php)
    <html>
        <body>
            <h1>You've <?=$name;?></h1>
        </body>
    </html>

Benefits of MVC Framework

    • Organized Code
    • Independent Block
    • Reduces the complexity of Web Applications
    • Easy to maintain
    • Easy to modify
    • Code reusability
    • Improved collaboration *
    • Platform independence
    PHP MVC Frameworks
      • Laravel
      • Symfony
      • Codelgniter
      • Yii
      • CakePHP
      • Zend Framework

What is Framework?

    • Programming frameworks are sets of pre-written code and libraries that provide a foundation for developing software applications.

    • Pre-written Code & Library

      • Tools
      • Components
      • Modules
    • Examples

      • Database Component
      • Caching
      • Pagination
      • Session management
      • Form Handling
      • Security mechanisms
      • User authentication
      • APIs
      • Payment Gateways
    • Benefits

      • Code organization
      • Reusability
      • Standardization
      • Testing & debugging support
      • Community and support

Benefits of Laravel Framework

    • Open source
    • Elegant syntax
    • MVC architecture
    • Database migration and ORM
    • Robust routing system
    • Command-line Interface (Composer)
    • Powerful template engine (Blade Template)
    • Authentication and authorization
    • Testing and debugging
    • Security (XSS, CSRF, SQL injection)
    • Scalability and performance (Redis and Memcached)
    • Robust ecosystem and community
    • Laravel Documentation

Main Topics of Laravel

    • Artisan CLI
    • Migration
    • Routing
    • Middleware
    • Views
    • Form Validation
    • Blade Template
    • Authentication
    • Controllers
    • Handling File Upload
    • Model
    • APIs Validation
    • Database
    • CRUD Project
    • Eloquent ORM
    • News Blog Project

3.Laravel installation

  • composer create-project laravel/laravel example-app
    
    • composer create-project laravel/laravel=10 myProject

Laravel Extensions

    • PHP IntelliSense (Damjan Cvetko)
    • PHP Namespace Resolver (Mehedi Hassan)
    • Laravel Extra Intellisense (amir)
    • laravel-blade (Christian Howe)
    • Laravel Blade Snippets (Winnie Lin)
    • Laravel goto view (codingyu)

4.Laravel Folder & File Structure

    1. Model Folder ————————> Database / SQL Queries Handling 1. Files
    2. Controller Folder —————> Business Logics Files
    3. View Folder ——————————> HTML Files
    4. Routing Folder ——————> URL Defining Files
    5. Assets Folder (Public folder) —————————> Images / Fonts / Music / Videos Files CSS / JavaScript Files

5.Laravel Routing Basics

  • Route::get('/', function () {
        return view('welcome');
    });

    php artisan route commands

    • php artisan
    • php artisan route -h
    • php artisan route:list
    • php artisan route:list --except-vendor
    • php artisan route:list --path=post

6.Laravel Routing Parameters & Constraints

7.Laravel Named Route & Routes Group

  1. Named Route
    Route::get('/hjfbvjhfd', function () {
        return view('post');
    })->name('mypost');
  2. Routes Group
    Route::prefix('page')->group(function () {
        Route::get('/about', function () {
            return view('welcome');
        })->name('myhome');
    
        Route::get('/gallery', function () {
            return view('welcome');
        })->name('gallery');
    
        Route::get('/post', function () {
            return view('post');
        })->name('post');
    });
  3. Page Note Found 404
    Route::fallback(function () {
        return "<h1>Page Note Found.</h1>";
    });

8.Laravel Blade Template - I

    flowchart LR
    A(Blade Template)
    A--->B(Template Engine Based on PHP)
Loading
  1. Benefits : Create Dynamic and Reusable Templates

  2. Blade provides a clean and convenient way to create views in Laravel

  3. Same code with php and blade template

        // php
        <?php echo "Hello"; ?>
        <?php echo $name; ?>
        <?php echo "<h1>Hello</h1>" ?>
    
        // blade template
        {{"Hello"}}
        {{$name}}
        {{!! "<h1>Hello</h1>" !!}}
  4. Blade Prevent: cross-site scripting (XSS) Attacks

        <?php 
            //php code 
        ?>
        @php 
            {--commet--}
        @endphp
  5. Basic syntex of blade

        <?php
        if(condition){
            //statement
        }else{
            //statement
        }
        ?>
        //blade
        @if(condition)
            //statement
        @else
            //statement
        @endif
  6. if in blade

        @switch($i)
            @case(1)
                //first case
                @break
            @default
                //default case
            @endswitch
  7. switch in blade

        @isset($record)
            //$record is default and is not null
        @endisset
  8. isset in blade

  9. Laravel Blade docs

        @for ($i = 0; $i < 10; $i++)
        The current value is {{ $i }}
        @endfor
    
        @foreach ($users as $user)
        <p>This is user {{ $user }</p>
        @endforeach
    
        @while (condition)
        <p>Loop Statement</p>
        @endwhile
    
        @forelse ($users as $user)
        <li>{{ $user->name }}</li>
        @empty
        <p>No users</p>
        @endforelse
    
        @continue
        @break
  10. Loops for, foreach, while, forelse

    Property Description
    $loop->index The index of the current loop iteration (starts at 0).
    $loop->iteration The current loop iteration (starts at 1).
    $loop->remaining The iterations remaining in the loop.
    $loop->count The total number of items in the array being iterated.
    $loop->first Whether this is the first iteration through the loop.
    $loop->last Whether this is the last iteration through the loop.
    $loop->even Whether this is an even iteration through the loop.
    $loop->odd Whether this is an odd iteration through the loop.
    $loop->depth The nesting level of the current loop.
    $loop->parent When in a nested loop, the parent's loop variable.
        @php
        $names = ['surej', 'rajan', 'himal', 'nabin'];
        @endphp
    
        <ul>
            @foreach ($names as $name)
                @if ($loop->even)
                    <li style="color: red">{{ $name }}</li>
                @elseif ($loop->odd)
                    <li style="color: green">{{ $name }}</li>
                    {{-- @else
                    <li>{{ $name }}</li> --}}
                @endif
            @endforeach
        </ul>
  11. Basic example

  12. Blade Loop Variable for @foreach

9.Laravel Blade Template - II

  • Including Subviews/Directives
    1. @include
    2. @section
    3. @extend
    4. @yield
  • Reusable Templates
        first.blade.php             second.blade.php
        <h1>First Page</h1>         <h1>Second Page</h1>
        {{ $status }} `Include View` @include(first)
        @include()
    
        @include('first', ['status' => 'Hello'])
  • passing props in laravel
        {{-- @include --}}
        {{-- prpos --}}
        @php
            $fruits = ['one' => 'Apple', 'two' => 'Mango', 'three' => 'banana', 'four' => 'orange'];
            $age = 20;
        @endphp
        {{-- @include('pages.header', ['names' => $fruits]) --}}
        {{-- @includeWhen($age > 18 ? true : false, 'pages.header', ['names' => $fruits]) --}}
        @includeUnless($age > 18 ? true : false, 'pages.header', ['names' => $fruits])
        <h1>Home page</h1>
    
        @include('pages.footer')
        @includeIf('pages.contact')

10.Laravel Blade Template - III

  • Template main directives
    1. @section
    2. @extend
    3. @yield
  • template inheritance
// master layout
@yield('title', 'web')

// other pages
@extends('layouts.masterlayout');

@section('content')
    <h2>Home page</h2>
    <p>Lorem ipsum dolor sit amet consectetur</p>
@endsection

@section('title')
    Home
@endsection

// master layout
@hasSection('content')
    @yield('content')
@else
    <h1>No Content Found</h1>
@endif

// other
@section('sidebar')
    @parent
    <p>This is appended to the sidebar</p>
@endsection

Day2

goto-toc⤴️

No Topics
11 js in balde
12 data-passing
13 controller
14 features-of-laravel-11
15 database-migration
16 migration-modifiers
17 migration-primary-foreign-key

11.Blade Template - IV JS in Blade

    • How to write js in blade template
        @php
            $user = 'Hello';
            $frouts = ['Apple', 'Mango', 'Banana', 'Litchi'];
        @endphp
    
        <script>
            // let data = @json($frouts);
    
            let data = {{ Js::from($frouts) }}
            data.map((val) => {
                console.log(val);
            })
        </script>
    • Js in Template Inheritance
        //define
        @stack('script')
    
        //use
        @extends('layout')
        @push('script')
            <script src="/example.js"></script>
        @endpush
    • style (CSS)
        @push('style')
            <link rel="stylesheet" href="css/bootstrap.css">
        @endpush
    
        @prepend (‘style’)
            <style>
                #wrapper{
                    background: tan;
    
                    }
            </style>
        @endprepend
    • javascript Framework (VueJs)
        @verbatim
            {{user}}
        @endverbatim
    • use Vue.js in laravel
        @verbatim
            <div id="app">{{ message }}</div>
        @endverbatim
        @push('scripts')
            <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
            <script>
                const {
                    createApp,
                    ref
                } = Vue
    
                createApp({
                    setup() {
                        const message = ref('Hello vue!')
                        return {
                            message
                        }
                    }
                }).mount('#app')
            </script>
        @endpush

12.Data Passing Route to View

    • Dynamic Data Passing
        function getUsers()
        {
            return  [
                1 => ['name' => 'Amitabh', 'phone' => '9123456789', 'city' => 'Goa'],
                2 => ['name' => 'Salman', 'phone' => '9123456789', 'city' => 'Delhi'],
                3 => ['name' => 'Sunny', 'phone' => "9123456789", 'city' => 'Mumbai'],
                4 => ['name' => 'Akshay', 'phone' => '9123456789', 'city' => 'Agra'],
            ];
        }
    
        Route::get('/users', function () {
        $names = getUsers();
            return view('users', [
                'users' => $names,
                'city' => 'Delhi'
            ]);
        });
    
        Route::get('/user/{id}', function ($id) {
    
            $users = getUsers();
            abort_if(!isset($users[$id]), 404);
            $user = $users[$id];
            return view('user', ['id' => $user]);
        })->name("view.user");

13.Controller in Laravel

    • To work on controller we should follow these three steps
      1. Create Controller File
        • To create Controller:
        • php artisan make:controller UserController
        • Then it will create: UserController.php
      class UserController extends Controller
      {
          public function show()
          { 
              return view('user.profile');
      
          } 
      
      }
      // then add it to route
      use App\Http\Controllers\UserController;
      Route::get('/user', [UserController::class, 'show']);
      1. Create Controller class
      2. Create Route
      PageController.php
      <?php
          namespace App\Http\Controllers;
      
          use Illuminate\Http\Request;
      
          class PageController extends Controller
          {
              public function showHome()
              {
                  return view("welcome");
              }
              public function showUser(string $id)
              {
                  // return view("user", ["id" => $id]);
                  return view("user", compact("id"));
              }
              public function showBlog()
              {
                  return view("blog");
              }
          }
          web.php
      
          Route::get("/", [PageController::class, 'showHome'])->name('home');
      
          // route group
          Route::controller(PageController::class)->group(function () {
              Route::get("/", 'showHome')->name('home');
              Route::get("/blog", 'showBlog')->name('blog');
              Route::get("/user/{id}", 'showUser')->name('user');
          });
      • Single Action Controller
          php artisan make:controller TestingController --invokable
          or
          php artisan make:controller TestingController --i
      
          class TestController extends Controller
          {
              public function __invok ()
      
              {
                  return view('test');
      
              } 
      
          }
      
          Route::get('/test', TestingController::class);
      • myProject>php artisan route:list --except-vendor
      • php artisan route:list --path=user

14.Features of Laravel 11

15.Database Migration

  • How to Work with Database
    1. Create Database
    2. Create Tables in Database(column Namw, Datatype)
    3. Insert Initial Data in Tables
    4. Code with Database

Steps

  1. Create Database
  2. Create Database Migration
    • (Create tables in database)
  3. Seeding
    • (Insert Initial Data in Tables)
    • php artisan make:migration create_students_table
  4. Create Model

Mysql DataTypes

  1. CHAR(size)
  2. VARCHAR (size)
  3. BINARY(size)
  4. VARBINARY(size)
  5. TINYTEXT
  6. TEXT(size)
  7. MEDIUMTEXT
  8. LONGTEXT
  9. TINYBLOB
  10. BLOB(size)
  11. MEDIUMBLOB
  12. LONGBLOB
  13. ENUM(val1, val2, val3, ...)
  14. SET(vall, val2, val3,..)
  15. BIT(size) 1to64
  16. TINYINT(size) -128 to 127
  17. INT(size) -2147483648 to 2147483647
  18. INTEGER(size)
  19. SMALLINT(size) -32768 to 32767
  20. MEDIUMINT(size) -8388608 to 8383607
  21. BIGINT(size) -9223372036854775808 to 1. 9223372036854775807
  22. BOOL
  23. BOOLEAN 0/1
  24. FLOAT(p)
  25. DOUBLE(size, d) 255.568
  26. DECIMAL(size, d) size = 60, d = 30
  27. DEC(size,d)

PHP Artisan Migration Commands

  1. php artisan make:migration
  2. php artisan make:migration create_students_table / tablename
  3. php artisan migrate
  4. php artisan migrate:status
  5. php artisan migrate:rollback
  6. php artisan migrate:reset
  7. php artisan migrate:refresh
  8. php artisan migrate:fresh
  9. php artisan make:model Task -m

16.Migration Modifiers and constraints

  • Types of Modifications
    • Column Modifications
      1. Add New Column
      2. Rename Column
      3. Delete Column
      4. Change Column Order
      5. Change Datatype or Size of Column
    • Table Modifications
      1. Rename Table
      2. Delete Table

Laravel:Modify Column with Migration

$table->renameColumn(‘from’, 'to'); 

MySQL <8.0.3
MariaDB < 10.5.2

$table->dropColumn('city');
$table->dropColumn(['city’, ‘avatar’, 'location']);
$table->string('name', 50)->change();
$table->integer('votes')->unsigned()->default(1)->comment('my comment')->change();

Change Column Order
$table after('password’, function (Blueprint $table) {
    $table->string('address');
    $table->string('city');
});

MYSQL Constraints with Migration

  • NOT NULL
  • UNIQUE
  • DEFAULT
  • PRIMARY KEY
  • FOREIGN KEY
  • CHECK
    Stable->string(‘email')->nullable();
    Stable->string(‘'email')->unique();
    Stable->unique('email’);
    Stable->string('city')->default('Agra');
    Stable->primary('user_id');
    Stable->foreign('user_id')->references('id')->on('users');
    DB::statement('ALTER TABLE users ADD CONSTRAINT age CHECK (age > 18);');
Modifier Description
->after('column’) Place the column "after" another column (MySQL).
->autoIncrement() Set INTEGER columns as auto-incrementing (primary key).
->comment('my comment’) Add a comment to a column (MySQL/PostgreSQL).
->first() Place the column "first" in the table (MySQL).
->from(Sinteger) Set the starting value of an auto-incrementing field (MySQL / PostgreSQL).
->invisible() Make the column "invisible" to SELECT * queries (MySQL).
->unsigned() Set INTEGER columns as UNSIGNED (MySQL).
->useCurrent() Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value.
->useCurrentOnUpdate() Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated (MySQL).

17.Migration Primary & Foreign Key

// create primary key
$table->primary('Cid');
// create foreign key
$table->foreign('city')->references('Cid')->on('City');
  • Foreign Key with Cascade
Stable->foreign('City_id')->references('Cid')->on('City’)
    ->onUpdate('cascade')
    ->onDelete('cascade’);

cascadeOnUpdate();
cascadeOnDelete();
restrictOnUpdate();
restrictOnDelete();
nullOnDelete();
  • 3way to make foreign key
$table->foreign('stu_id')->references('id')->on('students'); 
$table->foreignId('stu_id')->constrained (‘students’); 
$table->unsignedBiginteger('student_id'); 
$table->foreignId('student_id')->constratined();
  • Drop key Constraints
  • php artisan make:migration update_library_table --table=libraries
  • php artisan migrate:refresh
$table->dropPrimary('users_id_primary');
$table->dropUnique('users_email_unique');
$table->dropForeign('posts_user_id_foreign');
$table->dropForeign(['user_id']);