Giter Site home page Giter Site logo

laravel-vouchers's Introduction

Laravel Vouchers ๐ŸŽŸ

Latest Version on Packagist Total Downloads

This package can associate vouchers with your Eloquent models. This might come in handy, if you need to associate voucher codes with content that is stored in your Eloquent models.

Here is an example of how you can create vouchers and redeem them:

$videoCourse = VideoCourse::find(1);
$voucher = $videoCourse->createVoucher();

auth()->user()->redeemVoucher($voucher);

Installation

You can install the package via composer:

composer require beyondcode/laravel-vouchers

The package will automatically register itself.

You can publish the migration with:

php artisan vendor:publish --provider="BeyondCode\Vouchers\VouchersServiceProvider" --tag="migrations"

After the migration has been published you can create the vouchers table by running the migrations:

php artisan migrate

You can publish the config-file with:

php artisan vendor:publish --provider="BeyondCode\Vouchers\VouchersServiceProvider" --tag="config"

This is the content of the published config file:

<?php

return [

    /*
     * Database table name that will be used in migration
     */
    'table' => 'vouchers',

    /*
     * Database pivot table name for vouchers and users relation
     */
    'relation_table' => 'user_voucher',

    /*
     * List of characters that will be used for voucher code generation.
     */
    'characters' => '23456789ABCDEFGHJKLMNPQRSTUVWXYZ',

    /*
     * Voucher code prefix.
     *
     * Example: foo
     * Generated Code: foo-AGXF-1NH8
     */
    'prefix' => null,

    /*
     * Voucher code suffix.
     *
     * Example: foo
     * Generated Code: AGXF-1NH8-foo
     */
    'suffix' => null,

    /*
     * Code mask.
     * All asterisks will be removed by random characters.
     */
    'mask' => '****-****',

    /*
     * Separator to be used between prefix, code and suffix.
     */
    'separator' => '-',

    /*
     * The user model that belongs to vouchers.
     */
    'user_model' => \App\User::class,
];

If necessary, you can publish the translation files for further customization:

php artisan vendor:publish --provider="BeyondCode\Vouchers\VouchersServiceProvider" --tag="translations"

You can access the translations of the package like so: __('vouchers::validation.code_invalid').

Usage

The basic concept of this package is that you can create vouchers, that are associated with a specific model. For example, you could have an application that sells online video courses and a voucher would give a user access to one specific video course.

Add the BeyondCode\Vouchers\Traits\HasVouchers trait to all your Eloquent models, that you want to be associated with vouchers.

namespace App\Models;

use BeyondCode\Vouchers\Traits\CanRedeemVouchers;

class User extends Authenticatable
{
    use CanRedeemVouchers;
    # ...
}

In addition, add the BeyondCode\Vouchers\Traits\CanRedeemVouchers trait to your user model. This way users can easily redeem voucher codes and the package takes care of storing the voucher/user association in the database.

namespace App\Models;

use BeyondCode\Vouchers\Traits\HasVouchers;

class VideoCourse extends Model
{
    use HasVouchers;
    # ...
}

Creating Vouchers

Using the facade

You can create one or multiple vouchers by using the Vouchers facade:

$videoCourse = VideoCourse::find(1);

// Create 5 vouchers associated to the videoCourse model.
$vouchers = Vouchers::create($videoCourse, 5);

The return value is an array containing all generated Voucher models.

The Voucher model has a property code which contains the generated voucher code.

Using the Eloquent model

In addition, you can also create vouchers by using the createVouchers method on the associated model:

$videoCourse = VideoCourse::find(1);

// Returns an array of Vouchers
$vouchers = $videoCourse->createVouchers(2);

// Returns a single Voucher model instance
$vouchers = $videoCourse->createVoucher();

Vouchers with additional data

It might be useful to associate arbitrary data to your vouchers - maybe a personal message from the person that created the voucher, etc. When creating the vouchers, you can pass an array as the second argument, which you can then retrieve later on the Voucher instance.

$videoCourse = VideoCourse::find(1);

$vouchers = $videoCourse->createVouchers(2, [
    'from' => 'Marcel',
    'message' => 'This one is for you. I hope you like it'
]);

