Laravel

# Laravel Framework

Laravel is an open-source PHP web framework used for building web applications, based on the Model-View-Controller (MVC) architectural pattern. Laravel offers a wide range of features, including routing, middleware, authentication, sessions, caching, database management (with Eloquent ORM), and templating with Blade.

A web framework provides a structure, foundation and starting point for creating application, allowing to focus on creating application. It includes a collection of pre-written code, libraries, APIs, and tools that developers can use to build applications more efficiently.

# Folder Structure

  • app : This directory contains the core code of the application. It includes subdirectories, like

    • Console : Contains custom Artisan commands generated using the make:command command.
    • Exceptions : Contains custom exception handlers generated using the make:exception command..
    • Http : Contains controllers, middleware, and form requests.
    • Models : Contains the Eloquent ORM models.
    • Providers : Contains service providers for application bootstrapping.
  • bootstrap : Contains the application's bootstrap files, including app.php, which bootstraps the Laravel framework.

  • config : Configuration files for various parts of the application, such as database, cache, and session configuration.

  • database : Contains database migrations, seeds, and model factories.

    • migrations : Database migration files.
    • seeds : Database seeders.
    • factories : Model factories for generating test data.
  • public : This is the web server's document root. It contains the entry point (index.php), which is the entry point for all requests entering the application and configures autoloading and publicly accessible assets like CSS, JavaScript, and image files.

  • resources : Contains resources that the application uses, such as views, language files, and assets.

    • css, js, sass : Contains CSS and JavaScript assets.
    • lang : Language files for localization.
    • views : Blade templates for generating HTML.
  • routes : Contains route definitions for the application.

    • web.php : Routes for the web interface.
    • api.php : Routes for API endpoints.
    • console.php : Routes for Artisan commands.
  • storage : Contains application storage, such as logs, temporary files, and uploaded files.

    • app : Application-specific files generated by the application.
    • framework : Cache, sessions, and views used by the framework.
    • logs : Application log files.
  • tests : The tests directory contains your automated tests, such as PHPUnit test cases for the application.

  • vendor : Contains Composer dependencies.

  • .env : Environment configuration file.

  • artisan : Command line utility for interacting with your Laravel application.

# Routes

A route is a way of mapping HTTP request URIs to a specific controller action or a closure.

Route::get('/view/{id}', function(string $id){
    return "User" . $id;
});
http://127.0.0.1/view/17
  • /view : It is a route
  • /17 : It is a routing parameter.
Route Methods :
Method Description
get() Read data
post() Add/Create, Update, Delete
put() Update
patch() Update
delete() Delete
options() Request information about methods supported by server for resource
match() Used to define route that responds to multiple requests
any() Used to define route that responds to all requests

# Blades

Blade is the simple yet powerful templating engine that is included with Laravel. All Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to the application. Blade template files use the .blade.php file extension and are typically stored in the resources/views directory.

Blade Directives :

In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops called blade directives.

  • Displaying Data :
    {{ "Time : " . $time }}
    
        {{!! "<h1>I'm Dev</h1>" !!}}
  • Comment :
    {{-- This is comment --}}
  • Raw PHP :
    @php strtoupper("abcd") @endphp
  • Control Structure :
    @if ($age = 18)
            $permission = "Complete"
        @elseif ($age < 18)
            $permission = "Partial"
        @else
            "Incorrect Age"
        @endif
  • Switch Stamement :
    @switch($val)
            @case(1)
                // Case 1
                @break
            @case(2)
                // Case 2
                @break
            @default
                // Default Case
        @endswitch
  • Loops :
    {{-- For Loop --}}
        @for ($i = 0; $i < 10; $i++)
            Current value is {{ $i }}
        @endfor
    
        {{-- For Each --}}
        @foreach ($users as $user)
            This is user {{ $user->id }}
        @endforeach
    
        {{-- While Loop --}}
        @while (true)
            <p>I'm looping forever.</p>
        @endwhile
    
        {{-- For Else --}}
        @forelse ($users as $user)
            <li>{{ $user->name }}</li>
        @empty
            <p>No users</p>
        @endforelse
  • Loop Control :
    @foreach ($users as $user)
            @if ($user->type == 1)
                @continue
            @endif
    
            <li>{{ $user->name }}</li>
    
            @if ($user->number == 5)
                @break
            @endif
        @endforeach
  • Loop Variables :
    Property Description
    $loop->index Index of current iteration (starts at 0).
    $loop->iteration Current iteration (starts at 1).
    $loop->remaining Iterations remaining in the loop
    $loop->count Total number of items in array
    $loop->first Whether this is first iteration
    $loop->last Whether this is last iteration
    $loop->even Whether this is even iteration
    $loop->odd Whether this is odd iteration
    $loop->depth Nesting level of current loop
    $loop->parent When in nested loop, parent's loop variable
  • Empty :
    @empty($string)
            // Variable, array or collection is Empty
        @endempty
  • Isset :
    @isset($records)
            // Variable or array key is Set and is Not Null
        @endisset
Passing Data Route to View :
Route - web.php
Route::get('/users', function(){
    $name = "User Name";

    return view('userpage', ['user' => $name]);
});
Blade - userpage.blade.php
{{ "Welcome " . $user }}

# Composer

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on, and it will manage (install or update) them for you. Composer is not a package manager; it is a dependency manager.

Composer Commands :
  • Create Laravel Project :
    composer create-project laravel/laravel [Project-Name]
  • Install Dependency :
    composer install
  • Update Dependency :
    composer update

# Artisan

Artisan is the command-line interface included with Laravel. Artisan exists at the root of your application as the artisan script and provides a number of helpful commands that can assist in building the application.

Artisan Commands :
  • Run Project :
    php artisan serve
  • Create Controller :
    php artisan make:controller [Controller-Name]
  • Create Resource Controller :
    php artisan make:controller [Resource-Controller] --resource
  • Create Component :
    php artisan make:component [input]
  • Create ORM Model :
    php artisan make:model [Model]
  • Create Migration Table :
    php artisan make:migration [create-user-table]
  • Run Migrations :
    php artisan migrate
  • Rollback Migrations :
    php artisan migrate:rollback
  • Reset Migrations :
    php artisan migrate:reset
  • Refresh Migrations :
    php artisan migrate:refresh
  • Create Import/Export Model :
    php artisan make:import [ModelImport] --model=[Model]
    
        php artisan make:export [ModelExport] --model=[Model]

# Database

Laravel provides two main approaches for interacting with databases: the query builder and the ORM (Object-Relational Mapping) called Eloquent. The configuration for Laravel's database services is located in the application's config/database.php configuration file.

• Query Builder :

Laravel Query Builder is a fluent interface for building and running database queries in Laravel without having to write raw SQL statements.

$users = DB::table('users')->select('name', 'email')->get();

$users = DB::table('users')->where('age', '>', 18)->get();

DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);
• Eloquent ORM :

Laravel's Eloquent ORM is an ActiveRecord implementation for working with databases in PHP. It allows you to interact with your database tables using PHP objects. Each database table has a corresponding "model" that is used to interact with that table.

User's Model -
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    protected $table = "users";
    protected $primaryKey = "id";

    protected $fillable = [
        'name',
        'email',
        'status',
    ];
}
User's Controller -
$users = User::where('id', $id)->get()->toArray();

$result = User::create([
    'name' => $name,
    'email' => $email,
    'status' => 1,
]);

$user = User::find($id);
$user->delete();