CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

29 November, 2022

A Coupons and Promotional Codes Generator for Laravel

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 


Laravel-promocodes is an awesome coupon and promotional code generator for Laravel. The current release is for Laravel 9.x and PHP 8.1. It's completely rewritten, if you use the previous version, you should change your code accordingly. The code is simplified now and it should take you several minutes to completely rewrite usage.

Installation

You can install the package via composer:

composer require zgabievi/laravel-promocodes

Configuration

php artisan vendor:publish --provider="Zorb\Promocodes\PromocodesServiceProvider"

After you configure this file, run migrations:

php artisan migrate

Now you will need to use AppliesPromocode on your user model.

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zorb\Promocodes\Traits\AppliesPromocode;

class User extends Authenticatable {
    use AppliesPromocode;

    //
}

Usage

It's very easy to use. Methods are combined so that you can configure promo codes easily.

Creating Promo codes

Using class

Combine methods as you need. You can skip any method that you don't need, most of them already have default values.

use Zorb\Promocodes\Facades\Promocodes;

Promocodes::mask('AA-***-BB') // default: config('promocodes.code_mask')
          ->characters('ABCDE12345') // default: config('promocodes.allowed_symbols')
          ->multiUse() // default: false
          ->unlimited() // default: false
          ->boundToUser() // default: false
          ->user(User::find(1)) // default: null
          ->count(5) // default: 1
          ->usages(5) // default: 1
          ->expiration(now()->addYear()) // default: null
          ->details([ 'discount' => 50 ]) // default: []
          ->create();

Using helper

There is a global helper function that will do the same as promocodes class. You can use named arguments magic from php 8.1.

createPromocodes(
    mask: 'AA-***-BB', // default: config('promocodes.code_mask')
    characters: 'ABCDE12345', // default: config('promocodes.allowed_symbols')
    multiUse: true, // default: false
    unlimited: true, // default: false
    boundToUser: true, // default: false
    user: User::find(1), // default: null
    count: 5, // default: 1
    usages: 5, // default: 1
    expiration: now()->addYear(), // default: null
    details: [ 'discount' => 50 ] // default: []
);

Using command

There is also the command for creating promocodes. Parameters are optional here too.

php artisan promocodes:create\
  --mask="AA-***-BB"\
  --characters="ABCDE12345"\
  --multi-use\
  --unlimited\
  --bound-to-user\
  --user=1\
  --count=5\
  --usages=5\
  --expiration="2022-01-01 00:00:00"

Generating Promocodes

If you want to output promocodes and not save them to the database, you can call generate method instead of create.

use Zorb\Promocodes\Facades\Promocodes;

Promocodes::mask('AA-***-BB') // default: config('promocodes.code_mask')
          ->characters('ABCDE12345') // default: config('promocodes.allowed_symbols')
          ->multiUse() // default: false
          ->unlimited() // default: false
          ->boundToUser() // default: false
          ->user(User::find(1)) // default: null
          ->count(5) // default: 1
          ->usages(5) // default: 1
          ->expiration(now()->addYear()) // default: null
          ->details([ 'discount' => 50 ]) // default: []
          ->generate();

Applying Promocode

Using class

Combine methods as you need. You can skip any method that you don't need.

use Zorb\Promocodes\Facades\Promocodes;

Promocodes::code('ABC-DEF')
          ->user(User::find(1)) // default: null
          ->apply();

Using helper

There is a global helper function that will do the same as the promocodes class.

applyPomocode(
    'ABC-DEF',
    User::find(1) // default: null
);

Using command

There is also the command for applying promocode.

php artisan promocodes:apply ABC-DEF --user=1

For more details and source code, please visit Github.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Automatically Restart Horizon When Local PHP Files Change

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 



How many hours have lost debugging local jobs only to find out that you forgot to restart Horizon?

Laravel Horizon Watcher package contains an Artisan command horizon:watch that will start Horizon and automatically restart it when any PHP file is created, updated, or deleted.

This command is meant to be used in the local environment.

Installation

You can install the package via composer:

composer require spatie/laravel-horizon-watcher --dev

In your project, you should have the JavaScript package chokidar installed. You can install it.

via npm

npm install chokidar

or Yarn

yarn add chokidar

Optionally, you can publish the config file with this command:

