Promotional Codes Generator for Laravel >5

Overview

laravel-promocodes

Packagist Packagist license Scrutinizer Code Quality Build Status

Promocodes generator for Laravel 5.*. Trying to make the best package in this category. You are welcome to join the party, give me some advices ๐ŸŽ‰ and make pull requests.

laravel-promocodes

Table of Contents

What's new?

Installation

Install this package via Composer:

$ composer require zgabievi/promocodes

If you are using Laravel 5.5 or later, then installation is done. Otherwise follow the next steps.

Open config/app.php and follow steps below:

Find the providers array and add our service provider.

'providers' => [
    // ...
    Gabievi\Promocodes\PromocodesServiceProvider::class
],

Find the aliases array and add our facade.

'aliases' => [
    // ...
    'Promocodes' => Gabievi\Promocodes\Facades\Promocodes::class
],

Configuration

Publish config & migration file using Artisan command:

$ php artisan vendor:publish

To create table for promocodes in database run:

$ php artisan migrate

Configuration parameters are well documented. There is no need to describe each parameter here.

Check config/promocodes.php and read comments there if you need.

Usage

Generate as many codes as you wish and output them without saving to database.

You will get array of codes in return:

Promocodes::output($amount = 1);

Parameters

name type description required?
$amount number Number of items to be generated NO

Create as many codes as you wish. Set reward (amount).

Attach additional data as array. Specify for how many days should this codes stay alive.

By default generated code will be multipass (several users will be able to use this code once).

They will be saved in database and you will get collection of them in return:

Promocodes::create($amount = 1, $reward = null, array $data = [], $expires_in = null, $quantity = null, $is_disposable = false);

If you want to create code that will be used only once, here is method for you.

Promocodes::createDisposable($amount = 1, $reward = null, array $data = [], $expires_in = null, $quantity = null);

Parameters

name type description default required?
$amount integer Number of promocodes to generate 1 NO
$reward float Number of reward that user gets (ex: 30 - can be used as 30% sale on something) null NO
$data array Any additional information to get from promocode [] NO
$expires_in integer Number of days to keed promocode valid null NO
$quantity integer How many times can promocode be used? null NO
$is_disposable boolean If promocode is one-time use only false NO

Check if given code exists, is usable and not yet expired.

Returns Promocode object if valid, or false if not.

Promocodes::check($code);

Parameters

name type description required?
$code string Code to be checked for validity YES

If you want to check if user tries to use promocode for second time you can call Promocodes::isSecondUsageAttempt and pass Promocode object as an argument. As an answer you will get boolean value


Redeem or apply code. Redeem is alias for apply method.

User should be authenticated to redeem code or this method will throw an exception (\Gabievi\Promocodes\Exceptions\UnauthenticatedException).

Also if authenticated user will try to apply code twice, it will throw an exception (\Gabievi\Promocodes\Exceptions\AlreadyUsedException)

Returns Promocode object if applied, or false if not.

Promocodes::redeem($code);
Promocodes::apply($code);

Parameters

name type description required?
$code string Code to be applied by authenticated user YES

Get the collection of valid promotion codes.

Promocodes::all();

You can immediately expire code by calling disable function. Returning boolean status of update.

Promocodes::disable($code);

Parameters

name type description required?
$code string Code to be set as invalid YES

And if you want to delete expired, or non-usable codes you can erase them.

This method will remove redundant codes from database and their relations to users.

Promocodes::clearRedundant();

Promocodes can be related to users

If you want to use user relation open app/User.php and make it Rewardable as in example:

namespace App;

use Illuminate\Notifications\Notifiable;
use Gabievi\Promocodes\Traits\Rewardable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, Rewardable;

    // ...
}

Redeem or apply code are same. redeemCode is alias of applyCode

Pass promotion code you want to be applied by current user.

User::redeemCode($code, $callback = null);
User::applyCode($code, $callback = null);

Example (usage of callback):

$redeemMessage = $user->redeemCode('ABCD-DCBA', function ($promocode) use ($user) {
    return 'Congratulations, ' . $user->name . '! We have added ' . $promocode->reward . ' points on your account';
});

