Invalid argument supplied for foreach()

Posted 3 years ago by anikkhan

Hey i try to following the ACL in Laravel: Roles and Permissions Video

I did everything whatever jeff_way did but i am getting this error

Invalid argument supplied for foreach() (View: /Applications/MAMP/htdocs/webapp/resources/views/genres/create.blade.php)

Create.blade.php

@extends('layout.app')
@section('title', 'Add Genre')

@section('content')

    @can('add_genre')
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-login">
                <div class="panel-heading">
                    <div class="row">
                        <h1>Create Genre</h1>
                    </div>
                    <hr>
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-12">
                            @if (count($errors) > 0)
                                <div class="alert alert-danger">
                                    <button type="button" class="close"><span>×</span></button>
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif
                            <form id="login-form" action="/genre" method="post" role="form" style="display: block;">
                                {{ csrf_field() }}
                                <div class="form-group">
                                    <div class="input-group margin-bottom-sm">
                                        <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
                                        <input type="text" name="name" id="name" tabindex="1" class="form-control" placeholder="Genre Name" value="{{ old('name') }}">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="input-group margin-bottom-sm">
                                        <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
                                        <input type="text" name="slug" id="slug" tabindex="1" class="form-control" placeholder="Genre Slug" value="{{ old('slug') }}">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-sm-6 col-sm-offset-3">
                                            <input type="submit" id="submit" tabindex="4" class="form-control btn btn-login" value="Create">
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @else
        <h2 class="alert alert-danger">You don't have permisstion</h2>
    @endcan

@stop

AuthServiceProvider.php

<?php

namespace App\Providers;

use App\User;
use App\Permission;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);

        foreach ($this->getPermissions() as $permission){

            $gate->define($permission->name, function ($user) use ($permission){
               return $user->hasRole($permission->roles);
            });
        }
    }

//    protected function getPermission(){
//
//        return Permission::with('roles')->get();
//    }


     protected function getPermissions(){
         try{
             return Permission::with('roles')->get();
         } catch (\Exception $e){
             return [];
         }
     }
}

User.php

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'first_name', 'last_name', 'avatar', 'description', 'twitter', 'facebook'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function roles(){

        return $this->belongsToMany(Role::class);
    }

    public function assignRole($role){

        return $this->roles()->sync(Role::whereName($role)->firstOrFail());
    }

    public function hasRole($role){

        if (is_string($role)){
            return $this->roles()->contains('name', $role);
        }

        return !! $role->intersect($this->roles()->count());

//      foreach ($role as $r){
//          if ($this->hasRole($r->name)){
//              return true;
//          }
//      }
    }
}

permission.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    protected $table = "permissions";

    public function roles(){
        return $this->belongsToMany(Role::class);
    }
}

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function permissions(){

        return $this->belongsToMany(Permission::class);
    }

    public function givePermissionTo(Permission $permission){

        return $this->permissions()->save($permission);
    }
}

Please can anybody help me Thank you

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.