php artisan vendor:publish --tag="horizon-watcher-config"

Usage

Run this command

php artisan horizon:watch

to start Horizon. When a PHP file in your project gets created, updated, or deleted, Horizon will automatically restart.

For more details and source code, please visit Github.

Closing Note

The team of Codebrisk Laravel developers is always ready to execute even your boldest ideas. Our expert team can design and develop any type of custom CRM solution, SAAS app, or e-commerce app to meet our customer's needs and transform our customer's experiences. Get in touch with our team to discuss your bespoke ideas and learn more about the next steps to launching cooperation.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

A Set of Amazing Laravel Validation Rules for Credit Card

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 

This is a Set of Amazing Laravel Validation Rules for Credit Cards that will validate that a given credit card number, expiration date, or CVC is valid.

Usage

As FormRequest

<?php

namespace App\Http\Requests;

use LVR\CreditCard\CardCvc;
use LVR\CreditCard\CardNumber;
use LVR\CreditCard\CardExpirationYear;
use LVR\CreditCard\CardExpirationMonth;
use Illuminate\Foundation\Http\FormRequest;

class CreditCardRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'card_number' => ['required', new CardNumber],
            'expiration_year' => ['required', new CardExpirationYear($this->get('expiration_month'))],
            'expiration_month' => ['required', new CardExpirationMonth($this->get('expiration_year'))],
            'cvc' => ['required', new CardCvc($this->get('card_number'))]
        ];
    }
}

Card number

From request

$request->validate(
    ['card_number' => '37873449367100'],
    ['card_number' => new LVR\CreditCard\CardNumber]
);

Directly

(new LVR\CreditCard\Cards\Visa)
    ->setCardNumber('4012888888881881')
    ->isValidCardNumber()

Card Expiration

From request

// CardExpirationYear requires card expiration month
$request->validate(
    ['expiration_year' => '2017'],
    ['expiration_year' => ['required', new LVR\CreditCard\CardExpirationYear($request->get('expiration_month'))]]
);

// CardExpirationMonth requires card expiration year
$request->validate(
    ['expiration_month' => '11'],
    ['expiration_month' => ['required', new LVR\CreditCard\CardExpirationMonth($request->get('expiration_year'))]]
);

// CardExpirationDate requires date format
$request->validate(
    ['expiration_date' => '02-18'],
    ['expiration_date' => ['required', new LVR\CreditCard\CardExpirationDate('my')]]
);

Directly

LVR\CreditCard\Cards\ExpirationDateValidator(
    $expiration_year,
    $expiration_month
)->isValid();

// Or static
LVR\CreditCard\Cards\ExpirationDateValidator::validate(
    $expiration_year,
    $expiration_month
);

Card CVC

From request

// CardCvc requires card number to determine allowed cvc length
$request->validate(
    ['cvc' => '123'],
    ['cvc' => new LVR\CreditCard\CardCvc($request->get('card_number'))]
);

Directly

LVR\CreditCard\Cards\Card::isValidCvcLength($cvc);

For more details, Please visit Github.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Automatically Maintain Model Columns with Laravel Userstamps

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 


Laravel Userstamps provides an Eloquent trait that automatically maintains created_by and updated_by columns on your model, populated by the currently authenticated user in your application.

When using the Laravel SoftDeletes trait, a deleted_by column is also handled by this package.

Installation

This package requires Laravel 5.2 or later running on PHP 5.6 or higher.

This package can be installed using composer:

composer require wildside/userstamps

Usage

Your model must include a created_by and updated_by column, defaulting to null.

Using the Laravel SoftDeletes trait will also need a deleted_by column.

The column type should match the type of the ID column in your user's table. In Laravel <= 5.7 this defaults to unsignedInteger. For Laravel >= 5.8 this defaults to unsignedBigInteger.

An example migration:

$table->unsignedBigInteger('created_by')->nullable();
$table->unsignedBigInteger('updated_by')->nullable();

You can now load the trait within your model, and userstamps will automatically be maintained:

use Wildside\Userstamps\Userstamps;

class Foo extends Model {

    use Userstamps;
}

Optionally, should you wish to override the names of the created_by, updated_by, or deleted_by columns, you can do so by setting the appropriate class constants on your model. Ensure you match these column names in your migration.

