Monday, May 22, 2017

laravel dependencies do not work correctly

Help to understand, there is an ordinary model User, with the key role_id:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;

class User extends Authenticatable
{
    use Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function role()
    {
        return $this->hasOne('App\Role', 'id');
    }

    public function isManager()
    {
        return Auth::user()->role->name == 'manager';
    }

    public function isAdmin()
    {
        return Auth::user()->role->name == 'admin';
    }
}

And Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'name'
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }
}

migration for users table:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')
            ->unique();
        $table->string('password');
        $table->rememberToken();
        $table->integer('role_id')
            ->unsigned();
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade');
    });
}

Now the crux of the problem. When I try to get all the managers, only the first one displays the role. Controller:

public function managersView()
{
    $role = Role::where('name', 'manager')->first();
    $managers = Role::find($role->id)->users;
    return view('users.managers', [
        'managers' => $managers
    ]);
}

View:

@foreach ($managers as $manager)
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td>
            <button class="btn btn-success"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button>
            <button class="btn btn-warning"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
        </td>
    </tr>
@endforeach

The table displays only the role for the first user. Help please understand what is not true?



via Oleg Shleif

Advertisement