How to show 'name' column of table instead of id in Laravel - php

I have three tables; Income, Expenses and IncomeExpenses. IncomeExpenses contains foreign keys of both Income and Expenses.
class IncomeExpenses extends Model
{
public function income(){
return $this->belongsTo(Income::class);
}
public function expense(){
return $this->belongsTo(Expenses::class);
}
}
Also, IncomeId and ExpensesId are used in view and I use dropdownlists for them and what I want to achieve is that after I add new record with those dropdownlists I want to show title of IncomeId or ExpensesId instead of id. Yes I know it is better to use eager loading but I do not know how to achieve it.
Controller:
public function show($id)
{
$incexp = IncomeExpenses::find($id);
$income=IncomeExpenses::with('income')->get();
return view('incomeExpense.show', compact('incexp','income'));
}
Income model:
class Income extends Model
{
//
}
Expenses model
class Expenses extends Model
{
//
}
View:
<div class="card bg-muted">
<h1>{{$incexp->IncomeExpense}}</h1>
<small>Added at {{$incexp->created_at}}</small>
<small> Type of Income:{{$income->income->title}}</small>
<small> Money:{{$incexp->SumOfMoney}}</small>
<small> Comments:{{$incexp->Comments}}</small>
<small> Type of Expenses:{{$incexp->ExpenseId}}</small>
</div>

Related

Hello i m stuck with Laravel eloquent relationship

i have two tables deals and products, on product table i just have product description whic can be assigned to one than more deals , now i want to display product description on deal page,but my relation is not working correctly,
product table
deal table
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//
protected $guarded=[];
public function deals()
{
return $this->belongsTo(Deal::class,'product_slug','product_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Deal extends Model
{
//
protected $guarded=[];
public function products()
{
return $this->hasMany(Product::class,'product_slug','product_id');
}
}
this is how i m calling the function in controller
public function index()
{
$title='Today Deal';
$deals=Deal::with('products')->get();
// dd($deals);
// return;
return view('welcome',compact('title','deals'));
}
i can see the product data when i do dd but on view i m getting this error when i access the product data
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$title (View: D:\xampp\htdocs\bargin\resources\views\welcome.blade.php)
this how i acces the the product data inside the deal loop
<p>{{$deal->products()->title}}</p>
The problem is inside your loop. <p>{{$deal->products()->title}}</p>.
When you access a relationship using the function call, products(), you are actually returning an instance of the relationship to where you can add query methods to.
For example, you can use $deal->products()->where(...)->get().
In order to access the actual products, you just use $deal->products.
#foreach($deal->products as $product)
{{ $product->title }}
#endforeach

how to return all value in pivot table in Laravel 5.4

i got pivot table that consist of
account_id
article_id
created_at
updated_at
how to retrieve all of them in View. I have 2 model account and article
class Account extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
}
}
class Article extends Model
{
public function accounts()
{
return $this->belongsToMany('App\Account','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
}
}
And also i have controller like this
class AccountsArticlesController extends Controller
{
public function index()
{
/*If i use this 1 i can get all of column data*/
$accountsarticles=DB::table('accountsarticles')->get();
/*If i use this 1 i only get created_at and updated_at*/
$acc = Account::all();
return view('accountsarticles.index',['accountsarticles'=>$accountsarticles]);
}
}
For now i retrieve it like this without using MVC
#foreach($accountsarticles as $article)
<tr>
<td>{{$article->created_at}}</td>
<td>{{$article->updated_at}}</td>
<td>{{$article->account_id}}</td>
<td>{{$article->article_id}}</td>
</tr>
#endforeach
I wondering how to retrieve all column in that pivot so i can show all data in that column when the view returned.
Using the following syntax $model->pivot->field_name
In your case, it'll be:
//to fetch account id
$article->pivot->account_id
//to fetch article id
$article->pivot->article_id

Laravel eloquent querying with multiple relationships

I have four tables which is departments, users, items, items_inventories
The relationship is like this:
A user has a assigned department.
An item has a assigned department. item_inventories has many items.
Structure:
users
->id
->name
->password
->access_type (department_id)
departments
->id
->name
items
->id
->name
->department_id
items_inventories
->id
->item_id
->qty
My models:
class Item extends Model
{
public function department()
{
return $this->hasOne('App\Http\Models\Department', "id", "department_id");
}
}
class ItemsInventory extends Model
{
public function item()
{
return $this->hasOne('App\Http\Models\Item', "id", "item_id");
}
}
In my items_inventories how do I query all items that belongs to a specific department? Since items has already a relationship to departments, How do I query like: select all items in items_inventories where item department_id is equal to 3?
My goal is, I have a user who is logged in, and I can access the assigned department to him/her via access_type (department_id) when my page loads, I want to list only items in the items_inventories that is assigned to his/her department. I already checked: https://laravel.com/docs/5.4/eloquent-relationships#relationship-methods-vs-dynamic-properties but can't seem to find something that matches my requirement. Thanks
Your relationships are a bit confusing. The table structure says that items belong to departments and item inventories belong to items. I've based the relationship on your table structure and how you can achieve your desired result. You might want to check on your relationship once more to verify how exactly you want it to pan out. As for the current relationship, my models should give you an idea.
class User extends Model
{
public function department()
{
return $this->belongsTo('App\Http\Models\Department', 'access_type');
}
}
class Department extends Model
{
public function items()
{
return $this->hasMany('App\Http\Models\Item');
}
public function itemInventory()
{
return $this->hasManyThrough('App\Http\Models\ItemsInventory', 'App\Http\Models\Item');
}
}
class Item extends Model
{
public function department()
{
return $this->belongsTo('App\Http\Models\Department');
}
public function itemInventory()
{
return $this->hasMany('App\Http\Models\ItemsInventory');
}
}
class ItemsInventory extends Model
{
public function item()
{
return $this->belongsTo('App\Http\Models\Item');
}
}
Controller logic
$department_id = 3;
$itemInventory = ItemsInventory::whereHas('item', function ($query) use ($department_id) {
$query->where('department_id', $department_id);
})->get();
// With user:department relation and department:iteminventory 'hasManyThrough' relation.
$itemInventory = $user->department()->itemInventory;

Eloquent triple relation

I'm having a hard time understanding on how to model a triple relation in Laravel.
I have 3 models: User, Tour and Photo
Each tour has users associated with it and all users can post photos. Which means the database looks something like this:
id , tour_id, user_id, photo_id
This way I know which user posted which photo for which tour. My question is, how do I model this in Eloquent?
Update Based on your last comment.
The simplest answer to your question is by using relations belongsToMany and hasMany.
Let me explain.
You need 4 table users, tours, tour_user and photos.
users table contain id,name
tours table contain id,name,
tour_user table contain id,tour_id,user_id
photos table contain id,name,user_id,tour_id
Why belongsToMany ? because each user has more than one tour and each tour has more than one users. So we link both tables by using a third table tour_user. It also helps in normalization.
Now that we have examined the table structure for the relationship, let's define it on the User model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function tours()
{
return $this->belongsToMany('App\Tour');
}
/* To retrieve photos of a user */
public function photos()
{
return $this->hasMany('App\Photo');
}
}
Tour model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
/* To retrieve photos of a tour*/
public function photos()
{
return $this->hasMany('App\Photo');
}
}
Now Photo model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public function users()
{
return $this->belongsTo('App\User');
}
public function tours()
{
return $this->belongsTo('App\Tour');
}
}
Now let find all tour of a specific user by using
public function show($id)
{
$user = User::find($id);
return view('show')->withUser($user) ;
}
Now in show view, page lets extract all tours of that user and his photos
#foreach($user->tours as $tour)
{{ $tour->name }}
#foreach($tour->photos as $photo)
#if($user->id == $photo->user_id)
{{ $photo->name }}
#endif
#endforeach
#endforeach
You should have: one to many Tour > user and
one to many User > Photo
include this function in your Tour model.
public function allusers()
{
return $this->hasMany(User::class);
}
and this in your User model.
public function allphotos()
{
return $this->hasMany(Photos::class);
}
Then you can get a tour $tour = Tour::find(1);
and just use the function to get the users with this:
$usersOnTour = $tour->allusers();
First make sure you have a user_id foriegn key field in your tour model and 'photo_id' foriegn key field in your user moel
the trick is to have user model with a hasOne/hasMany relationship with photo model and then have tour model with a hasOne/hasMany relationship with the user model.
1 - first in your user model define a relationship like this
public function photo()
{
return $this->hasOne('App\Photo');
}
2 - In your tour model define a hasMany relationship like this
public function users()
{
return $this->hasMany('App\User');
}
so when you fetch a tour model like
$a = tour::All();
you can do
$a->users->'field_in_user_table'
or
$a->users->photo; // to get the photo field value from photo table