// Congratulations, Zura! We have added 10 points on your account

How to use additional data?

  1. Process of creation:
Promocodes::create(1, 25, ['foo' => 'bar', 'baz' => 'qux']);
  1. Getting data back:
Promocodes::redeem('ABC-DEF', function($promocode) {
    echo $promocode->data['foo'];
});

// bar

or

User::redeemCode('ABC-DEF', function($promocode) {
    echo $promocode->data['foo'];
});

// bar

Testing

Finally it's here. I've written some test to keep this package healthy and stable

laravel-promocodes tests

License

laravel-promocodes is licensed under a MIT License.

Comments
  • Monetary value?

    Monetary value?

    Hi, thanks for this awesome package. I have plans to include this in a project am working on but I want to understand how can i tweak your code if i want the generated codes to be attached to monetary value. Say how itunes gift card work.

    enhancement 
    opened by dayaki 16
  • Promocode can be used more than once

    Promocode can be used more than once

    I believe this package is the best in the category. I noticed one anamoly, calling Promocodes::apply($code) doesn't insert into pivot table and so, a user can use a promocode more than once.

    While reading the definition of apply method, i think this line isn't working as it must.

    $promocode->users()->attach(auth()->user()->id,[ 'used_at' => Carbon::now(), ]);

    I'm working to find a fix but I think you would have a better idea.

    opened by yasirlateef 8
  • Added opportunity to set fixed amount of promo codes

    Added opportunity to set fixed amount of promo codes

    Now you can do : Promocodes::create($amount, $reward, $data, $expiresIn, false, $amount); $amount is an integer.

    You need to make migration if you have already installed laravel-promocodes php artisan vendor:publish php artisan migrate

    opened by OleksiiBrylin 6
  • You have changed an important behavior: Throw AlreadyUsedException when user used it twice but other user can still use it

    You have changed an important behavior: Throw AlreadyUsedException when user used it twice but other user can still use it

    Unfortunately with this change you have removed an important behaviour:

    /** @test */
    public function it_throws_exception_coupon_was_used_before()
    {
        $this->signIn();
    
        Coupon::redeem($this->coupon['code']);
    
        $this->expectException('\Exception');
        $this->expectExceptionMessage(__('vue/checkout.coupon already used'));
    
        Coupon::redeem($this->coupon['code']);
    }
    

    This test is now with the update failing for me. It used to catch the error AlreadyUsedException, but even when is_disposable was set to false.

    This is important for this use-case: "Every user gets to use a Promocode, but every user only once'.

    The first test and this second test need to be true so that Promocode is working again.

    /** @test */
    public function multiple_users_can_use_the_same_promocode()
    {
        $this->signIn();
    
        $this->assertInstanceOf('Gabievi\Promocodes\Models\Promocode', Coupon::redeem($this->coupon['code']));
    
        $this->signIn(); // second user
        
        $this->assertInstanceOf('Gabievi\Promocodes\Models\Promocode', Coupon::redeem($this->coupon['code']));
    }
    

    I know that the alternative would be to use isSecondUsageAttempt.

    If you don't want to change the code, please update the readme file since it still says Also if authenticated user will try to apply code twice, it will throw an exception

    opened by pmochine 4
  • Validation promo code

    Validation promo code

    Hello, thank you for the package. What should be done when the user wants to apply the promo code? And the display of errors is intended? I think validation should be added with Laravel https://laravel.com/docs/9.x/validation#custom-validation-rules

    enhancement 
    opened by hasanmonfared 3
  • config values are not used in migration

    config values are not used in migration

    https://github.com/zgabievi/laravel-promocodes/blob/cb708ae8c73ee469719c288baf6d12767c89d6d6/migrations/2016_05_17_221000_create_promocodes_table.php#L15

    opened by neolikotsi 3
  • Installation error: Dependencies

    Installation error: Dependencies

    I'm trying to install your package, but get this:

      Problem 1
        - zgabievi/promocodes[8.1.0, ..., 8.1.1] require doctrine/dbal ^2.10 -> found doctrine/dbal[v2.10.0, ..., 2.12.x-dev] but the package is fixed to 3.0.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
        - Root composer.json requires zgabievi/promocodes ^8.1 -> satisfiable by zgabievi/promocodes[8.1.0, 8.1.1].
    
    Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
    

    Any suggestions ?

    opened by rabol 3
  • Feature request: Entering own promo codes and promos codes like lyft

    Feature request: Entering own promo codes and promos codes like lyft

    Can we enter our own promo codes and as well as pre-generated ones.

    Secondly was wondering if you can create the promo codes like LYFT. They give a 50$ coupon, where 5$ is applied per ride till 50 is done so 10 rides.

    Or any way you think I can use your packaged to do that ?

    And can you please change "Amount" to "number" - I got super confused as to what the diff between amount and reward was

    opened by heyaj19 3
  • Feature request + Question

    Feature request + Question

    Question: I am using Promocode::check($code) to check if promocode is available or not? But it is throwing InvalidPromocodeException exception, shouldn't it ideally return false, as that is the whole point of this function to check if code is valid or not?

    Feature request:

    • I don't see an option to let same user use same promo code multiple times say 2 or 3, how we do this?
    • How do we generate user specific promocodes? Promo code applicable only for a particular user?
    enhancement 
    opened by abhij89 3
  • Improvements to the package

    Improvements to the package

    @zgabievi When calling the 'attach' method, the package is explicitly relying that the primary key of 'User' model is 'id'. While in my project, I chose it to be 'user_id', so I think it's better to user 'auth()->id()' to get authenticated user's id.

    opened by yasirlateef 3
  • Any plans to improve the code quality of the package?

    Any plans to improve the code quality of the package?

    Hello, @zgabievi!

    The package looks nice, but a bit outdated. I faced some problems using it in production, had to override the main class.

    What you'll say if I'll send the PR of a more modern typed version of the package, and probably with the option to point out the model to use? It will require PHP 8 and probably Laravel 8.x.

    opened by michael-rubel 2
  • Fix decrement on unlimited usage

    Fix decrement on unlimited usage

    This pull request will fix decrementing on unlimited usages.

    After applying the first decrement the value it would be -2 and will break the apply method as it will always show no usage left

    opened by A-Ghorab 0
  • Column not found: 1054 Unknown column 'user_id' in 'field list'

    Column not found: 1054 Unknown column 'user_id' in 'field list'

    Hi,

    if you customize users foreign key in the config, create method throws an exception user_id column can not be found.

    something like this do the trick:

     return $this->generate()->map(fn(string $code) => app(PromocodeContract::class)->create([
                config('promocodes.models.users.foreign_id') => optional($this->user)->id,
                'code' => $code,
                'usages_left' => $this->unlimited ? -1 : $this->usagesLeft,
                'bound_to_user' => $this->user || $this->boundToUser,
                'multi_use' => $this->multiUse,
                'details' => $this->details,
                'expired_at' => $this->expiredAt,
            ]));
    
    opened by SidneySaints 0
  • PSR-4 issue with Zorb\Promocodes\Promocode\Promocode class

    PSR-4 issue with Zorb\Promocodes\Promocode\Promocode class

    I'm getting this one from composer:

    Class Zorb\Promocodes\Promocode\Promocode located in ./vendor/zgabievi/laravel-promocodes/src/Models/Promocode.php does not comply with psr-4 autoloading standard. Skipping.

    opened by piotrknapik 1
  • Lets user create promo code

    Lets user create promo code

    I want a user to able to create promo code by themselves and allow other users to redeem the promo code

    So the user that created the promo code can view the list of promo code he/she has And also know the promo code that have been redeemed by other user

    Note - Other user cannot see each other created promo code Except the specific promo code they redeem

    Is this possible or already available

    opened by Temian1 0
  • Partial usage of promotional code (gift card)

    Partial usage of promotional code (gift card)

    Is your feature request related to a problem? Please describe. When users purchase vouchers, the user can use that same voucher more than 1 time (Partial usage of voucher in case cart value is less than voucher value)

    Describe the solution you'd like Every time he uses the voucher, the amount will deduct from the voucher and the remaining amount will be stored as the current voucher amount. (gift cards feature)

    Describe alternatives you've considered There currently is a solution which requires some coding, but It'd be better if we would be able to achieve this with an easy way

    Additional context This feature was originally requested by: @prafful-panwar

    enhancement 
    opened by zgabievi 0
