• Stars
    star
    279
  • Rank 143,111 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 4 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This package allows you to easily manage invite codes for your Laravel application.

Laravel Invite Codes

Readme banner This package allows you to easily manage invite codes for your Laravel application.

Total Downloads Latest Stable Version License Continuous integration

Sponsor my work!

If you think this package helped you in any way, you can sponsor me on GitHub! Sponsor Me

Documentation

Installation

To get started with Laravel Invite Codes, use Composer to add the package to your project's dependencies:

composer require mateusjunges/laravel-invite-codes

Or add this line in your composer.json, inside of the require section:

{
    "require": {
        "mateusjunges/laravel-invite-codes": "^1.6",
    }
}

then run composer install.

All migrations required for this package are already included. If you need to customize the tables, you can publish them with:

php artisan vendor:publish --provider="Junges\InviteCodes\InviteCodesServiceProvider" --tag="invite-codes-migrations"

and set the config for custom_migrations to true, which is false by default.

'custom_migrations' => true,

After the migrations have been published you can create the tables on your database by running the migrations:

php artisan migrate

If you change the table names on migrations, please publish the config file and update the tables array. You can publish the config file with:

php artisan vendor:publish --provider="Junges\InviteCodes\InviteCodesServiceProvider" --tag="invite-codes-config"

When published, the config/invite-codes.php config file contains:

<?php

return [
    /*
    |--------------------------------------------------------------------------
    |  Models
    |--------------------------------------------------------------------------
    |
    | When using this package, we need to know which Eloquent Model should be used
    | to retrieve your invites. Of course, it is just the basics models
    | needed, but you can use whatever you like.
    |
    */
    'models' => [
        'invite_model' => \Junges\InviteCodes\Http\Models\Invite::class,
    ],

    /*
    |--------------------------------------------------------------------------
    | Tables
    |--------------------------------------------------------------------------
    | Specify the basics authentication tables that you are using.
    | Once you required this package, the following tables are
    | created by default when you run the command
    |
    | php artisan migrate
    |
    | If you want to change this tables, please keep the basic structure unchanged.
    |
    */
    'tables' => [
        'invites_table' => 'invites',
    ],

    /*
    |--------------------------------------------------------------------------
    | User
    |--------------------------------------------------------------------------
    | To use the ProtectedByInviteCode middleware provided by this package, you need to
    | specify the email column you use in the model you use for authentication.
    | If not specified, only invite code with no use restrictions can be used in this middleware.
    |
    */
    'user' => [
        'email_column' => 'email',
    ],

    /*
    |--------------------------------------------------------------------------
    | Custom migrations
    |--------------------------------------------------------------------------
    | If you want to publish this package migrations and edit with new custom columns, change it to true.
    */
    'custom_migrations' => false,
];

Usage

This package provides a middleware called ProtectedByInviteCodeMiddleware. If you want to use it to protect your routes, you need to register it in your $routeMiddleware array, into app/Http/Kernel.php file:

$routeMiddleware = [
    'protected_by_invite_codes' => ProtectedByInviteCodeMiddleware::class,
];

Now you can protect your routes using middleware rules:

Route::get('some-route', function() {
    //
})->middleware('protected_by_invite_codes');

You can also add it to the __construct(), in your controllers:

public function __construct()
{
    $this->middleware('protected_by_invite_codes');
}

Creating invite codes

To create a new invite code, you must use the InviteCodes facade. Here is a simple example:

$invite_code = \Junges\InviteCodes\Facades\InviteCodes::create()
    ->expiresAt('2020-02-01')
    ->maxUsages(10)
    ->restrictUsageTo('[email protected]')
    ->save();

The code above will create a new invite code, which can be used 10 times only by a logged in user who has the specified email [email protected].

The methods you can use with the InviteCodes facade are listed below:

Set the expiration date of your invite code

To set the expiration date of your invite code you can use one of the following methods:

  • expiresAt(): This method accept a date string in yyyy-mm-dd format or a Carbon instance, and set the expiration date to the specified date.
  • expiresIn(): This method accept an integer, and set the expiration date to now plus the specified amount of days.

Restrict usage to some specific user:

To restrict the usage of an invite code you can use the restrictUsageTo() method, and pass in the email of the user who will be able to use this invite code.

Set the maximum allowed usages for an invite code:

If you want that your invite code be used a limited amount of times, you can set the max usages limit with the maxUsages() method, and pass an integer with the amount of allowed usages.

Also, you can use the declarative syntax, and use the canBeUsedXTimes() method, where X is the amount of times your invite code will be usable. For example:

  • ->canBeUsed10Times(): This invite code can be used 10 times.
  • ->canBeUsed50Times(): This invite code can be used 50 times.

You can use any integer number you want with this method.

Create multiple invite codes

If you want to create more than one invite code with the same configs, you can use the make() method. This method generates the specified amount of invite codes. For example:

\Junges\InviteCodes\Facades\InviteCodes::create()
    ->maxUsages(10)
    ->expiresIn(30)
    ->make(10);

