This is the first time i am trying to use eloquent relationship.I have a userModel and a phoneModel class.They represents users and phone table respectively. Here i am trying to access The phone number of a user when he/she logged in.
users table has the field (id,name,password) and phone table has the
(field id,phone_no,user_id)
phone migration is below:
public function up()
{
//
Schema::create('phone',function(Blueprint $table){
$table->increments('id');
$table->string('phone_no',20);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
i applied hasOne and belongs to relationship on both models:
userModel.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class userModel extends Model implements Authenticatable
{
//
use \Illuminate\Auth\Authenticatable;
protected $table = 'users';
public function phone(){
$this->hasOne('App\Models\phone');
}
}
phoneModel.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class phoneModel extends Model
{
//
protected $table='phone';
public function user()
{
return $this->belongsTo('users');
}
}
Now when i tried to get a phone number from logged user i get an error called class 'phone' not found
Here is the code inside show method of userController:
public function show($user)
{
//
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if($info){
$phone = userModel::find($info->id)->phone;
$data=array('info'=>$info,'phone'=>$phone);
return View::make('user.show')->with($data);
}else{
$info=userModel::where($indicator,'=', Auth::user()->name)->get()->first();
return View::make('user.show')->with('user',$info);
}
}
You named your phone class phoneModel but you added the relationship as $this->hasOne('App\Models\phone');. You also created those classes in the App namespace but referenced them as App\Models\class.
The standard practice is to name your model classes after the model and using uppercase letters. So your classes would be called User and Phone rather than userModel and phoneModel. And the database tables would be users and phones. If you use these standards, Laravel will take care of a lot of things automatically behind the scenes.
User class
namespace App;
class User extends Model implements Authenticatable
{
//
use \Illuminate\Auth\Authenticatable;
//Laravel will assume the User model is in the table `users` so you don't need to specify
public function phone(){
$this->hasOne('App\Phone');
}
Phone Class
namespace App;
class Phone extends Model
{
//Laravel will assume the Phone model is in the table `phones` so you don't need to specify
public function user()
{
return $this->belongsTo('App\User');
}
Related
This is my Vote model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vote extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function options(){
return $this->hasMany('App\Option');
}
}
this is my Option model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Option extends Model
{
public function vote(){
return $this->belongsTo('App\Vote');
}
public function users(){
return $this->belongsToMany('App\User');
}
}
The case is i want to get the users data from many to many relationship in Option model, but started from Vote model. So i get the options data in the Vote model first, then i get the users data in Option model (many to many)
Laravel has no native support for a direct relationship.
I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep
class Vote extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function users()
{
return $this->hasManyDeep(User::class, [Option::class, 'option_user']);
}
}
I am pretty new in Laravel and need write a simple backend API.
I am doing smething wrong and I dont know what, because I get some of data from Suppliers table and empty array payments:[ ].
I am trying to get all data from two related tables - PAYMENTS and SUPPLIERS.
It`s a one to many relation SUPPLIERS_ID in PAYMENTS table is connected with ID in SUPPLIERS. Here I give You a graphic representation:
Here`s my code:
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->hasOne('App\Suppliers');
}
}
PaymentsController.php
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PaymentsController extends Controller
{
public function index()
{
$payments = Suppliers::with('payments')->get();
return response($payments, Response::HTTP_OK);
}
}
And i get the following answear:
[{"id":1,"name":"Ekonaft","adress":"33-100 Tarnow ","email":"ekonaft#gmail.com","payments":[]},
{"id":2,"name":"Orlen","adress":"Ares testowy","email":"email#email.pl","payments":[]}]
What I`m doing wrong that I get te empty array payments:[ ] on the end of each object?
Try the inverse relationship on payments
belongsTo = has a foreign key to another table
Quoting an example
Should i use belongsTo or hasOne in Laravel?
This is how you can access suppliers from Payments
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo('App\Suppliers');
}
}
This is payments from suppliers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments','suppliers_ID','id');
}
}
Also, make sure the id's are visible on the output (if id's are hidden, laravel can't work with the relationship). You can also specify the keys on the relationship if you want to use hasOne
Edit: add the keys names within the relation, your fk naming is in capslock
Change you relations like bel
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany(App\Payments::class, 'suppliers_ID', 'id');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo(App\Suppliers::class, 'suppliers_ID', 'id');
}
}
then try again..... :)
You are getting empty array of payments:[] due to miss-matching table relationship key name.
Please, make few changes in both relational function.
public function payments()
{
//return $this->hasMany('App\Model', 'foreign_key', 'local_key');
return $this->hasMany('App\Payments', 'suppliers_id');
}
public function suppliers()
{
//return $this->belongsTo('App\Model', 'foreign_key', 'other_key');
return $this->belongsTo('App\Suppliers', 'suppliers_id');
}
You can learn more about eloquent relationship directly from Laravel documentation for better understanding. https://laravel.com/docs/5.7/eloquent-relationships#one-to-many
Let me know if you still getting same error.
I have a set of relationships that looks like this:
The users and agencies have a lot of data stored in them, in addition to the pivot tables you see there.
What I'd like to do is find the agencies or users that match the preferences of the currently logged in individual, whether they are an agency or user.
It's a straight comparison, so nothing fancy. But I honestly have no idea how to write the eloquent query to account for the pivot tables. Can someone point me in the right direction?
I'm looking at something like this, which is understandably failing:
$loggedinagency = Auth::user()->id;
$match_user_agency = User::with('work_prefs')
->where('work_prefs', 'like',
Agency::find($loggedinagency)->work_prefs)
->get();
Edit: The relationships are declared like so:
User:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $table = 'users';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'preference_user', 'user_id', 'preference_id');
}
}
Agency:
<?php
namespace App;
class Agency extends Authenticatable
{
use Notifiable;
protected $table='agencies';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'agency_preference', 'agency_id', 'preference_id');
}
}
Work Preferences:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Work_Prefs extends Model
{
protected $table = 'work_prefs';
public function user() {
return $this->belongsToMany('App\User', 'preference_user', 'preference_id', 'user_id');
}
public function agency() {
return $this->belongsToMany('App\Agency', 'agency_preference', 'preference_id', 'agency_id');
}
}
My authenticated user has a color assigned to them via a relationship in the User model.
I would like to go:
return Auth::color()->id;
To return the logged in users color id.
How do I go about doing this?
I also can't do:
Auth::user()->color()->id
or
Auth::user()->color->id
I am getting Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$id
However all relationships are defined.
I am coming from Laravel 4, what am I doing wrong?
<?php
namespace App\Models;
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;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function color() {
return $this->hasOne('\App\Models\Colour');
}
public function salesarea() {
return $this->belongsTo('\App\Models\Salesarea');
}
public function getNameAttribute() {
return $this->first_name." ".$this->last_name;
}
}
Seeing i cant create a comment yet i'll write my question here,
Is this suposed to be a one to many or one to one ?
Is the user_id column present in your color database table ?
if it is a one to many you need to check if:
your user model has this function
public function colors()
{
return $this->hasMany('App\Color');
}
your Color model has this function
public function user()
{
return $this->belongsTo('App\User');
}
If so you should be able to do
Auth::user()->colors witch is a collection of color objects
if it is supposed to be a one to one
you need to check if your user model has this function
public function color()
{
return $this->hasOne('App\Color');
}
your color model has this function
public function user()
{
return $this->belongsTo('App\User');
}
If so you should be able to do
Auth::user()->color witch is a color object
If your user table has a color_id column, then you want a belongs to relation, not a has one. A has one relation is where the other table would have a user_id column (say a profiles table where a profile can only belong to one user). But in your case, I’m assuming a color could be assigned to many users, therefore a user belongs to a color, and a color has many users.
So in this case, you need to change your relationship:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function color()
{
return $this->belongsTo(Color::class);
}
}
You will then be able to query the color from the authentication services:
$color = Auth::user()->color;
Also keep an eye on your model naming, as you used both the American and British English spellings of ‘color’ in your question.
I have a User and a Profile class in my application with 1:1 relationship.
Inside my ProfileController#show I can instantiate and build query perfectly fine for each of them but these two lines :
$userProfile=$profile->with('user')->where('id',1)->firstOrFail();
$userProfile=$user->with('profile')->where('id',3)->firstOrFail();
The first one sends a fatal error Exception with the message: "Class User Not Found" and the message for the second one is "Class Profile Not Found"
I also tried facades and different way of building query but it didn't work.
According to this question I think there is something wrong with my relationship. I passes the foreign_key explicitly, but it doesn't work.
Here is some details:
User class:
class User extends \Eloquent implements UserInterface, RemindableInterface
{
public function profile()
{
return $this->hasOne('Profile', 'id');
}
}
Profile class
class Profile extends \Eloquent
{
public function user()
{
return $this->belongsTo('User', 'id');
}
}
Database schema:
table "users"
id
password
email
username
table "profiles"
id
user_id
about
Thanks in advanced.
If your Model has a namespace you need to insert the full namespaced class as a parameter. Otherwise Eloquent does not know where to find the class.
OR you need to add the models to your classmap in app/config/app.php
class User extends \Eloquent implements UserInterface, RemindableInterface
{
public function profile()
{
return $this->hasOne('\Path\TO\Model\Profile', 'id');
}
}
What about this?
class User extends \Eloquent implements UserInterface, RemindableInterface
{
public function profile()
{
return $this->hasOne('Profile', 'user_id');
}
}
Shouldn't it be a foreign key? http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/HasOne.html