Releases(9.1.0)
Owner
Zura Gabievi
Web Developer as Singular
Zura Gabievi
Laravel Design Pattern Generator (api generator)

Laravel Design Pattern Generator (api generator) you can create your restful api easily by using this library and you can filter, sort and include elo

HusseinAlaa 2 Sep 25, 2022
Html menu generator for Laravel

Html Menu Generator for Laravel This is the Laravel version of our menu package adds some extras like convenience methods for generating URLs and macr

Spatie 813 Jan 4, 2023
A Laravel and Lumen Badges Generator

Laravel and Lumen Badge Generator That package is a easy wrapper to Badges/Poser. #Installing composer require vluzrmos/laravel-badge-poser Laravel co

Vagner Luz do Carmo 6 Jun 10, 2020
A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache.

Laravel OTP Introduction A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache. The ca

Lim Teck Wei 52 Sep 6, 2022
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023
A Laravel Code Generator based on your Models using Blade Template Engine

Laravel Code Generator is a PHP Laravel Package that uses Blade template engine to generate code for you. The difference between other code generators

Victor Yoalli 59 Dec 5, 2022
Laravel 5 Model Factory Generator

Laravel 5 Model Factory Generator This package offers a lazy way to create a new model factory files, since Laravel (< 5.5) have no Artisan command to

