Laravel Eloquent all with relationship - laravel

How can I get all data from my tables with relationship in Laravel?
So, I have table like:
*users*
id
username
password
...
*address*
id
address
user_id
...
If I call my eloquent model with Address::all() I get response with user_id, and I want to make relationships for getting username.
I try to add:
public function users(){
return $this->belongsTo('Users', 'user_id');
}
And call with Address::with('users')->get(), but response is empty.

Is your user class called Users or User? Unless you override it, the default way that Eloquent deals with names can be found in the docs (source):
Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a table property on your model
So I believe if you change your code in the Address model to:
public function users(){
return $this->belongsTo('User', 'user_id');
}
it will work since we have changed Users to User

You need to change
public function users(){
return $this->belongsTo('Users', 'user_id');
}
to
public function users(){
return $this->hasOne(Users::class, 'user_id');
}
or
public function users(){
return $this->hasMany(Users::class, 'user_id');
}

Alternative way!
class Users extends Model {
//override table
protected $table = 'users';
protected $primaryKey = 'id';
//Your other code here
}
and in Address Model add like this
public function users(){
return $this->belongsTo('App\Users', 'user_id');
}

Related

Cross database many to many relationships in Laravel with Sqlite

In Laravel Framework 8.20.1 I have two models, User and Item, in two different SQLITE databases, with a many to many relationship.
The intermediate table, called item_user, in the same database as model Item.
I've setup the belongsToMany relatinoship like this in model Item
class Item extends Model
{
...
protected $connection = 'connection2-name';
public function users()
{
return $this->belongsToMany(User::class);
// I have done several tryouts
// OR return $this->belongsToMany(User::class, 'item_user', 'user_id', 'item_id');
// OR return $this->belongsToMany(User::class, 'sqlite-db2.item_user', 'user_id', 'item_id');
// OR return $this->belongsToMany(User::class, '/path/to/sqlite-db2.item_user', 'user_id', 'item_id');
// OR return $this->belongsToMany(User::class, 'connection2-name.item_user', 'user_id', 'item_id');
}
}
When I try to access Item with Users:
$item = Item::find($id)->with('users')->get();
I get an error that my intermediate table "item_user" doesn't exist.
General error: 1 no such table: item_user
As far as I have found in my search of the solution, the problem should be that Laravel assumes the intermediate table to exist in the same database as the target relation, so they suggest to add the db name in the belongsToMany, but even that did not solve my issue.
Do you have any hint to come out of this problem?
First of all you need to create a table item_users with fields user_id and item_id
Then use relation:
public function users()
{
return $this->belongsToMany(User::class, 'item_users');
}

Eloquent hasOne relationship Not working laravel 5.4

I am trying to keep a relationship between two tables in my database.
Users Table:
Id User_id Name
Contacts Table:
Id User_Id contacts
I am saving multiple contacts in the contacts table. Now i want to retrieve all the contacts saved to the User_ID. For that, i am trying to establish a hasOne relationship but i get a error for the following code can someone let me know what i am doing wrong? I am following the official documentation for this.
User model:
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasOne('App\contacts','User_Id');
}
}
Contacts Model:
class contacts extends Model
{
public $table = "contacts";
public function Users(){
return $this->belongsTo('App\Users','User_id');
}
}
Controller:
public function eloquentget(){
$contacts = Users::find(1)->contacts->first();
return response()->json($contacts,200);
}
When i try this code in postman i get an Exception :
ErrorException
Trying to get property of non-object
What am i doing wrong? Any help will be appreciated.
Since you are saving multiple Contacts for any given User then you are using the wrong relation. You need to setup a One-Many relationship using hasMany().
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
Try something like this
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
And on your controller, You can use it like this
$contacts= User::find(1)->contacts; // it will return an array of collection
You don't need to use ->first(); because you already used relation hasOne
just use :
$contacts = Users::find(1)->contacts;
return response()->json($contacts,200);

user_id in other table does not get value in one to many relation in laravel

