How to Add relation to default User Class in laravel? - 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?

Related

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 one to many relationship fetch data

i make a one to many relationship in my project but when i want to fetch data it returns null response.
i have a user Model and Intership Model.
each user has one Intership and each Intership has many users. so , relationship is one to many .
i create this relation but i cant fetch data. i want to show intership information of a user.
MY 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;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'last_name',
'email',
'role',
'phone',
'user_code',
'born_date',
'national_code',
'password',
];
protected $primaryKey = 'user_code';
protected $table = 'users';
/**
* 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',
];
public function intership()
{
return $this->belongsTo(Intership::class,'intership_code','intership_code');
}
}
MY INTERSHIP MODEL :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Intership extends Model
{
use HasFactory;
protected $table = 'interships';
protected $primaryKey = 'intership_code';
protected $fillable = [
'teacher_code',
'user_code',
'school_code',
'work_code',
'intership_term_code',
'intership_code',
'class_code',
'start',
'end',
];
public function users()
{
$this->hasMany(User::class,'user_code','user_code');
}
}
MY CONTROLLER :
public function index()
{
$user = User::where('user_code',32132)->first();
$interships = $user->intership;
return $interships;
}
Notes :
1- i dont have "id" field in my tables so instead of "id" i have user_code for users and intership_code for interships that are foreignkey
2- user with user_code => 32132 already exists.
3- i want to show a user intership information
Ok so first things first, since you use your User model the relationship that you want to build is in the User model, the one in Internship model is irrelevant (at least for this question).
public function intership()
{
return $this->belongsTo(Intership::class,'user_code','user_code');
}
Your foreign key in your Internships table that connects it with the Users table is the user_code which links to the user_code of the user in Users table.

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'])
];
}
}

Why I'm getting a null value when querying a model in eloquent?

I have a problem where I'm getting a null value when querying a model in eloquent, I have a two models User.php and Project.php, When I use tinker and use User.php to check if the data has a relation to Project.php model I got what I want, but when I use the Project.php to check if it has a relation to User.php I'm getting a null value.
This is my code for Project.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public $table = "project";
protected $guarded = [];
public function owner(){
return $this->belongsTo(User::class);
}
}
And this is my code for 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;
public function projects(){
return $this->hasMany(Project::class);
}
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is my result in Tinker:
This is the result when I use tinker and query, as you can see my User.php has a relation to Project.php, But when I use Project.php I'm getting null value.
Have you tried with:
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
Because (quote from the docs):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column.
You should use eager loading to load parent relationship like this :
Project::with('owner')->first()->owner
And confirm that the foreign keys is correct

Returning null Value for User from Model

I'm getting a null value for the user at http://localhost:8000/messages. I am trying to get the user table values within the Message model. It also gives a null value in the console.
Route
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
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 messages()
{
return $this-> hasMany(Message::class);
}
}
Snapshot
messages table must have user_id with proper user ID to make belongsTo relationship work.
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

Resources