Roni Yusuf Manalu 16 Feb 15, 2020
API generator for Laravel 5

Apify API generator for Laravel 5 Table Of Contents Installation Configuration Usage Installation To install apify use composer Download composer requ

Erik C. Forรฉs 26 Dec 14, 2022
Scaffold generator for Laravel 5.x

Laravel 5.x Scaffold Generator Usage Step 1: Install Through Composer composer require 'laralib/l5scaffold' --dev Step 2: Add the Service Provider Op

null 315 Dec 8, 2022
Laravel 5 Barcode Generator

This is a barcode generation package inspired by https://github.com/tecnickcom/TCPDF. Actually, I use that package's underline classes for generating

Nuruzzaman Milon 1.1k Jan 6, 2023
Secret Phrase Generator for Laravel.

Secret Phrase Generator for Laravel It generates secret pass phrase for Laravel Auth System. Require "require": { "php": "^7.3|^8.0",

null 2 Feb 21, 2022
Simple project to send bulk comma-separated emails using laravel and messenger module from quick admin panel generator.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Novath Thomas 1 Dec 1, 2021
Laravel generator with GUI. Generate crud / scaffold.

Laravel generator with GUI. Generate crud / scaffold.

George 420 Dec 5, 2022
Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

Laravel Migrations Generator Generate Laravel Migrations from an existing database, including indexes and foreign keys! This package is cloned from ht

Kit Loong 1.4k Jan 1, 2023
Laravel MiGator - Migrations Generator

Laravel Migator A package that will allow developers to interactively generate schema migrations for a laravel application. It takes into account the

Synetic 2 Oct 13, 2022
Barcode generator in PHP that is easy to use, non-bloated and framework independent.

PHP Barcode Generator This is an easy to use, non-bloated, framework independent, barcode generator in PHP. It creates SVG, PNG, JPG and HTML images,

Picqer 1.4k Jan 6, 2023
The official Statamic 3 static site generator package

Statamic Static Site Generator Generate static sites with Statamic 3. Installation Install the package using Composer: composer require statamic/ssg

Statamic 187 Dec 25, 2022
Generator-hedley - Scaffold a headless Drupal backend, Angular app client, and Behat tests

generator-hedley Scaffold a headless Drupal backend, Angular app client, and Behat tests Hedley is a yeoman generator that scaffolds a headless Drupal

null 99 Jun 3, 2022
๐Ÿ”น Generator Template for ๐Ÿ™ƒ Phony Framework

?? Generator Template This repository contains the Generator Template for ?? Phony Framework. ?? Start generating fake data with ?? Phony Framework, v

Phonyland 2 Jan 30, 2022