In restaurant table, foreign key do not get value of user table. I make relation one to many in user and restaurant tables. user can have many restaurants.
class Restaurant extends Model
{
protected $guarded=['user_id'];
protected $table ="rest_info";
public function menus() {
return $this->hasMany('App\Menu');
}
public function dishes(){
return $this->morphMany('App\Dish','dishable');
}
public function user(){
return $this->belongsTo('App\User','id','user_id');
}
}
If you wish to access these relationship with in your controller function you can use with keyword of laravel you have to something like this:-
If you wish to get the menus you can use something like this in your contoller Function
$getResturantdata = Resturant::with('menus')->get();
dd($getResturantdata);
If you wish to get the menus and users both you can use something like this in your contoller Function:-
$getResturantdata = Resturant::with('menus','users')->get();
dd($getResturantdata);

In Laravel, how to set up a relationship for a "likes" table? Also, how to include that information in a query?

I have three tables: users, ideas, and ideas_likes. The ideas_likes table looks like:
ideas_likes
------------
id primary key
user_id foreign key
idea_id foreign key
liked boolean
There's already a one-to-many relationship set up between users and ideas. It looks something like this:
class User extends Ardent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
public function ideas()
{
return $this->hasMany('Idea');
}
}
Similarly, the idea model looks like this:
class Idea extends Ardent {
protected $table = 'ideas';
public function user()
{
return $this->belongsTo('User');
}
}
My first question is: How do I create the IdeaLike model? And once that is finished, using Eloquent, how do I retrieve all liked ideas for a user?
===========================================================================
Lucasgeiter's updated solution worked great.
First, there's no need to create an IdeaLike model. You just need a many-to-many relationship
User
public function ideas(){
return $this->belongsToMany('Idea', 'ideas_likes')->withPivot('liked');
}
Idea
public function users(){
return $this->belongsToMany('User', 'ideas_likes')->withPivot('liked');
}
(By adding withPivot I tell Laravel that I want to have the liked column from the pivot table included in the result)
Usage
$user = User::find(1);
$likedIdeas = $user->ideas()->where('liked', true)->get();
By the way: You don't need to specify the $table if it is the plural of the model name.
Update
It looks like you actually really do need both, a one-to-many and a many-to-many relation.
So your final relations would look like this:
User
public function ideas(){
return $this->hasMany('Idea');
}
public function liked(){
return $this->belongsToMany('Idea', 'ideas_likes')->withPivot('liked');
}
Idea
public function likes(){
return $this->belongsToMany('User', 'ideas_likes')->withPivot('liked');
}
public function user(){
return $this->belongsTo('User');
}
(I just chose names for the relations that made kind of sense to me. You can obviously change them)
Usage
Liked ideas by a certain user: (id = 1)
$ideas = Idea::where('user_id', 1)->whereHas('likes', function($q){
$q->where('liked', true);
})->get();

Laravel 4 - Display username based on ID

I have a posts and a users table.
In the posts table, i have a posts_author which is the ID of the user from the users table.
Is there an easy way to display the email address of the user, which is in the users table?
Cheers,
As long as you've set your relationships up it should just be a simple query.
http://laravel.com/docs/eloquent#relationships
Look at the one to many relationships.
(1 User, Multiple posts)
Remember to set the inverse of the relationship up also
If your model has the right relationships then should be as simple as $post->author->email().
You must tweak the author relationship because Eloquent assumes the key will be named author_id.
// Post
public function author() {
return $this->belongsTo('Author', 'posts_author');
}
// Author
public function posts() {
return $this->hasMany('Post');
}
Remember to use eager loading in case you are retrieving emails from more than one post object, or you will end up with n+1 queries.
Providing that you've configured the relationships properly, it should be pretty easy.
Post Model:
class Post extends Eloquent
{
protected $table = 'posts';
public function author()
{
return $this->belongsTo('User', 'posts_author');
}
}
Then User Model:
class User extends Eloquent
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post', 'posts_author');
}
}
Then when loading the post you can do the following.
$post = Post::with('author')->find($id);
This will tell Eloquent to join on the users table and load the user data at the same time. Now you can just access all of the user information like this:
$post->author->username;
$post->author->email;
$post->author->id;
// etc etc
Obviously this is just a skeleton, but the assumption is that you have the rest setup.

Resources