The code above will create 10 new invite codes which can be used 10 times each, and will expire in 30 days from now.

Redeeming invite codes

To redeem an invite code, you can use the redeem method:

\Junges\InviteCodes\Facades\InviteCodes::redeem('YOUR-INVITE-CODE');

When any invite is redeemed, the InviteRedeemedEvent will be dispatched.

Redeeming invite codes without dispatching events

If you want to redeem an invite codes without dispatch the InviteRedeemedEvent, you can use the withoutEvents() method:

\Junges\InviteCodes\Facades\InviteCodes::withoutEvents()->redeem('YOUR-INVITE-CODE');

Handling invite codes exceptions

If you want to override the default 403 response, you can catch the exceptions using the laravel exception handler:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Junges\InviteCodes\Exceptions\InviteWithRestrictedUsageException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\ExpiredInviteCodeException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\DuplicateInviteCodeException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\InvalidInviteCodeException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\UserLoggedOutException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\InviteMustBeAbleToBeRedeemedException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\SoldOutException) {
        //
    }
    if ($exception instanceof \Junges\InviteCodes\Exceptions\RouteProtectedByInviteCodeException) {
        //
    }
    
    return parent::render($request, $exception);
}

Using artisan commands

This package also provides a command to delete all expired invites from your database. You can use it like this:

\Illuminate\Support\Facades\Artisan::call('invite-codes:clear');

After all expired invites has been deleted, it will dispatch the DeletedExpiredInvitesEvent.

Tests

Run composer test to test this package.

Contributing

Thank you for considering contributing for the Laravel Invite Codes package! The contribution guide can be found here.

Changelog

Please see changelog for more information about the changes on this package.

License

The Laravel Invite Codes package is open-sourced software licenced under the MIT License. Please see the License File for more information.

More Repositories

1

laravel-acl

This package helps you to associate users with permissions and permission groups with laravel framework
PHP
561
star
2

laravel-kafka

Use Kafka Producers and Consumers in your laravel app with ease!
PHP
441
star
3

trackable-jobs-for-laravel

This package allows you to easily track your laravel jobs!
PHP
253
star
4

laravel-pix

Uma solucão simples para integrar sua aplicação Laravel a API PIX do Banco Central do Brasil
PHP
96
star
5

laravel-time-helpers

This package provides two simple functions to get future and past times.
PHP
38
star
6

laravel-2fa

This package provides a simple two factor authentication for laravel applications.
PHP
35
star
7

accel-stepper-with-distances

This library allows you work with the popular AccelStepper not with steps, but distances!
C++
18
star
8

laravel-kafka-example

An example on how to use laravel kafka package.
PHP
7
star
9

ignition-stackoverflow-portuguese

A Laravel Ignition tab that fetches StackOverflow PT-BR questions and provides a searchbar.
PHP
6
star
10

dotfiles

My personal dotfiles - making anywhere feel like home
Shell
5
star
11

mips-vhdl-processor

Implementação do processador MIPS usando VHDL
VHDL
3
star
12

udp-client-server

A simple client-server application using UDP.
C
2
star
13

multimodal-emotion-recognition-system

The source code for my course completion work (A multimodal emotion recognition system) 🎓
Jupyter Notebook
1
star
14

batch-mailer-for-laravel

A batch mailer implementation for laravel with built-in failover transport
PHP
1
star
15

calculo-numerico

Repositório com alguns métodos de cálculo que implementei durante as aulas de cálculo numérico de 2017
Scilab
1
star
16

junges.dev

The source code of my personal website
PHP
1
star
17

modelagem-software-2018

Repositório com soluções de exercícios de Modelagem de Software, do curso de engenharia de computação da UEPG, 2018
1
star
18

huac

Repositório para a disciplina de projeto de software, do curso de Engenharia de Computação na Universidade Estadual de Ponta Grossa
PHP
1
star
19

sistemas-operacionais-2018

Repositório com exercícios das aulas de SO-2018
C
1
star
20

estrutura-de-dados

Repositório com algoritmos de estruturas de dados
C++
1
star
21

tcc-flask-app

Flask app to predict emotions in videos using a multimodal approach
CSS
1
star
22

bresenham-demo

Java application to demonstrate the operation of the bresenham algorithm, to draw a line between two points
Java
1
star
23

php-json-builder

A simple utility class to manipulate JSON objects.
PHP
1
star
24

laravel-postmark-api

Postmark API Client for Laravel Apps
PHP
1
star
25

projeto-final-sistemas-embarcados

Projeto final da disciplina de Sistemas embarcados, do curso de Engenharia de Computação, na Universidade Estadual de Ponta Grossa - UEPG
JavaScript
1
star
26

laravel-signos

PHP
1
star
27

computacao-grafica

Repositório com o conteúdo das aulas de Computação gráfica do curso de Engenharia de Computação - UEPG
Java
1
star
28

sistemas-embarcados-2018

Repositório com o conteúdo das aulas de Sistemas Embarcados, do curso de Engenharia de Computação da Universidade Estadual de Ponta Grossa
C++
1
star