Laravel | Important Questions & Functionality

 Laravel Important Functionality


# 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/update) them for you.

Dependency management: 

Composer is not a package manager in the same sense as Yum or Apt are. Yes, it deals with "packages" or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does however support a "global" project for convenience via the global command.

This idea is not new and Composer is strongly inspired by node's npm and ruby's bundler.

Suppose:

  1. You have a project that depends on a number of libraries.
  2. Some of those libraries depend on other libraries.

Composer:

  1. Enables you to declare the libraries you depend on.
  2. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).
  3. You can update all your dependencies in one command.


# Artisan

Artisan is the command line interface included with Laravel. It provides a number of helpful commands for your use while developing your application.

#3 Difference Between Cache and Cookies

ParametersCacheCookies
BasicsA system uses caches for storing content from a website and applications. They make things more accessible for a user.A website or application uses cookies to store the user’s activities and identify their trail of preferences.
Things StoredCache stores Javascript, CSS, HTML pages, media (images and videos), etc.Cookies store temporary data for tracking, such as browsing sessions, history of using websites and apps, etc.
CapacityCaches are comparatively less memory efficient. They occupy a lot of space on any device.Cookies are far more efficient with the device’s memory. They take up a very lesser amount of memory.
Location of StorageThe cache stores the website content only on a user browser.Cookies store their content on both- a server as well as a browser.
ExpirationOne needs to delete the cache manually. It does not expire automatically.The cookies have a very limited life span that depends entirely on their creators. The cookies, thus, expire after a fixed amount of time.

The default Expires value for a cookie is not a static time, but it creates a Session cookie. This will stay active until the user closes their browser/clears their cookies.


# Session

A session is a way to store information (in variables) to be used across multiple pages temporarily (until user close the website or destroy the session) . Unlike a cookie, the information is not stored on the users computer.
The default session time in PHP is 24 minutes (1440 seconds). You can increase the time from php. ini configuration file or using PHP function in your main file as per your need.

session_start();
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";

// remove all session variables
session_unset();

// destroy the session
session_destroy();

//unset any specific variable session
unset($_SESSION['variable_name']);

in laravel 
// Via a request instance...
$request->session()->put('key', 'value');
 
// Via the global "session" helper...
session(['key' => 'value']);

// Retrieve a data from the session key.

$data=session('key');




# Factory with Seeder (Right Way)

we use factory to generate demo data:

#1 Generate the factory

php artisan make:factory OrderFactory

after that update the factory accordingly with model name:

    protected $model = Order::class;

    public function definition(): array
    {
        return [
            'txn_id'    => fake()->name(),
            'user_id'   => User::inRandomOrder()->first('id')->id,
            'product'   => Str::random(12),
            'price'     => fake()->randomNumber(3),
        ];
    }

#2 Generate the seeder and add the factory on it.

php artisan make:seeder OrderSeeder

public function run(): void
    {
        Order::factory()->count(50)->create();
    }


#3 
(i) Seed directly by seeder classname 

we can run without register the seed by using the classname:

php artisan db:seed --class=UserSeeder


(ii) OR by adding the seeder in DatabaseSeeder class:

    public function run(): void
    {
        $this->call(OrderSeeder::class);
    }

php artisan db:seed

by this commend we can run multiple seeds at once by adding in the DatabaseSeeder  class.
    public function run(): void
    {
            $this->call(UserSeeder::class);
            $this->call(OrderSeeder::class);
 
    }

(iii) OR by adding the factory directly in DatabaseSeeder class:
we can skip the step 2 (make seeder class)
this is process:
#1 make factory
#2 add in databaseSeeder class

    public function run(): void
    {
            User::factory()->count(10)->create();
            Order::factory()->count(10)->create();
       
    }

#3 run : php artisan db:seed




# By using only Seeder (Not recommended)

#1 Make the seeder for table

php artisan make:seeder UserSeeder
php artisan make:seeder OrderSeeder

#2 Add value in the seeder class

