Mohamed Benhida

admin@devma.net

December 8, 2017

Bind Service Container Laravel

Hey,

In this post we will talk about Bind in Service Container.

We begin by making a simple example just to understand how it works (is not a real world example).

We have an user with column admin now we will check in UserController.php if this authenticate user is an admin.

First of all we gonna need to create an Admin class on app/Services/Admin.php

<?php

namespace App\Services;
use App\User;

class Admin
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function isAdmin() {
        return $this->user->admin == 4;
    }
}

Now We will come to our AppServiceProvider.php (is a file that reload each time at first of your project).

$this->app->bind(ClassName::class,Closure);

AppServiceProvider

<?php

namespace App\Providers;

use App\Services\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $auth = \App\User::find(1);

        $this->app->bind(Admin::class,function() use($auth) {
            return new Admin($auth);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

We come to our UserController.

UserController.php

<?php

namespace App\Http\Controllers;

use App\Services\Admin;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public $admin;

    public function __construct(Admin $admin)
    {
        $this->admin = 0;

        if($admin->isAdmin()) {
            $this->admin = 1;
        }
    }

    public function index()
    {
        return $this->admin;
    }
}

Web/routes.php

Route::get('/',[
    'uses' => 'UserController@index'
]);

Now if we visit the link we will get if the authenticate user is really an admin or not so that how it work bind on laravel you pass the construct parametre once in your project in AppServiceProvider.php

 

 

© Mohamed Benhida.

Blog | Packages | About