Laravel | PHP | Basics | Part 1

Laravel | PHP | Basics
In this post, we will see the basics of laravel
Laravel is a frame work on top of PHP (PHP Hypertext Preprocessor) for web artisans.

When you download and install composer which is the dependency manager for PHP, you need to run the command

composer install

Getting started

How to create a project in laravel:

  • composer create-project laravel/laravel example-app
OR
  • composer global require laravel/installer
  • laravel new example-app

The config folder

The entry point is in the config folder.
In the config/database.php file, the "connection" key contains all the database drivers configuration available or provided by the laravel framework.

The supported datavase drivers are
  1. sqlite
  2. mysql
  3. pgsql
  4. sqlsrv
  5. redis

"mysql" => [
	"driver" => "mysql",
	"host" => env("DB_HOST","127.0.0.1"),
	"port" -=> env("DB_PORT", "3306"),
	"database" => env("DB_DATABASE", "my_db")
];
To define all the controller actions on APIs, we use the web.php file in the routes directory
For this, we use the Route Facade
Laravel supports both GET and POST methods
Example of a GET request:
Route::get("/login.php", function(){
	return view("/welcome", $params_assoc_array);
}
);
To pass variables in paths like /{user}/1001 and /{user}/1002
Here, user is a variable which stores the user name and is different for different user.
To pass the variables, just enclose the variable names where it is assigned a value in the URL(Uniform Resource Locator).
You can have as many named variable parameters as you want in a URL.
for e.g.,
https://thewedesk.blogspot.com/{name}/{post}/{comment}
Route::post("/user/{post}/{comment}");
Using annotations:
To trigger a function which is called when a URL is hit, use the @ operatoier before the method name for eg,