use Wildside\Userstamps\Userstamps;

class Foo extends Model {

    use Userstamps;

    const CREATED_BY = 'alt_created_by';
    const UPDATED_BY = 'alt_updated_by';
    const DELETED_BY = 'alt_deleted_by';
}

When using this trait, helper relationships are available to let you retrieve the user who created, updated, and deleted (when using the Laravel SoftDeletes trait) your model.

$model->creator; // the user who created the model
$model->editor; // the user who last updated the model
$model->destroyer; // the user who deleted the model

Methods are also available to temporarily stop the automatic maintenance of userstamps on your models:

$model->stopUserstamping(); // stops userstamps being maintained on the model
$model->startUserstamping(); // resumes userstamps being maintained on the model

Workarounds

This package works by hooking into Eloquent's model event listeners and is subject to the same limitations as all such listeners.

When you make changes to models that bypass Eloquent, the event listeners won't be fired and userstamps will not be updated.

Commonly this will happen if bulk updating or deleting models or their relations.

In this example, model relations are updated via Eloquent and userstamps will be maintained:

$model->foos->each(function ($item) {
    $item->bar = 'x';
    $item->save();
});

However, in this example, model relations are bulk updated and bypass Eloquent. Userstamps will not be maintained:

$model->foos()->update([
    'bar' => 'x',
]);

For more details, please visit Github.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Rector Rules for Laravel for Refactors the Code of Your App

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 





Rector instantly upgrades and refactors the PHP code of your application. This package is a Rector extension developed by the Laravel community.

Installation

You can install the RectorLaravel package as a dependency:

composer require driftingly/rector-laravel --dev

Use Sets

To add a set to your config, use RectorLaravel\Set\LaravelSetList class and pick one of the constants:

use RectorLaravel\Set\LaravelSetList;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->sets([
        LaravelSetList::LARAVEL_90
    ]);
};

Laravel Rules for Rector

AddArgumentDefaultValueRector

Adds default value for arguments in defined methods.

configure it!

class: RectorLaravel\Rector\ClassMethod\AddArgumentDefaultValueRector

use Rector\Config\RectorConfig;
use RectorLaravel\Rector\ClassMethod\AddArgumentDefaultValueRector;
use RectorLaravel\ValueObject\AddArgumentDefaultValue;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(AddArgumentDefaultValueRector::class, [
        AddArgumentDefaultValueRector::ADDED_ARGUMENTS => [
            new AddArgumentDefaultValue('SomeClass', 'someMethod', 0, false),
        ],
    ]);
};
 class SomeClass
 {
-    public function someMethod($value)
+    public function someMethod($value = false)
     {
     }
 }

AddGenericReturnTypeToRelationsRector

Add generic return type to relations in the child of Illuminate\Database\Eloquent\Model

class: RectorLaravel\Rector\ClassMethod\AddGenericReturnTypeToRelationsRector

 use App\Account;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\HasMany;

 class User extends Model
 {
+    /** @return HasMany<Account> */
     public function accounts(): HasMany
     {
         return $this->hasMany(Account::class);
     }
 }

AddGuardToLoginEventRector

Add new $guard argument to Illuminate\Auth\Events\Login

class: RectorLaravel\Rector\New_\AddGuardToLoginEventRector

 use Illuminate\Auth\Events\Login;

 final class SomeClass
 {
     public function run(): void
     {
-        $loginEvent = new Login('user', false);
+        $guard = config('auth.defaults.guard');
+        $loginEvent = new Login($guard, 'user', false);
     }
 }

AddParentRegisterToEventServiceProviderRector

Add parent::register(); call to register() class method in child of Illuminate\Foundation\Support\Providers\EventServiceProvider

class: RectorLaravel\Rector\ClassMethod\AddParentRegisterToEventServiceProviderRector

 use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

 class EventServiceProvider extends ServiceProvider
 {
     public function register()
     {
+        parent::register();
     }
 }

There are 25 Laravel Rector Rules in this package. You can see all these rules on Github.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Google Cloud Tasks to be used as the Queue Driver in Laravel

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 Laravel Google Cloud Tasks Queue package allows Google Cloud Tasks to be used as the queue driver. This package requires Laravel 6 or higher and supports MySQL 8 and PostgreSQL 14. Might support older database versions too, but the package hasn't been tested for it.