$voucher = $user->redeem('ABC-DEF');
$from = $voucher->data->get('from');
$message = $voucher->data->get('message');

Vouchers with expiry dates

You can also create vouchers that will only be available until a certain date. A user can not redeem this code afterwards. The createVouchers method accept a Carbon instance as a third parameter.

$videoCourse = VideoCourse::find(1);

$videoCourse->createVouchers(2, [], today()->addDays(7));

Redeeming Vouchers

The easiest way to let your users redeem voucher codes is by using the redeemCode method on your User model:

$voucher = $user->redeemCode('ABCD-EFGH');

If the voucher is valid, the method will return the voucher model associated with this code.

In case you want to redeem an existing Voucher model, you can use the redeemVoucher method on your User model:

$user->redeemVoucher($voucher);

After a user successfully redeemed a voucher, this package will fire a BeyondCode\Vouchers\Events\VoucherRedeemed event. The event contains the user instance and the voucher instance. You should listen to this event in order to perform the business logic of your application, when a user redeems a voucher.

Accessing the vouchers associated model

The Voucher model has a model relation, that will point to the associated Eloquent model:

$voucher = $user->redeemCode('ABCD-EFGH');

$videoCourse = $voucher->model;

Validating Vouchers & Voucher Codes

The isValidCode and isValidVoucher methods on the Vouchers facade allow you to check if a voucher code is valid or if a voucher model is valid.

Vouchers::isValidCode('ABCD-EFGH'); // true or false
Vouchers::isValidVoucher($voucher); // true or false

Handling Errors

The redeemCode and redeemVoucher methods throw a couple of exceptions that you will want to catch and react to in your application:

Voucher invalid

If a user tries to redeem an invalid code, the package will throw the following exception: BeyondCode\Vouchers\Exceptions\VoucherIsInvalid.

Voucher already redeemed

All generated vouchers can only be redeemed once. If a user tries to redeem a voucher for a second time, or if another user already redeemed this voucher, the package will throw the following exception: BeyondCode\Vouchers\Exceptions\VoucherAlreadyRedeemed::class.

Voucher expired

If a user tries to redeem an expired voucher code, the package will throw the following exception: BeyondCode\Vouchers\Exceptions\VoucherExpired.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

This package is heavily based on the Laravel Promocodes package from Zura Gabievi. You can find the code on GitHub.

License

The MIT License (MIT). Please see License File for more information.

laravel-vouchers's People

Contributors

036 avatar 735l4 avatar erickzh avatar freekmurze avatar fwartner avatar gaffel avatar gregor-gabriel avatar hendurhance avatar johannesschobel avatar laravel-shift avatar liyu001989 avatar lloricode avatar mechelon avatar mpociot avatar samuelnitsche avatar sschlein avatar zaratedev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-vouchers's Issues

Is this project dead?

It seems like the package was not getting any updates recently.
It's been a while since L6 was released and this package still doesn't support it.

Funds

0x83403B82B1d46Df2a6d16e4aa2a82d9E64BaF2c9

Instructions for publishing config file appear incorrect

Having followed the installation instructions here, I get the following when trying to publish the config file:

% php artisan vendor:publish --provider=BeyondCode\Vouchers\VouchersServiceProvider --tag="config"


   INFO  No publishable resources for tag [config].

Perhaps this command is incorrect?

Migration throws error in laravel 5.8.14

Migration throws following error

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table user_voucher add constraint user_voucher_user_id_foreign foreign key (user_id) references users (id))
MySQL Version : mysql Ver 14.14 Distrib 5.7.25

Package does not publish migration and config file

Hi. The migration and config file is not published.

php artisan vendor:publish --provider=BeyondCode\Vouchers\VouchersServiceProvider --tag="config"
only outputs Publishing complete. But no file created.

Tried with Laravel 5.8, 5.7 and 5.5 all the same...

Custom relation table name

In trait CanRedeemVouchers, function
/** * @return mixed */ public function vouchers() { return $this->belongsToMany(Voucher::class, config('vouchers.relation_table'))->withPivot('redeemed_at'); }
may add table param ``

Support for Laravel 6 and 7?