Route::get("/home","HomeController@index")->name('home');
To limit the values of the variable parameters, we discussed earlier in this post, simply use the where clause like
->where(["operation"=> (insert|update|delete)"]);
All the HTML,CSS and JavaScript files are stored in the resources/assets directory in the root folder
In the assets directory, there are three sub directories:
  1. images
  2. js
  3. sass

In the views directory which is located in this resources directory all the blade template files are stored

eg, if you create a file that is stored in the resources/views directory, use the blade.php file extension to the file name.
This file name is used as a reference in other files

  1. @extends will include the file which is passed to it as an argument
  2. @("layouts.app") includes the contents of the blade file in the resources/layouts directory and then the app.blade.php
  3. This is uuseful for code reusability if the same code is erquiredfor all web pages of a website like a menu bar, a side bar or a site map
  4. To insert PHP code in a blade file, just enclkose the code in {{ }} (double curly braces both open and close)
  5. If youy want to print data without escaping the spedcial characters ior html entities we use {!! !!}

In the laravel root directory, a composer.json and composer.lock files will be created
In the above two files, composer stores all the packages and their dependencies in JSON(JsavaScript Object Notation) format with the currently installed major version number and minor version number

for eg

"packages" : [
{"name":"laravel/laravel",
 "version":"2.9.8"
},
{"name1" :"junit/php",
 "version1":"6.7.4"
}
]
Now, we come to the "app" directory inside the directory in which the project was created.
The sub directories if the "app" directory are:
  1. Console
  2. Exceptions
  3. Http
  4. Models
  5. Providers
  6. Scope
  7. Traits

Exception Handling

The custom exception handler must extend the ExceptionHAndler class and override the method

  1. report(Exception $ex)
  2. render(Exception $ex);

HTTP Controllers

Now we come to the Http Folder where all the business logic, database, connections are written as configured in the config folder we discussed earlier:-

Http folder contains two sub directories
  1. Controller
  2. Middleware
Every controller class must extend the Illuminate\Routing\Controller class which is pre defined in Laravel service container.
Every controller must use the 3 traits
  1. Illuminate\Foundation\Bus\DispatcjesJObs
  2. Illuminate\Foundation\Validation\ValidatesREquests
  3. Illuminate\Foundation\Auth\Access\AuthorizesRequests
for example


namespace App\Http\Controllers;
class Controller extenmds BAseController {
	use AuthorizesRequests, DispatchesJobs, ValidatesRequests
}

To generate a reason for going to the home poage after syccessful login, create a constructor __construct() which will be a middleware auth

The second method is index() which will return a blade template as the output


public function __construct() {
	$this->middleware('auth');
}
public function index() {
	return view("home");l
}

In the Model directory inside the admin.php directory, use single PHP file for the table, for eg,

namespace App\Models;
use Illuminate\Foundation\Auth\Usert as Authenticatable;
use Illuminate\Notificatiuobns\Notifiable
class Admin extends Authenticable {
	use Notifiable;
    protected $table = "admin";
    protected $fillable = ["namwe","email","password"];
    protected hidden = ["password"];
}
The providers sub directory insuide the app directory declares, initializers and defines the service providers to be injected in the Laravel service container
The primary and the most important service provideris the AppServiceProvider class
Every user-defined service provider shpoulkd extend the Illuminate\Support\ServiceProvider class
This class has 2 methods:
  1. public function boot() {}
  2. public function register() {}
The EventServiceProvider takes care if the event handling:

protected $listen = [        
  "App\Events\Event"=>[
  	"App\Listeners\EveentListener"];
  ];
The RouteServiceProvider performs the mapping of API and web routes

  public function map() {
  	$this->mapApiRoutes();
  	$this->mapWebRoutes();
  }
  

Screenshots

The default directory structure created when a laravel project is created is shown in the figure below
  1. The app directory contains all the business logic and MVC(Model View Controller) implemention
  2. The config directory contains all the configuration settings for various objects in the Laravel service container
  3. The database directory contains all the migrations, seerders and factories
  4. The resources folder contains all the blade templates, HTML files, CSS fles and JavaScript files
  5. The public folder contains PHP files that are available to the entires application
  6. The routes folder contains all the web.php and api.php files for mapping HTTP requests (both GET and POST) to c0ontrollers
  7. The storage directory contains all the log files and otherarchival storage
  8. The tests folder contains the unit testing code

Helper functions

Helper functions are used to process HTTP requests and repsonses and other miscellaneous tasks

The request() helper function contains an associative array of Request header names are keys and their values as the associative array values

The response() helper function stores an associative array of reponse properties and their values

The view() function takes two parameters. The first is the fully qualified path name of the file wiyhout the extension of .blade.php and an associative array which will be passed from the model to the controller and from throm the controller method to the blade file

The redirect() function contains the URL to which the redirect was working

The session() function stores all teh state information as a key value associative array

Redis Cache

  • To get a value from the redis cache, use Cache::get("key");
  • To insert a value from the redis cache, use Cache::put("key");
  • To increment a value by 1 for a value stored in the cache, use Cache::increment("key");
  • To decrement a value by 1 for a value stored in the cache, use Cache::decrement("key");
  • To store a value which be stored in the cache foreveer, use the
    Cache::rememberForever("key",function() {
                   });
    			   
To go to Redis cache, type the command redis-cli on the prompt
Now, you have opened the redis cache. It runs on port number 6379.
There, you can type the commands which are understood by redis

php artisan tinker

Suppose you wish to test small parts of code this will give you a prompt to write the small code and check out where the bug is and what is the exception which has occured

Following is the list of artisan commands

  1. php artisan make:model -> makes a Model class
  2. php artisan make:controller -> Makes a Controller class
  3. php artisan make:migration -> Runs all the migrations
  4. php artisan serve -> Starts the server
  5. php artisan migration:refresh -> Reverses all the previous migrations
  6. php artisan migrtaion:rollback -> Reverses the latest migration
  7. php artisan scheduler -> Schedules a program to run at specific intervals of time
To update the packages and their dependencies run
composer update

Comments

Popular posts from this blog

XPath for HTML markup

Apache Hadoop | Running MapReduce Jobs

Laravel | PHP | Basics | Part 2