Laravel adding details of two different user into there respected table - laravel

I want to store details as per user who is login and there ROLE that is whether they are teacher or student in respected table
In my Controller
public function store(Request $request)
{
$input = Request::all();
$this->validate($request,[
'user_id'=>'required',
'city'=>'required',
]);
if (User::find($role,'teacher')){
Teacher::create($input);
}
else{
Student::create($input);
}
return redirect ('home');
}
Now my Model for users
protected $fillable = [
'name', 'email', 'password','role'
];
protected $hidden = [
'password', 'remember_token',
];
public function details()
{
return $this->hasOne(['App\Teacher','App\Student']);
}
teachers model
protected $fillable = [
'user_id', 'city',
];
public function user()
{
return $this->belongsTo('App\User');
}
now students model
protected $fillable = [
'user_id', 'city',
];
public function user()
{
return $this->belongsTo('App\User');
}

Related

redirecting to error page on failed send password notification

use AuthenticableTrait, Notifiable, CanResetPassword, HasRoles, TwoFactorAuthentication,SendsPasswordResetEmails;
protected $fillable = ['auth_method', 'first_name', 'last_name', 'email', 'password', 'contact_number_country_code', 'contact_number', 'is_admin', 'is_sso_auth', 'status', 'last_login', 'require_mfa'];
protected $appends = ['full_name', 'avatar'];
public function sendPasswordResetNotification($token)
{
// try {
$this->notify(new AdminResetPasswordNotification($token));
// }
// catch(\Exception $e){
// return view('admin');
// }
}
public function verifyUser()
{
return $this->hasOne(VerifyUser::class, 'user_id');
}

Laravel resource: Get some of relations

There is a model User and a model Payments. I need to create a resource such that returns user with successful payment which is identified by a status fields. This is my solutions:
class User extends BaseModel
{
use HasFactory, SearchableTrait, SortableTrait;
protected $fillable = ['name', 'mobile', 'email', 'username', 'hash_id'];
public $searchable = ['name', 'mobile', 'email', 'id', 'user:referred'];
public $sortable = ['name', 'mobile', 'email', 'id'];
protected $table = 'users';
public function invoices()
{
return $this->hasMany(Invoice::class,'user_id');
}
}
and in controller
public function index()
{
$users = new User();
$users = $users::with(['invoices'])->filtered()->sorted();
return UserResource::collection($users->paginate());
}
and
<?php
namespace Modules\User\Transformers;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'mobile' => $this->mobile,
'invoices' => count($this->invoices()->where('status', 2999)->get()),
];
}
}
and model
class Invoice extends Model
{
protected $fillable = [];
protected $table = 'payment_invoices';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function scopeSuccessful($query)
{
return $query->where('status', 2999);
}
}
It seems to be messy solution. I am looking for something to use the scope inside the model relation inside the resource. How can I do that?
in your controller you can just do this :
use Illuminate\Database\Eloquent\Builder;
public function index()
{
$users = User::with(['invoices'])->whereHas('invoices', function(Builder $query) {
$query->where('status', 2999);
});
return UserResource::collection($users->paginate());
}
<?php
class User extends BaseModel
{
use HasFactory, SearchableTrait, SortableTrait;
protected $fillable = ['name', 'mobile', 'email', 'username', 'hash_id'];
public $searchable = ['name', 'mobile', 'email', 'id', 'user:referred'];
public $sortable = ['name', 'mobile', 'email', 'id'];
protected $appends = ['success_payments']; // append this value in all queries
protected $table = 'users';
public function invoices()
{
return $this->hasMany(Invoice::class,'user_id');
}
//the function for it
public function getSuccessPaymentsAttribute(){
return App\Payment::where('user_id', $this->id)->where('status', 'success')->get(); //replace the attribute name or condition as per your db structure
}
}
You can use this in your User Model.

Get user without email column

I have a database from which I fetch comments and data about the author.
I use axios to download asynchronous comments together with the author of the comment.
User.php
public function comments() {
return $this->hasMany('App\Comment');
}
Comment.php
public function author()
{
return $this->belongsTo('App\User', 'user_id');
}
CommentController.php
public function fetch(Request $request)
{
$comments = Comment::with('author')
->orderByDesc('id')
->get();
return response($comments, 200);
}
I would like to fetch only comment.author.name and comment.author.avatar . Is there any other way than hiding fields? I think that I will need the other fields in other methods.
User.php
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'email', 'password', 'remember_token',
];
you can specify wich columns you have selected on eager loading like this :
Comment::with(['author'=>function($query){
$query->select('name','avatar');
}])->get();
or simply :
Comment::with('author:name,avatar')->get()

Return model relation / pivot in a method after creation in Laravel Eloquent

How can I return the model with his relation / pivot in a method after a firstOrNew?
Model:
class Customer extends Model
{
protected $table = 'customers';
protected $primaryKey = 'customer_id';
public $timestamps = true;
protected $fillable = [
'email',
'first_name',
'last_name',
'address',
'city',
'county',
'country',
'phone',
'organization_id',
'unique_value'
];
protected $guarded = [];
public function locations()
{
return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}
}
Method:
$customer = Customer::firstOrNew(['unique_value' => $unique_code]);
Do some logic...
and
return $customer;
How can I return the $customer with locations()?? I will do a firstOrNew for locations too.
Use protected $appends = ['locations']; in your Model.
protected $primaryKey = 'customer_id';
public $timestamps = true;
protected $appends = ['locations'];
protected $fillable = [
'email',
'first_name',
'last_name',
'address',
'city',
'county',
'country',
'phone',
'organization_id',
'unique_value'
];
protected $guarded = [];
public function locations()
{
return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}
Or you use return $cusotmer->load(['locations'])

Laravel eloquent add extra models to hasMany

I have a user Model and each user has multiple licenses. There are 2 default licenses that apply to all users that are not in the licenses table and they need to be created on the fly using certain data contained in the User model.
How can I create 2 licenses each time I'm getting a user's licenses and add it to the output of licenses()?
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
public $timestamps = false;
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function licenses()
{
return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
}
}
You could create an extra function in the model where you call the licenses and add the extra licenses.
Remember to test all places where you use this function so no strange stuff will happen.
<?php
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'users';
public $timestamps = false;
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
// HasMany function
public function _licenses()
{
return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
}
// New licenses function
public function licenses()
{
// Get licenses from database
$licenses = $this->_licenses;
// Add other lisences
$licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "foo" ]));
$licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "bar" ]));
// Return the new collection
return $licenses
}
}

Resources