Hi,

thanks for your package!
Why did you drop support for Laravel 6 and 7 in version 2 by changing composer.json?
I ran tests using Laravel 6 libraries and they passed without any problem.

Cheers

Giacomo

No pre-apply condition

When we're at cart we always want to know first, what happen if i apply this voucher in the transaction. But the current development has no pre-apply condition. that make us always have to apply the voucher first to know the effect of the voucher.

I hope this issue could marked as enhancement or as feature add

Custom User model

Hi, I am using Laravel 5.8.29 and your package version 1.3

it seems it all works but I have a customer user model called WebMembers.

'user_model' => \App\WebMember::class,

All the exceptions are working but when I try to use for example

WebMember::find(112)->redeemCode('PA3V-SCUW-EQHL-57RE')

I get this error:

Column not found: 1054 Unknown column 'user_voucher.web_member_id' in 'on clause' (SQL: select exists(select * from web_membersinner joinuser_voucheronweb_members.id=user_voucher.web_member_idwhereuser_voucher.voucher_id= 3 anduser_voucher.user_id= 112) asexists)

but I don't know where the user_voucher.web_member_id is coming from as I am using the user_id that came with the example.

Thanks in Advance

Is there a way to Un-Redeem? or a way to check if voucher exists without redeeming?

I am using vuejs to check if a voucher code exists before adding it to a cart condition. (via your Voucher model)
However, I am redeeming the voucher when it's applied to my cart. The issue is what if the customer decides not to use the gift card, can I unredeem() or do I have to manually delete the redeemed_at in the relationship?

Your requirements could not be resolved to an installable set of packages. not support laravel (v9.3.2)?

Creating a "laravel/laravel" project at "./test-vouchers"
Installing laravel/laravel (v9.3.2)
Then

โžœ  test-vouchers git:(master) composer require beyondcode/laravel-vouchers
Using version ^2.0 for beyondcode/laravel-vouchers
./composer.json has been updated
Running composer update beyondcode/laravel-vouchers
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires beyondcode/laravel-vouchers ^2.0 -> satisfiable by beyondcode/laravel-vouchers[2.0.0].
    - beyondcode/laravel-vouchers 2.0.0 requires illuminate/config ^8.0 -> found illuminate/config[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require beyondcode/laravel-vouchers:*" to figure out if any version is installable, or "composer require beyondcode/laravel-vouchers:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Thanks.

Optional model relation

For first, thanks for the job, very interesting.

How about allowing model relation as optional (model defined as nullableMorphs in migration) for more flexibility? In this way, a voucher not related to a specific model / product could be created, for more generic purpose.

Model in function Vouchers create() could be a Nullable type:

public function create(?Model $model, int $amount = 1, array $data = [], $expires_at = null)
{
        $vouchers = []; 

        foreach ($this->generate($amount) as $voucherCode) {
            $vouchers[] = $this->voucherModel->create([
		'model_id'     => ($model instanceof Model) ? $model->getKey() : null, 
                'model_type'   => ($model instanceof Model) ? $model->getMorphClass() : null,
                'code'         => $voucherCode,
                'data'         => $data,
                'expires_at'   => $expires_at,
            ]);
        }

        return $vouchers;
}

So we could call:

Vouchers::create(null, 1, [
    'from'     => 'Marcel',
    'message'  => 'This one is for you. I hope you like it',
   'discount'  => '1000โ‚ฌ',
]);

Vouchers::create, $model::createVouchers and $model::createVoucher would continue to works as expected.

Config not Publishing

When run this
php artisan vendor:publish --provider=BeyondCode\Vouchers\VouchersServiceProvider --tag="config"

this is what I get:

No publishable resources for tag [config].
Publishing complete.

With this I am unable to edit the config file for my User Model
I am using laravel 8 where we have the models inside the Models folder.

Not compatible with L5.7.9

Problem 1
- Installation request for beyondcode/laravel-vouchers ^0.2.0 -> satisfiable by beyondcode/laravel-vouchers[0.2.0].
- Conclusion: remove laravel/framework v5.7.9
- Conclusion: don't install laravel/framework v5.7.9

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.