public function run(): void
    {
        DB::table('users')->insert([
            [
                'name'          => Str::random(10),
                'email'         => Str::random(10). '@gmail.com',
                'phone'         => 9 . rand(123451547, 999999999),
                'password'      => Hash::make('password'),
                'created_at'    => date('Y-m-d H:i:s'),
                'updated_at'    => date('Y-m-d H:i:s'),
            ],
            [
                'name'          => Str::random(10),
                'email'         => Str::random(10). '@gmail.com',
                'phone'         => 9 . rand(123451547, 999999999),
                'password'      => Hash::make('password'),
                'created_at'    => date('Y-m-d H:i:s'),
                'updated_at'    => date('Y-m-d H:i:s'),
            ]
        ]);

    }

you can add one or more as per requirement. 
in the given example create, 2 records will be created.

#3 Register the seeder class in the "DatabaseSeeder" Class located in seeder folder

    public function run(): void
    {
        $this->call(UserSeeder::class);
    }

#4 Run the Seed Commend

php artisan db:seed

OR we can run without register the seed by using the classname:

php artisan db:seed --class=UserSeeder





# Rename the Column Name and Data Type using migration without losing data


#1 First of all we need to install "doctrine/dbal" composer package.

composer require doctrine/dbal

#2 create Rename the column name migration

public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->renameColumn('product', 'item');
            $table->bigInteger('price')->change();
        });
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->renameColumn('item', 'product');
            $table->string('price')->change();

        });
    }

#3 Run : php artisan migrate


# Traits: 

Using traits is one of the best practices alongside OOP. Traits are a mechanism for code reuse in single inheritance languages such as PHP.In simple terms Traits is a group of methods that you want to include within another class. You can easily reuse that methods to another class. Trait is save to write same code again and again.

it's work like the helper.

PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes, we can implement it.
  • Traits are a way to reuse code in Laravel.
  • They are similar to classes, but they cannot be instantiated on their own.
  • Traits can be included in classes to give them additional methods and functionality.
  • Traits offer several advantages, including code reusability, flexibility in composition, and adherence to the Single Responsibility Principle.

Step 1: Create a Traits Folder inside a app directory and create a new file of OrderTrait inside a Traits Folder (app\Traits\ArticlePostTrait).


<?php
  namespace App\Traits;

  use App\Models\Article;
  
  trait ArticlePostTrait {
      public function getAllArticles() {

            $articles = Article::all();

      }
  }


Step 2: Now Import Trait in a Controller.

use App\Traits\ArticlePostTrait;

Step 3: Use This ArticleTrait in other Class or Controller.

use App\Traits\ArticlePostTrait;

class ArticleController extends Controller {
    use ArticlePostTrait;

     public function index() {
        $articles = $this->getAllArticles();
        return $articles
    }
}



Accessors and Mutators

 Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

    //accessor and mutator
    protected function Name(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),  //accessor
            set: fn (string $value) => strtolower($value), //mutetor
        );
    }

    protected function phone(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => Crypt::decrypt($value),  //accessor
            set: fn (string $value) => Crypt::encrypt($value), //mutetor
        );
    }



# Multiple Database use in Laravel

#Step 1
In Laravel, database configuration is done in the config/database.php file. To set up multiple database connections, you need to define each connection in this file.

// config/database.php

'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
// ...
],

'second_db' => [
'driver' => 'mysql',
'host' => env('SECOND_DB_HOST', '127.0.0.1'),
'port' => env('SECOND_DB_PORT', '3306'),
'database' => env('SECOND_DB_DATABASE', 'forge'),
'username' => env('SECOND_DB_USERNAME', 'forge'),
'password' => env('SECOND_DB_PASSWORD', ''),
// ...
],
// Add more database connections as needed
],

#Step 2:
Set Environment Variables

To keep sensitive database credentials secure, use Laravel’s environment file (.env) to store them.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

SECOND_DB_CONNECTION=mysql
SECOND_DB_HOST=127.0.0.1
SECOND_DB_PORT=3306
SECOND_DB_DATABASE=second_database
SECOND_DB_USERNAME=second_username
SECOND_DB_PASSWORD=second_password