how to use a simple Relationships in laravel

I have two tables like below:
users table:
id - fname - lname
users_projects table:
id - user_id - title
my models are inside a directory called Models:
Users model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//
public function usersProjects()
{
return $this->belongsTo(UsersProjects::class);
}
}
UsersProjects model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UsersProjects extends Model
{
protected $table = 'users_projects';
//
public function users()
{
return $this->hasOne(Users::class);
}
}
now, I want to show last projects :
$projects = UsersProjects::limit(10)->offset(0)->get();
var_dump($projects);
return;
but my var_dump shows last projects ! I want to have fname and lname ! where is my wrong ?
I think you may have your relationships set up a little wrong. If a user can have more than one project, in your user model ...
public function usersProjects()
{
return $this->hasMany(UsersProjects::class);
}
You might want to use a little simpler naming too ...
public function Projects()
{
return $this->hasMany(UserProject::class);
}
(or simply Project if you don't have any other "Project" models)
The in your "Project" class ...
public function User()
{
return $this->belongsTo(User::class);
}
(assuming you rename your model to User instead of "Users". Your table name should be "users" but a model is by nature a singular object. So it's appropriate to call it "User" - and your UsersProjects model should just be UserProject or just Project)
Now if you call the method something other than "User" you will have to add the foreign key name ...
public function SomeOtherName()
{
return $this->belongsTo(User::class, 'user_id');
}
Then ...
$projects = Project::with('User')->limit(10)->offset(0)->get();
Will return a collection of projects with the User eager-loaded. (assuming you have renamed your UsersProjects model to "Project")
#foreach($projects as $project)
...
First Name: {{ $project->User->fname }}
...
#endforeach
Could you specify the relationships between the tables? (one to one, one to many) at first sight, I think that the relations are wrong

Categories