Laravel: Trying to get relationship - php

User:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function email_preferences()
{
return $this->hasOne('EmailPreference');
}
}
EmailPreference:
class EmailPreference extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'email_preferences';
public function user()
{
return $this->belongsTo('User');
}
}
users table
id PK
first_name
last_name
email
email_preferences table
id PK
user_id FK (users.id)
newsletter
I'm trying to display the email preferences for a user:
$user = Auth::user();
echo '<pre>';
print_r($user->email_preferences);
exit;
I get nothing...

It sounds like you want something like this:
<?php
$user = Auth::user();
echo 'Receive newsletter? ' . ($user->emailPreferences->newsletter ? 'Yes' : 'No');
EDIT:
I did some digging & found that underscores can be tricky when used in Eloquent function/property names. If you eliminate the underscore, things should just work:
<?php
class User extends Eloquent implements UserInterface, RemindableInterface {
public function emailPreferences()
{
return $this->hasOne('EmailPreference');
}
}
See this answer: Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties

Related

Laravel 8 belongsTo relationship not returning data on User model

I'm building a Laravel 8 API and want to automatically join user_settings onto a user whenever the User model is queried.
My thinking is that I can achieve this with the belongsTo relationship since user_settings "belongs" to a user.
However, when I attach this to my UserSetting model and query a user I'm not seeing any user settings attached to my User despite having data in the user_settings table.
Where am I going wrong?
Model: User
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserSetting extends Model
{
use HasFactory, SoftDeletes;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'user_settings';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id',
'theme',
'refreshButtonPlacement',
'animationSpeed',
'fetchTimeout'
];
/**
* Get the user that owns the comment.
*/
public function user()
{
return $this->belongsTo(UserSetting::class);
}
}
Model: User
<?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 Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'last_login_at' => 'datetime'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
I also tried using a One To One relationship and defined a settings method on my User model but in Tinker when I ran User::findOrFail(1)->settings; I had nothing either.
Relationship setup:
class User extends Model
{
//some custom stuff
/**
* Get the phone associated with the user.
*/
public function user_setting()
{
return $this->hasOne(UserSetting::class);
}
}
class UserSetting extends Model
{
//some custom things
/**
* Get the user that owns the comment.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Afterwards you can use eager laoding by default, in your case you will have to add $with = ['user_setting'] to your User class.
You could also use the ->with() method, for that you will have to use either:
User::with('user_setting')->find(Auth::id());
//or
Auth::user()->with('organisation')->first()
Laravel doesn't load the relationship values in every call because of the obvious overhead. So you will either define the relationship to be loaded by default or you will have to work with the ->with() method for eager loading the relationship.
Add this method to your User model
And you can access the user settings through a dynamic attribute $user-> user_setting
on each User model instance
For more informations
https://laravel.com/docs/8.x/eloquent-relationships#one-to-one
public function user_setting(){
return $this->hasOne(UserSetting::class);
}

How to make HasMany Relation ship in Laravel 4.2

I have a user model looks like this
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function answer(){
return $this->hasMany('Answer','user_id');
}
public function supplierranking(){
return $this->hasMany('Supplierrank','userid','id');
}
}
Now each user will rank a company in a ranking Model which looks like this
Class Supplierrank extends Eloquent{
public function supplier(){
return $this->belongsTo('Supplier','supplierid','id');
}
public function user(){
return $this->belongsTo('User','userid','id');
}
}
I am able to get the user with the ranking details but I also have to get the details of companies that has been ranked from a Supplier table
which looks like this
Class Supplier extends Eloquent{
public function supplierranks(){
return $this->hasMany('Supplierrank','supplierid');
}
}
My query that I have done looks like this
$usersandranking = User::where('event','=',$exceleve)->with('supplierranking')->orderBy('id')->get();
It gets me user detail and there rankings but not the supplier names
Can any one help me on this

Laravel 5 setup model event to "clear up" pivot tables on model delete

I am using Laravel 5 to build a user based application. Some models have a manyToMany relationship in my app and therefore I am using pivot tables.
When I delete a user from the system, I use this simple function:
/**
* Delete user.
*
* #param $id
* #return mixed
*/
public function deleteUser($id)
{
return $this->user->whereId($id)->delete();
}
However, when the user is deleted, the rows in the pivot tables (for example role_user) do not get deleted.
I have read on the laravel site that I can use model events to "clear up" my pivot tables, but i'm really unsure how I would implement that.
Can anyone point me in the right direction?
Edit
Below is my current model setup:
namespace App\Models\User;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Scopes\MultiTenantTrait;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword, MultiTenantTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['cust_id', 'first_name', 'last_name', 'email', 'status', 'activation_code'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Boot the model.
*
*/
public static function boot()
{
parent::boot();
static::deleting(function($user)
{
$user->roles()->delete();
$user->supervisors()->delete();
$user->types()->delete();
$user->rates()->delete();
$user->miscs()->delete();
});
}
...
You can add a boot method to your models, like the following:
public static function boot() {
parent::boot();
// This is a deleting event on the model
static::deleting(function($model) {
$model->... //Here your model is still available
// You could add something like this
DB::table('role_user')->where('user_id', $model->id)->delete();
})
}
But you can also extend the delete method in your models:
public function delete() {
DB::table('role_user')->where('user_id', $this->id)->delete();
parent::delete();
}

Make a variable with array of data from Laravel ManyToMany relationship

Im struggling to understand Laravels relationship usage. I finally managed to save the relationships between person and festival, using the model and this code:
$person = new Person;
$person->firstname = $firstname;
$person->lastname = $lastname;
$person->save();
$person_id = $person->id;
$person->festival()->attach($festival_id);
But I am not sure how to make a variable with all the persons of the festival im current working on. I store the value of festival_id in session:
$festival_id = Session::get('festival');
That is writing fine to my personFestival database.
id festival_id person_id
0 1 1
1 1 2
But i dont have any code in my PersonFestival-model, should I?
How can I retrieve all the persons of the festival with id=1 in a variable that I can use blade's foreach in a view on? Sorry about this mess, this is so confusing for me but i feel that im close to achieving it.
Tables:
persons (id, firstname, lastname)
festivals (id,name)
personFestival (id, person_id, festival_id)
Models:
class Festival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'name','year','info','slug', 'image','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_festivals';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function bands() {
return $this->hasMany('Band');
}
public function persons() {
return $this->belongsToMany('Person','fs_festival_persons','person_id','festival_id');
}
}
class Person extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'email','firstname','lastname','homepage', 'info','tlf','isonline','isbanned','username','password','password_temp','remember_token','code','active','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_persons';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function festival() {
return $this->belongsToMany('PersonFestival','fs_festival_persons','person_id', 'festival_id');
}
}
class PersonFestival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'person_id','festival_id'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_festival_persons';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Pivot tables (your fs_festival_persons table) don't usually have a model associated with them, unless you really need some special logic for them. In this case, it doesn't look like you do, so you can probably just get rid of that model.
To answer your other question, all of the persons associated with a festival can be accessed through the relationship on your festival model:
$festival = Festival::find(1);
// Collection of Person objects via lazy loading
$persons = $festival->persons;
// Relationship object:
$relation = $festival->persons();
// Manually getting the Persons through the relationship:
$persons = $festival->persons()->get();
// You can iterate the Collection just like an array:
foreach ($persons as $person) {
var_export($person->name);
}
You can read more on querying relationships here: Laravel 4.2 / Laravel 5.0

Laravel Fetching error from database Eloquent ORM

I am developing a Simple CRUD Application,
I want to fetch my forms details from my forms table.
my controller look like below,
public function manage_forms()
{
$form_data=Form::all();
return View::make('manage_forms')->with('form_array',$form_data);
}
the routes.php,
Route::get('manage-forms',array('as'=>'manage_forms','uses'=>'Nri#manage_forms'));
the View file,
<title>Registered Form details</title>
<h2>Registered Form details</h2>
<ul>
#foreach($form_array as $form_view)
<li>{{$form_view->name}}</li>
#endforeach
</ul>
My Forms model (Form.php),
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Form extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'forms';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
I am getting error like
BadMethodCallException
Method all does not exist.
You have to change your class name from Form to something else, as Form:: is already in use by laravel itself and you can't use the same class more than once
Remember to run php artisan dump-autoload after changing
Here:
class Formdata extends Eloquent implements UserInterface, RemindableInterface {
// ^this needs to be changed
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'forms';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
and this:
public function manage_forms()
{
$form_data=Formdata::all();
^ and this
return View::make('manage_forms')->with('form_array',$form_data);
}

Categories