#Step 3:
 Create Models with different databases

php artisan make:model User -m
php artisan make:model Product -m

Be sure to specify the connection in the generated model files:

// app/Models/User.php
protected $connection = 'mysql';



// app/Models/Product.php
protected $connection = 'second_db';


Run Migration
php artisan migrate
php artisan migrate --database=second_db

Retrieve Data

// Retrieve users from the 'mysql' database $users = User::all(); // Retrieve products from the 'second_db' database $products = Product::all();

//second Way
DB::connection('tenant_xyz')->table('some_table')->get();


# Webhook

A webhook is an HTTP-based callback function that allows lightweight, event-driven communication between 2 application. webhooks are used to communicate the occurrence of an event in one system to another system, and they often share data about the event.

The Webhook payload is sent in standard JSON format and contains an event object with the following information represented by key-value pairs (KVPs)




#Some Laravel Importent Function

1. Str::uuid(): Str::uuid() method in Laravel generates a UUID (Universally Unique Identifier) which is highly unlikely to be duplicated. UUIDs are 128-bit values. 


        $uuid = Str::uuid();
        return $uuid; //// Outputs: 'f47ac10b-58cc-4372-a567-0e02b2c3d479'


2. str_shuffle(): is a function that randomly shuffles all the characters in a string. It’s a simple way to randomize the order of characters in a string.


        $string = "HelloWorld";
        $shuffledString = str_shuffle($string);
        echo $shuffledString; // Outputs: 'eWolHlodr'


 

# PUT and PACTH method

PUT and PATCH are both methods used to update resources on a server, but they have different uses: 

PUT: Used to replace an existing resource with a new one. This is best when you need to update or create a resource with a known identifier. PUT sends all the fields of the resource in the request body, even if they are not modified. 
PATCH: Used to make partial updates to an existing resource. This is a lightweight option to PUT because it only sends the fields that need to be changed in the request body.

# Request Response Code

1xx: Informational response that means the request was received and is being processed. These codes are rarely visible to the end user. 
2xx: Success response that means the action was received, understood, and accepted. 
3xx: Redirection response that means further action is needed to complete the request. 
404: Not found response that means the requested resource does not exist. 
400: Bad request response that means the data being sent to the request is incorrect, malformed, missing, or unusable by the server. 
500: Internal server error response that means the server failed to understand and handle a request. 
503: Service unavailable response that means the server is unavailable when the browser makes the request. 
410: Gone response that means the page used to be there, but it has been permanently removed. 
202 (Accepted): Response after deleted the record

# File Upload


#updating profile
        $image_path = "";
         if($request->hasFile('image')){
            #delete old profile photo
            $oldimg= public_path('storage/'.$product->image);
            if(File::exists($oldimg)){                
                File::delete($oldimg);
            }
            #upload image
            $image=$request->file('image');
            $uploadPath     = "storage/uploads/product/";
            $extension      = $image->getClientOriginalExtension();
            $filename       = time().'.'.$extension;
            $image_path     = $uploadPath.$filename;
            $image->move($uploadPath, $filename);
            $product->update(['image'=>$image_path]);
            }


# Easy Mail

Mail::html('<h1>Hi, welcome user!</h1>', function ($message) { $message->to('recipient@example.com') ->subject('Welcome to Our Service!'); });


Mail::raw('Hi, welcome user!', function ($message) { 

$message->to('recipient@example.com') 

->subject('Welcome to Our Service!'); });


# .htaccess file to secure project

<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Block Access to Sensitive Directories RewriteRule ^(app|bootstrap|config|database|resources|routes|tests|vendor|storage/(?!public/)).* - [F,L] </IfModule> <Files ~ "\.(env|json|config.js|md|gitignore|gitattributes|git|lock|example|xml|log)$"> Order allow,deny Deny from all </Files> <Files ~ "(artisan)$"> Order allow,deny Deny from all </Files> <FilesMatch "^\."> Require all denied </FilesMatch>


















Post a Comment

0 Comments

Visual Studio