I'm begginer in Laravel. I have this code:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
public static $roles = [];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function comments()
{
return $this->hasMany('App\Comments');
}
public function hasRole(array $roles)
{
foreach($roles as $role)
{
if(isset(self::$roles[$role]))
{
if(self::$roles[$role]) return true;
}
else
{
self::$roles[$role] = $this->roles()->where('name', $role)->exists();
if(self::$roles[$role]) return true;
}
}
return false;
}
}
class Role extends Model
{
protected $quarded = [];
public $timestamps = false;
public function users()
{
return $this->belongsToMany('App\User');
}
}
and schema:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->boolean('enable')->default(0);
$table->string('name', 120)->nullable();
$table->string('surname', 120)->nullable();
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('counter')->default(0);
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
});
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->engine = "InnoDB";
});
Schema::create('role_user', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->bigInteger('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->engine = "InnoDB";
});
And my user:
DB::table('users')->insert([
'name' => 'Marian',
'surname' => 'La',
'email' => 'marian@icloud.com',
'email_verified_at' => \Carbon\Carbon::now(),
'password' => Hash::make('passw'),
]);
DB::table('role_user')->insert([
'user_id' => 1,
'role_id' => 1,
]);
This code work fine. I have problem with my role. How can i print user role in blade?
I make this code:
public function getAdmin(int $id)
{
return User::find($id);
}
$admin = $this->getAdmin(1);
And now my $admin - has admin object.
When i print in blade file: $admin->name, $admin->surname - it's work.
When i print:
i have result:
[{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]
How can I show correct value (admin):
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2W38eNC
via IFTTT
Aucun commentaire:
Enregistrer un commentaire