eloquent relationship belongsTo('Spatie\Permission\Models\Role', 'id', 'id') not working - laravel

so i was following this tutorial [laravel 8 crud tutorial]1
and i wanted the create,edit,delete,show to be modal. i manage to make it work on show,delete and create but my edit is not working.
user.php (model)
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function userRole()
{
return $this->belongsTo('Spatie\Permission\Models\Role', 'id', 'id');
}
}
Edit modal
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>{{ __('Role') }}:</strong>
{!! Form::select('roles[]', $roles,$user->userRole->name, array('class' => 'form-control','multiple')) !!}
</div>
</div>
if i remove the name in $user->userRole i get no error, but when i put a name in$user->userRole->name i get an error
Trying to get property 'name' of non-object (View: C:\Apache24\htdocs\BDProject_v1\resources\views\Users\modal\edit.blade.php)

Well, that means you are trying to get the property of a non-object. Please dump the value and check if it is an object or an array.
var_dump($user->userRole);

Related

Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php)

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

How to resolve mass assignment error in laravel?

I am new to the laravel, i am implementing user registration api while registering the user it's throwing an error like mass_assignment
Add [first_name] to fillable property to allow mass assignment on [App\\Entities\\User].
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table ='user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name','phone_number','email'
];
protected $guarded =[];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
UserController.php
public function userRegister(userRequest $request){
$data = $this->repository->create($request->all());
return $user = new UserTransformer($data);
}
}
please help why this error is happening ..?
The main problem is laravel5.8 the model paths are different so use following facade
use App\modelname
instead of use App\Entities\User,let me know if this resolves your problem :-)

laravel Auth::attempt() always returning false

I'm making a simple user authentication with laravel passport, I made an AuthController where I put login and register functions, whenever I try to login with the right email and password I get
{"message":"invalid user"}
its like the attempt() method always returning false, I am using laravel 8.
here is AuthController.php
<?php
namespace App\Http\Controllers;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request){
if(Auth::attempt($request->only('email', 'password'))){
$user=Auth::user();
return $user;
}
return response([
'message'=> 'invalid user'
], 401);
}
}
user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'phone',
'skype',
'birthdate',
'address',
'postalcode',
'city',
'country',
'status',
'image',
'description',
'geo_lat',
'geo_lng'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}

How to include a JSON column property in Laravel API Resource

I have a model which is illustrated below which I am struggling to access a very trivial property.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class Vendor extends Authenticatable
{
use Notifiable, HasApiTokens, SoftDeletes;
protected $guard = 'vendor';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'slug','images'
];
//images is a json column
protected $casts = [
'images' => 'array'
];
}
Within my model I now have a property which is
public function coverImage()
{
return \Storage::disk('s3')->url( $this->images['cover']);
}
I am basically trying to retrieve a property within my JSON column but whenever I try to access it in my API resource, it throws the error:
ErrorException: Trying to access array offset on value of type null in file C:\...\Models\Vendor.php on line 63
Is there something that I am missing?
I had a lightbulb moment, all I needed to do was to expose it in my VendorResource as thus
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class VendorResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'email' => $this->email,
'coverImage'=> \Storage::disk('s3')->url( $this->images['cover'])
];
}
}

How to Add relation to default User Class in laravel?

I'm new to Laravel.
I have many to many relationship with user and movie and hence created an movie_user pivot table:
I am using the Laravel 6.5.2 default authentication; in App/User.php .
The default User.php class is as follows:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Modules\Movie\Entities\Movie;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','profile_pic_url',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I want to add a following relationship for movie in user class
public function movies()
{
return $this->belongsToMany(Movie::class);
}
But to do this I think i need to extend Model class and not Authenticatable class;
so the problem is how can I insert the relation inside the 'class User extends Authenticatable'
is there any method like dependency injection to achieve this solution?, and if yes in which is the best way to do this?

Resources