laravel functioning


URL REQUEST CONTROLLER

The entry point for all requests to a Laravel application is the public/index.php file. All requests are directed to this file by your web server configuration. It's simply a starting point for loading the rest of the framework.

KERNEL

The incoming request is sent to either the HTTP kernel or the CONSLOLE kernel depending on the type of request.

The HTTP kernel configures error handling and logging and perform other tasks that need to be done before the HTTP request is actually handled.

The CONSOLE kernel handles all the artisan commands that comes from the terminal.

SERVICE PROVIDERS

One of the most important actions of Kernel is to load the service providers. All of the service providers for the application are configured in the config/app.php file's providers array. Service providers are responsible for loading all of the framework's components such as the database, queue, validation and routing. Since they load and configure every feature offered by the framework, service providers are the most important aspect of the Laravel.

DISPATCH REQUESTS

Once all the service providers have been registered, the Request will be handed off to the router. The router will dispatch the request to a route or controller as well as run defined middleware.

FROM METHOD SPOOFING

HTML forms do not support PUT, PATCH or DELETE methods. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method.

<form action="{{route('test')}}" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

method_field helper can be used to generate the _method input.

{{ method_field('PUT') }}

CSRF PROTECTION

Laravel makes it easy to protect your application from CSRF attacks by generating a CSRF token for each active user session. All HTML forms should include a CSRF token field to process the data. csrf_field helper can be used to generate the token field.

<form method="POST" action="{{route('test')}}">
    {{ csrf_field() }}
</form>

The VerifyCsrfToken middleware will automatically verify that token.

CONTROLLERS

Instead of defining all the request handling logic as Closures in route files, we can use controller classes to organize those logics. Controllers can group related request handling logic into a single class. The controllers extend the base controller class included in Laravel.

<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;

class myController extends Controller
{
    public function welcome()
    {
        return view('welcome');
    }
}
?>

A route can be pointed to this controller action as shown below.

Route::get('welcome', 'myController@welcome');

When a request matches the specified route URI, the welcome method on the myController class will be executed. we can create a controller using the make:controller Artisan command.

php artisan make:controller myController

ACCESSING HTTP REQUESTS

To get an instance of the current HTTP request, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function test(Request $request)
    {
        $name = $request->input('username');
    }
}
?>

RETRIEVING INPUTS

You may also retrieve all of the input data as an array using the all() method.

$input = $request->all();

RETRIEVING AN INPUT VALUE

$name = $request->input('username');

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is empty.

$name = $request->input('username', 'James');

When working with forms that contain array inputs, dot notation should be used to access the arrays.

$name = $request->input('products.0.username');

Input can be accessed using dynamic properties too.

$name = $request->username;

only and except methods can be used to retrieve a subset of the input data. Both of these methods accept a single array or a dynamic list of arguments.

$input = $request->only(['username', 'password']);
$input = $request->except('confirm_password');

CHECK INPUT VALUE

has method can be used to determine if a value is present on the request. The has method returns true if the value is present.

if ($request->has('username')) {

}

RETRIEVING COOKIES

To retrieve a cookie value from the request, use the cookie method on a Illuminate\Http\Request instance:

$value = $request->cookie('name');

ATTACHING COOKIES TO RESPONSES

Cookie calue can be returned by passing it's name, value and the duration of validation in minutes to this method.

return response('Welcome')->cookie(
    'name', 'value', $minutes
);

Generating Cookie Instances

Cookie instance can be generated with the use the global cookie helper.

$cookie = cookie('name', 'value', $minutes);
return response('Hello World')->cookie($cookie);

FILE UPLOADS

Uploaded files can be retrieved using the file method or dynamic properties. The file method returns an instance of the UploadedFile class and provides a variety of methods for interacting with the file.

$file = $request->file('columnName');

$file = $request->columnName;

hasFile method can be used to determine if a file is present or not.

if ($request->hasFile('columnName')) {

}

VALIDATING UPLOADS

Upload validation can be done via the isValid() method.

if ($request->file('columnName')->isValid()) {
    
}

FILE PATHS & EXTENSIONS

The uploaded fie's path and extension can be retrieved using these methods.

$path = $request->columnName->path();
$extension = $request->columnName->extension();

STORE UPLOADED FILES

The UploadedFile class has a store method which will move an uploaded file to the specified location. It accepts the path where the file should be stored relative to the root directory. The filename will be generated automatically. This method also accepts an optional second argument for the name of the disk that should be used to store the file. The method will return the path of the file relative to the disk's root.

$path = $request->columnName->store('filePath');
$path = $request->columnName->store('filePath', 'Uploads');

The storeAs() method can be used too which accepts the path, file name and location as its arguments.

$path = $request->columnName->storeAs('filePath', 'fileName.jpg');
$path = $request->columnName->storeAs('filePath', 'fileName.jpg', 'Uploads');

CREATING RESPONSES

