smzapp
smzapp

Reputation: 839

Why does a property attribute returns empty using a model?

I have a controller and a model.

Now, I wanted to get the property of a model from the controller, but I can not access it. Here is my code:

MODEL

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use Notifiable;

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

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

    public function isRole()
    {
        return $this->role; //mysql column role
    }
}

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{ 
    public function index()
    {
        $user = new User;
        return $user->isRole(); //this is just to test display the role column. but it returns empty or no value.
    }
}

I also tried to echo $this->role inside the function isRole(), but again it is empty. In my database, I have values inserted on role column.

I also executed the php artisan migrate in order to update the data.

Somebody help me: what's going on here? thanks

Upvotes: 1

Views: 79

Answers (2)

rocambille
rocambille

Reputation: 15996

In your code:

$user = new User;
return $user->isRole();

You're creating a User out of nothing, so the role will be garbage. Try the following to get the first user of your table:

$user = User::firstOrFail();
return $user->isRole();

Note that if the table is empty, firstOrFail will throw an exception.

EDIT:

As stated in shukshin.ivan's comment, users can also be filtered using a where clause like the following:

$user = User::where('email', $request->email)->first();
return $user->isRole();

Upvotes: 3

Try

public function index()
    {
        $user = App\User::find(1);

        return $user->isRole();
    }

you get empty value because new User(); is empty

Upvotes: 1

Related Questions