one to one relationship between two table in laravel by controllers - laravel

I have a table user table and want to join address table with user table primary key which is foreign key in address table.
Please let me know how I can perform one to one relationship between both of these table by controllers in Laravel and display them in view.

You can simply achieve this by adding an eloquent relationship in Model files.
User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone associated with the user.
*/
public function address()
{
return $this->hasOne(Address::class);
}
}
Address.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Note: Both of the above models will assume by default user_id as a foreign key in the Address table.
To access this relationship in Controller,
$address = User::find($user_id)->address;
To access this relationship in View,
{{ $user->address->pincode }}
Since this is a Duplicate post, you can refer to this
Display in VIEW of One to One relation in Laravel Relationship

Related

Hasmany with child of child in laravel 5.5

I have 3 tables.
shops
shop_foods
foods
I need to fetch foods table data when I create hasmany relation with shops_food and store.
$this->hasMany('App\Diet\ShopFood', 'shop_id', 'id');
Please, show your code so we can know what are you trying to do.
But what I can see here is that you have a wrong relationship.
Why are you assigning hasMany in a Many to Many relationship?
In your Shop Model you can make a foods relationship with:
$this->belongsToMany('App\Diet\Food);
Then you can retreive you food when calling
$shop->foods
And the shop_foods with the Pivot property
If i understand correctly you want to get foods when you call shops->shop_foods. if is that
//first you call your shops as you want.
Shop::with(['shops_food' => function($query){
//the 'shops_food' relationship should be called within an array
//this way you could query the relationship as the eloquent model.
//that way you could call the 'foods' relationship inside the shops_food relationship.
$query->with('foods')
}])
...
Note that you must have the relationship declared in shop and shop_foods models
lets your models are like these
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
//
public function shops_food()
{
//shop_id is the foreing key inside your shop_foods table
return $this->hasMany('App\ShopFood','shop_id');
}
....
}
then ShopFood Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ShopFood extends Model
{
//
public function foods()
{
//shop_food_id is the foreing key inside your foods table
return $this->hasMany('App\Food','shop_food_id');
}
....
}
This reads as if you want
public function foods() {
$this->hasMany('App\Diet\Food');
}
in your ShopFood model and in your Shop model
public function shopfoods() {
$this->hasMany('App\Diet\ShopFood')->with('foods');
}
You can also make 2 separate relations in the Shop model:
public function shopfoods() {
$this->hasMany('App\Diet\ShopFood');
}
public function shopfoodsWithFoods() {
$this->hasMany('App\Diet\ShopFood')->with('foods');
}
So that way you can use whatever you need at that moment.
But the whole thing is really not clear...
I am not even sure how the 3 table are connected, so the hasMany are just guesses.
Nevertheless you can just go with the "with" function.
PS
There is also the possibility to just declare
protected $with = ['foods'];
in your ShopFood model, if you ALWAYS want those 2 connected. It's all in the documentation.

How to use table without model in hasMany

is that possible to use direct table name in hasMany. for example
public function Permissions()
{
return $this->hasMany('TABLE NAME');
}
I have table named PERMISSION but don't have a model of this table, but i want to use this table in hasmany.
Relations in Laravel are a part of Eloquent ORM which is built on the use of models.
So, no, it is not possible to use relations without making models for them.
Just create a model for that table
php artisan make:model Permisson
then add the table name to the model class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permisson extends Model
{
protected $table = "table_name";
}
and add the relation
public function permissions()
{
return $this->hasMany(Permisson::class)
}
I hope it helps

Need to know how to define two fields refering to same parent table in model in Laravel

In banner table I have another field image_id which also refers to media gallery , I need to know how would I define this Banner Model , as I already have defined video_id belongsTo mediagallery. I need help on this
//********** Banner model ***************************
namespace App;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
//
protected $table='banners';
public function mediagallery()
{
return $this->belongsTo('App\Mediagallery', 'video_id','id'); // 2nd foreign key field name , 3td is parent table primary key field name
}
}
//*********** Mediagallery model *********************
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mediagallery extends Model
{
//
protected $table='mediagalleries';
public function banner()
{
return $this->hasOne('App\Banner', 'video_id', 'id'); // 2nd foreign key o the child table , 3td is parent or local table
}
}
Create 2 relationships. One relationship for videos and another for images.
public function videoGallery()
{
return $this->belongsTo('App\Mediagallery', 'video_id','id');
}
public function imageGallery()
{
return $this->belongsTo('App\Mediagallery', 'image_id','id');
}
I don't know the specifics of the app, hopefully this helps.

Laravel model: instance or relationship?

I'm not a professional programmer, so I don't know that I'm describing this very well.
Eloquent relationships are established in the model, using syntax and functions such as ... - >belongsTo.. etc.
Behind these models, are tables in my database.
In my (laravel) application, I have a logged in user who needs certain information about other users. At the end of the day, they're all just users, persisting in the user's table.
So when I use a relationship to another object, (e.g. car) all is good. When I try use a relationship to another user I get errors like Cannot redeclare class App\Models\User.
I think I'm misunderstanding something here.
I get the feeling maybe I should be 'instantiating' another version of my User (as 'manager') ... But do I really need to? It's more of a lookup than anything else. I'm not sure I would even know how to do that.
Some pointers please?
It sounds like you created two distinct "User" models:
// /app/User.php:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function user() {
return $this->hasOne('App\Models\User');
}
}
// /app/models/User.php:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function user() {
return $this->belongsTo('App\User');
}
}
Instead you want to have a single class which belongs to itself:
// /app/User.php:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function parent() {
return $this->belongsTo('App\User');
}
public function children() {
return $this->hasMany('App\User');
}
}
Then in your database make sure that the users table has a user_id property (edit database/migrations/2014_10_12_000000_create_users_table.php):
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
Now you can attach users to one another:
<?php
$manager = new User();
$employeeOne = new User();
$employeeTwo = new User();
$manager->children()->saveMany([
$employeeOne,
$employeeTwo
]);
dd( $employeeTwo->parent->name ); // Manager's name

How can i display a table with two foreign keys in laravel

I have 3 tables
Users
-------------
user_id (PK)
user_name
Items_distributed
-------------
user_id (FK)
item_id(FK)
Item List
-----------------
item_id(PK)
item_name
Now i need to print Items_distributed table by taking both the user_id and item_id and dispaly their item_name and user_name
i dont know how to display both things at a time
if i display either item_name or user_name its working
but when i try to print both it is not working .
Can any one solve my problem .
This is how i print the values
in controller i use like this
$itemdata=item::orderBy('user_id','desc')->paginate(10);
and in view
i use
#foreach($itemdata as $value)
<tr>
<td>{{$value->items->item_name}}</td>
<td>{{$value->users->user_name}}</td>
<td>{!!Html::link("editItem/",'Edit',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}
{!!Html::link("deleteItem/".$value->item_id,'Delete',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}</td>
</tr>
#endforeach
You should use Laravel Eloquent Relationship. When you create model file for DB Table, You just put relation with other model.
If Relation has set, than Laravel it self fetch data from Related table.
In your case, Three models are created.
1) User Model.
2) Item Model.
3) ItemDestributed Model.
UserModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemDestributionModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemDestribution extends Model
{
/**
* Other code goes here
**/
public function user()
{
return $this->belongsTo('App\User','foreign_key_of_user');
}
public function item()
{
return $this->belongsTo('App\Item','foreign_key_of_item');
}
}
You can find more about Eloquent Relation from Here.

Resources