All routes and controllers should return a response to the user's browser. There are several ways to to do so. The basic one is to return a string that will be converted into a full HTTP response by the framework.

Route::get('/', function () {
    return 'Welcome to Laravel';
});

REDIRECTS

Redirect responses contain the proper headers needed to redirect the user.

Route::get('dashboard', function () {
    return redirect('admin/dashboard');
});

While redirecting the user back to their previous location, you can use the global back() helper function.

Route::post('user/profile', function () {
    // Validate the request...

    return back()->withInput();
});

Named route can be attached to the redirect helper with no parameters.

return redirect()->route('login');

REDIRECTING TO CONTROLLER ACTIONS

The users can also be directed to controller actions.

return redirect()->action('HomeController@index');

REDIRECTING WITH FLASH SESSION MESSAGES

Redirecting with flashing session messages are easier with Laravel.

Route::post('user/profile', function () {    
    return redirect('dashboard')->with('message', 'Profile updated!');
});

After redirecting the user, flashed messages can be displayed from the session using Blade syntax.

@if (session('message'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

FILE DOWNLOADS

The download method can be used to generate a response fors the user's browser to download the file at the given path. This method accepts the path to the file as its first argument, a file name as the second argument that determines the file name that is seen by the user downloading the file and an array of HTTP headers as the third argument which are optional.

return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);

FILE RESPONSES

The file method can be used to display a file such as an image or PDF directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as the second.

return response()->file($pathToFile);
return response()->file($pathToFile, $headers);

HTTP SESSION

When using the database session driver, you will need to create a table to contain the session values.

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->integer('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

session:table Artisan command can be used to generate this migration file.

php artisan session:table
php artisan migrate

RETRIEVING SESSION DATA

The global session helper or the Request instance can be used to retrieve session data. Request instance method can be type-hinted on a controller method.

public function display(Request $request, $id)
{
    $value = $request->session()->get('key');
}

While retrieving a value from the session, you can pass a default value as the second argument to the get method that will be returned if the specified key does not exist. A closure can also be passed to the method instead that will be executed and its result returned if the key doesn't exist.

$value = $request->session()->get('key', 'default');
$value = $request->session()->get('key', function () {
    return 'default';
});

Global session PHP function can also be used to retrieve and store data in the session. When the session helper is called with a single string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session.

Route::get('home', function () {
    // Retrieve a piece of data from the session...
    $value = session('key');

    // Specifying a default value...
    $value = session('key', 'default');

    // Store a piece of data in the session...
    session(['key' => 'value']);
});

RETRIEVING ALL SESSION DATA

The all() method can be used to retrieve all data from session.

$data = $request->session()->all();

CHECK VALUE IN SESSION

The has() method can be used to determine if a value is present in the session. It returns a boolean if the value is present and not null.

if ($request->session()->has('users')) {
   
}

The exists() method can be used to determine if a value is present in the session, even if it's null.

if ($request->session()->exists('users')) {
    
}

STORING DATA IN SESSION

The put() method or the session helper canbe used to store data in session.

// Via a request instance...
$request->session()->put('key', 'value');

// Via the global helper...
session(['key' => 'value']);

PUSH NEW KEY AND VALUE TO SESSION

The push method can be used to push a new key-value pair onto a session value.

$request->session()->push('user.teams', 'developers');

RETRIEVING AND DELETING A KEY FRM SESSION

The pull() method will retrieve and delete a key and it's value from the session.

$value = $request->session()->pull('key', 'default');

FLASH DATA

Flash data can be stored in session only for the next reques by using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request and deleted.

$request->session()->flash('message', 'Task was successful!');

The reflash() method can be used to keep the flash data for several requests while keep() method can be attached to keep specific flash data only.

$request->session()->reflash();
$request->session()->keep(['username', 'email']);

DELETING DATA

The forget() method will remove a piece of data from the session while the flush() method can be used to remove all data from the session.

$request->session()->forget('key');
$request->session()->flush();

REGENERATION SESSION ID

Laravel automatically regenerates the session ID during authentication to prevent csrf attacks via the built-in LoginController. The regenerate() method can be used to manually regenerate it.

$request->session()->regenerate();

VALIDATION

Laravel uses a ValidatesRequests trait which validates incoming HTTP request with a variety of validation rules.

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
}

It's a good idea to stop running validation rules on attributes after the first validation failure. To do so, you can assign the bail rule to the attribute.

$this->validate($request, [
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

Dot syntax can be used to specify nested parameters in validation rules.

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

DISPLAYING VALIDATION ERRORS

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

VIEWS

Views contain the HTML code blocks served by the application and separate the controller logic from presentation logic. We can return those views using the global view helper.

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

Views can be nested within sub-directories where the dot notation can be used to such reference nested views.

return view('admin.profile', $data);

SHARING DATA WITH ALL VIEWS

Some data might be needed to share with all views that are rendered by the application which can be done using the share() method.

public function welcome()
{
    View::share('key', 'value');
}