Installation

For the installation purpose, Please require the package using Composer.

composer require stackkit/laravel-google-cloud-tasks-queue

Add a new queue connection to config/queue.php.

'cloudtasks' => [
    'driver' => 'cloudtasks',
    'project' => env('STACKKIT_CLOUD_TASKS_PROJECT', ''),
    'location' => env('STACKKIT_CLOUD_TASKS_LOCATION', ''),
    'handler' => env('STACKKIT_CLOUD_TASKS_HANDLER', ''),
    'queue' => env('STACKKIT_CLOUD_TASKS_QUEUE', 'default'),
    'service_account_email' => env('STACKKIT_CLOUD_TASKS_SERVICE_EMAIL', ''),
    // Optional: The deadline in seconds for requests sent to the worker. If the worker
    // does not respond by this deadline then the request is canceled and the attempt
    // is marked as a DEADLINE_EXCEEDED failure.
    'dispatch_deadline' => null,
    'backoff' => 0,
],

Update the QUEUE_CONNECTION environment variable

QUEUE_CONNECTION=cloudtasks

How it works & Differences

Using Cloud Tasks as a Laravel queue driver is fundamentally different than other Laravel queue drivers, like Redis.

Typically a Laravel queue has a worker that listens to incoming jobs using the queue:work / queue:listen command. With Cloud Tasks, this is not the case. Instead, Cloud Tasks will schedule the job for you and make an HTTP request to your application with the job payload. There is no need to run a queue:work/listen command.

Dashboard (beta)

The package comes with a beautiful dashboard that can be used to monitor all queued jobs. Experimental

The dashboard works by storing all outgoing tasks in a database table. When Cloud Tasks calls the application and this package handles the task, we will automatically update the tasks' status, attempts, and possible errors.

There is probably a (small) performance penalty because each task dispatch and handling does extra database reads and writes. Also, the dashboard has not been tested with high throughput queues.

To make use of it, enable it through the .env file:

STACKKIT_CLOUD_TASKS_DASHBOARD_ENABLED=true
STACKKIT_CLOUD_TASKS_DASHBOARD_PASSWORD=MySecretLoginPasswordPleaseChangeThis

Then publish its assets and migrations:

php artisan vendor:publish --tag=cloud-tasks
php artisan migrate

The dashboard is accessible at the URI: /cloud-tasks

Authentication

Set the GOOGLE_APPLICATION_CREDENTIALS environment variable with a path to the credentials file.

More info: https://cloud.google.com/docs/authentication/production

If you're not using your master service account (which has all abilities), you must add the following roles to make it works:

  1. App Engine Viewer
  2. Cloud Tasks Enqueuer
  3. Cloud Tasks Viewer
  4. Cloud Tasks Task Deleter
  5. Service Account User

Security

The job handler requires each request to have an OpenID token. In the installation step, we set the service account email, and with that service account, Cloud Tasks will generate an OpenID token and send it along with the job payload to the handler.

This package verifies that the token is digitally signed by Google. Only Google Tasks will be able to call your handler.

For more details about this package, Please visit Github

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Waterline - An elegant UI for monitoring Laravel Workflows

 Programing Coderfunda     November 29, 2022     Laravel, laravel-packages, php     No comments   

 Waterline is an amazing and elegant UI for monitoring Laravel Workflows.

Installation

This UI is installable via Composer.

composer require laravel-workflow/waterline
php artisan waterline:install

Authorization

Waterline exposes a dashboard at the /waterline URL. By default, you will only be able to access this dashboard in the local environment. However, within your app/Providers/WaterlineServiceProvider.php file, there is an authorization gate definition. This authorization gate controls access to Waterline in non-local environments.

Gate::define('viewWaterline', function ($user) {
    return in_array($user->email, [
        'admin@example.com',
    ]);
});

This will allow only the single admin user to access the Waterline UI.

Upgrading Waterline

After upgrading Waterline you must publish the latest assets.

composer require laravel-workflow/waterline
php artisan waterline:publish

Dashboard View


Workflow View


For more details and source code, please visit Github.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Python AttributeError: 'str' has no attribute glob
    I am trying to look for a folder in a directory but I am getting the error.AttributeError: 'str' has no attribute glob Here's ...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (2)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda