Laravel | PHP | Basics | Part 1
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
- 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.
- sqlite
- mysql
- pgsql
- sqlsrv
- redis
"mysql" => [
"driver" => "mysql",
"host" => env("DB_HOST","127.0.0.1"),
"port" -=> env("DB_PORT", "3306"),
"database" => env("DB_DATABASE", "my_db")
];
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);
}
);
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}");
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');
->where(["operation"=> (insert|update|delete)"]);
In the assets directory, there are three sub directories:
- images
- js
- 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
- @extends will include the file which is passed to it as an argument
- @("layouts.app") includes the contents of the blade file in the resources/layouts directory and then the app.blade.php
- 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
- To insert PHP code in a blade file, just enclkose the code in {{ }} (double curly braces both open and close)
- 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
"packages" : [
{"name":"laravel/laravel",
"version":"2.9.8"
},
{"name1" :"junit/php",
"version1":"6.7.4"
}
]
- Console
- Exceptions
- Http
- Models
- Providers
- Scope
- Traits
Exception Handling
The custom exception handler must extend the ExceptionHAndler class and override the method
- report(Exception $ex)
- 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:-
- Controller
- Middleware
Every controller must use the 3 traits
- Illuminate\Foundation\Bus\DispatcjesJObs
- Illuminate\Foundation\Validation\ValidatesREquests
- Illuminate\Foundation\Auth\Access\AuthorizesRequests
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
}
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 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:
- public function boot() {}
- public function register() {}
protected $listen = [
"App\Events\Event"=>[
"App\Listeners\EveentListener"];
];
public function map() {
$this->mapApiRoutes();
$this->mapWebRoutes();
}
Screenshots
- The app directory contains all the business logic and MVC(Model View Controller) implemention
- The config directory contains all the configuration settings for various objects in the Laravel service container
- The database directory contains all the migrations, seerders and factories
- The resources folder contains all the blade templates, HTML files, CSS fles and JavaScript files
- The public folder contains PHP files that are available to the entires application
- The routes folder contains all the web.php and api.php files for mapping HTTP requests (both GET and POST) to c0ontrollers
- The storage directory contains all the log files and otherarchival storage
- The tests folder contains the unit testing code
Helper functions
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
php artisan make:model
-> makes a Model classphp artisan make:controller
-> Makes a Controller classphp artisan make:migration
-> Runs all the migrationsphp artisan serve
-> Starts the serverphp artisan migration:refresh
-> Reverses all the previous migrationsphp artisan migrtaion:rollback
-> Reverses the latest migrationphp artisan scheduler
-> Schedules a program to run at specific intervals of time
composer update
Comments
Post a Comment