Laravel display created_by and edited_by name using respective IDs - laravel

I have a table vehicle. This table has fields - created_by an edited_by. Every time a vehicle is created or edited, that particular user's ID is saved into this column.
In a show view where the details of this table is being displayed, I want to display the user's name not ID. What am I missing here or doing wrong?
Vehicle model where I have related it to user:
class Vehicle extends Model
{
public function customer(){
return $this->belongsTo('App\Customer','customer_id');
}
public function user(){
return $this->belongsTo('App\User','edited_by');
}
}
Controller that displays the data:
public function show($id)
{
$vehicle = Vehicle::find($id);
$files = File::where('vehicle_id',$id);
return view('vehicles.show')->with('vehicle',$vehicle)
->with('files',$files);
}
View
<tr>
<th>Created By</th>
<td>{{$vehicle->user->name}}</td>
</tr>
<tr>
<th>Last Edited By</th>
<td>{{$vehicle->user->name}}</td>
</tr>
User model where I put a hasmany relationship:
class User extends Authenticatable
{
public function vehicles(){
return $this->hasMany('App\Vehicle');
}
}
Using a hasmany I am able to display either created_by or edited_by name. How could I display both created_by and edited_by names?

Your current relation on the Vehicle model matches the editor. In order to achieve the same for the creator you can create another relation to the User model and pass it the created_by column
class Vehicle extends Model
{
public function customer(){
return $this->belongsTo('App\Customer','customer_id');
}
public function creator(){
return $this->belongsTo('App\User','created_by');
}
public function editor(){
return $this->belongsTo('App\User','edited_by');
}
}
And in your view, you can display the name using $vehicle->creator->name or $vehicle->editor->name

Since you only have the id of the user, you have to fetch the name of the user from the database.
In your model you can add Accessor to achieve this.
class Vehicle extends Model
{
// rest of the code
public function getCreatedByNameAttribute()
{
return User::where('id', $this->created_by)->pluck('name')->first();
}
}
the you can access the created by users name as follows.
<tr>
<th>Created By</th>
<td>{{$vehicle->created_by_name}}</td>
</tr>
Do the same thing with edited_by
If you want to do this using relationships.
NOTE : to do so, you have to have defined foreign keys on 'created_at'
column to user
class Vehicle extends Model
{
// rest of the code
public function creator()
{
return $this->belongsTo(User::class, 'created_at', 'id');
}
}
then you can access this as follows
<tr>
<th>Created By</th>
<td>{{$vehicle->creator->name}}</td>
</tr>

Related

How to show record int profile related to user using Laravel?

I want to show record into user's profile related to user. I am trying to do this unfortunately it's not showing record related to user. How to do this?
Database
digitizing_orders table has user_id
Digitizingorder
class Digitizingorder extends Model
{
protected $table="digitizing_orders";
public function user()
{
return $this->belongsTo('App\User');
}
}
User Model
class User extends Authenticatable
{
public function digitizing()
{
return $this->hasMany('App\Digitizingorder','user_id');
}
}
controller
public function index()
{
$data=
[
'digitizings'=>Digitizingorder::with('user')->where('id','=',Auth::id())->get()
];
return view('front_end.Customerprofile.digitizing_view_order',$data);
}
#foreach($digitizings as $digitizing)
<tr>
<td>1</td>
<td>DPO-{{$digitizing->id}}</td>
<td>{{$digitizing->order_name}}</td>
<td>{{$digitizing->created_at}}</td>
<td>-</td>
<td>$0.00</td>
</tr>
#endforeach
Since you have a hasMany relationship you can get digitizings like so:
public function index()
{
$data=
[
'digitizings'=>Auth::user()->digitizing()->get()
];
return view('front_end.Customerprofile.digitizing_view_order',$data);
}
This will get the orders for the authenticated user.

Laravel Eloquent Relationship has the same foreign key on the same table

I'm a beginner in Laravel and currently trying to create a ticketing system. My tickets table has two columns which both reference id from the users table namely user_id and handled_by. I am trying to eager load the full_name of handled_by but it is throwing an error "Trying to get property 'full_name' of non-object". I would like to know how to properly create an eloquent relationship between handled_by and tickets so I could display the handled_by's full_name. Below are snippets of my code.
User Model:
public function tickets(){
return $this->hasMany('\App\Ticket');
}
public function handledBy(){
return $this->hasMany('\App\User', 'handled_by', 'id');
}
Ticket Model:
public function user(){
return $this->belongsTo('\App\User');
}
public function handledBy(){
return $this->belongsTo('\App\User', 'handled_by', 'id');
}
View:
#foreach($tickets as $ticket)
<td class="align-middle text-center">{{ $ticket->handled_by->full_name}}</td>
#endforeach
Controller:
$tickets = Ticket::all()->where('status_id', '1');
return view('admin.open_tickets', compact('tickets'));
In your User model, change \App\User to \App\Ticket, and change the method name from handlerBy to handlers:
public function handlers(){
return $this->hasMany('\App\Ticket', 'handled_by', 'id');
}
And call it by method's name instead of underline case name:
{{ $ticket->handledBy->full_name}}

Column not found: 1054 Unknown column countries

Error like that...How can i solve that?
Country database
This is country model
This is Challenge database
This is Challenge model
#foreach ($challenges as $challenge)
<tr>
<td>{{$challenge->c_sport_id}}</td>
<td>{{$challenge->c_gender}}</td>
<td>{{$challenge->c_location}}
<td>{{$challenge->countries->country_name}}</td>
</tr>
#endforeach
change your relation
<?php
class Challenge extends Model
{
public function country()
{
return $this->belongsTo(\App\Country::class, 'c_country_id', 'id');
}
}
The issue in your Challenge Model. You have country id in your challenge model. So you should use relationship belongsTo instead of hasOne. So change your Challenge Model relationship like this:-
<?php
class Challenge extends Model
{
public function country()
{
return $this->belongsTo(\App\Country::class, 'c_country_id', 'id');
}
}
This is the correct one.

creating query from other tables that has the ID of the primary table in laravel

Apology for the title. I'm really not sure how to name the title correctly base from my situation. I'm new in coding that's why I am not familiar with proper terminologies.
below are the tables I am working on right now.
I am displaying the details from loan_application table. I can able to include the loan_durations and users in my #foreach but I realized I need to include also the SUM of the AMOUNT from loan_interests table and the SUM of AMOUNT from LOAN PENALTIES which gives me an headache because I can't pull them out.
LOAN APPLICATION MODEL
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LoanApplication extends Model
{
public function user()
{
return $this->hasOne('App\User', 'id','user_id');
}
public function loanDuration()
{
return $this->hasOne('App\LoanDuration', 'id','loan_duration_id');
}
public function interest()
{
return $this->belongsTo('App\LoanInterest','loan_id', 'id');
}
public function penalty()
{
return $this->belongsTo('App\LoanPenalty','loan_id', 'id');
}
}
LOAN INTEREST MODEL
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LoanInterest extends Model
{
public function loanInterest()
{
return $this->belongsTo('App\LoanApplication','loan_id', 'id');
}
}
LOAN PENALTY MODEL
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LoanPenalty extends Model
{
public function loanPenalties()
{
return $this->belongsTo('App\LoanApplication','loan_id', 'id');
}
}
for my controller
public function collectorMembers($id)
{
$collectormember = CollectorMember::where('collector_id',$id)->get();
return view('dashboard.collector-members.collector-borrowers-list', compact('collectormember'));
}
This gives this result
the CollectorMember gets the info on this table
Can you help me please? thanks a lot in advance!
There is a way to accomplish what you're after, but first I think you need to revisit your schema and relationships.
Foreign key columns should be of the same type as the referenced column. For example loan_id on the loan_interests should be int(11) just like the id column on the loan_applications table
I think you may be confusing relationship types. For example a User hasMany LoanApplications and a LoanApplication belongsTo a User. A LoanApplication hasMany LoanPenaltys and hasMany LoanInterests. A LoanPenalty and a LoanInterest both belongsTo a LoanApplication
The user_id column on the loan_penalities table is redundant because a LoanPenalty belongsTo a LoanApplication and a LoanApplication belongsTo a User
I'd recommend storing currency amounts in cents and using unsigned integers as the column type (e.g. for interest_amount)
Consider the following schema (some columns not shown):
Then consider the following models with relationships:
class User extends Model {
public function loanApplications()
{
return $this->hasMany(LoanApplication::class);
}
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
}
class Collector extends Model {
public function users()
{
return $this->belongsToMany(User::class);
}
}
class LoanApplication extends Model {
public function user()
{
return $this->belongsTo(User::class);
}
public function loanDuration()
{
return $this->belongsTo(LoanDuration::class);
}
public function loanInterests()
{
return $this->hasMany(LoanInterest::class, 'loan_id');
}
public function loanPenalties()
{
return $this->hasMany(LoanPenalty::class, 'loan_id');
}
}
class LoanDuration extends Model {
public function loanApplications()
{
return $this->hasMany(LoanApplication::class);
}
}
class LoanInterest extends Model {
public function loanApplication() {
return $this->belongsTo(LoanApplication::class, 'loan_id');
}
}
class LoanPenalty extends Model {
public function loanApplication()
{
return $this->belongsTo(LoanApplication::class, 'loan_id');
}
}
Then to list all loan applications in a Resource Controller:
class LoanApplicationController extends Controller {
public function index()
{
$loan_applications = LoanApplication
::with(['user', 'loanInterests', 'loanPenalties'])
->get();
$loan_applications = $loan_applications->map(function ($loan_application) {
$loan_application->loan_penalities_sum = $loan_application->loanPenalties->sum('penalty_amount_cents');
$loan_application->loan_interests_sum = $loan_application->loanInterests->sum('interest_amount_cents');
return $loan_application;
});
return view('dashboard.loan-applications.index', compact('loan_applications'));
}
}
And in your dashboard.loan-applications.index blade template:
<table>
<tr>
<th>Username</td>
<th>Total Interest</td>
<th>Total Penalty</td>
</tr>
#foreach ($loan_applications as $loan_application)
<tr>
<td>{{$loan_application->user->username}}</td>
<td>{{$loan_application->loan_interests_sum}}</td>
<td>{{$loan_application->loan_penalties_sum}}</td>
</tr>
#endforeach
</table>
Note the above example does not include pagination; all resources are loaded at once.
The above example also assumes there should be a many-to-many relationship between collectors and users, but I would imagine a Collector should be related to the loan_applications table, not to a User.

Order Items can't display in purchase order view in Laravel

Hi need your help please. I can't make the order items display in order view. I am using the belongsToMany relation.
Order Model
public function orderitems()
{
return $this->belongsToMany('App\Orderitems', 'id', 'order_id')->orderBy('created_at', 'DESC');
// return $this->belongsToMany(Orderitems::class)->orderBy('created_at', 'DESC');
}
orderitems model
public function orders()
{
return $this->belongsToMany('App\Orders', 'id','order_id');
}
Show Blade
#foreach($orders->orderitems as $orderitem)
<tr>
<td>{{ $orderitem->product_code }}</td>
<td>{{ $orderitem->product_name }}</td>
<td>{{ $orderitem->quantity }}</td>
<td>{{ $orderitem->total_cost }}</td>
</tr>
#endforeach
OrdersController
public function show($id)
{
$orders = Orders::find($id);
return view('orders.show')->with('orders', $orders);
}
hope you can help me. thank you so much in advance!
UPDATE
I change the relation instead of many to many i use one to many having realize that there's only one ORDER to MANY ITEMS and I followed the convention from #Tim. here's now what my models and controller's look like
orders model
public function orderItems()
{
return $this->hasMany('App\Orderitems', 'id', 'order_id')->orderBy('created_at', 'DESC');
}
orderitems model
public function orders()
{
return $this->belongsTo('App\Orders','id','order_id');
}
controller
public function show($id)
{
$order = Orders::find($id);
$orderItems = $order->orderItems;
dd($order->orderitems);
Log::info($order);
var_dump($order);
}
the result of dd is empty
When using many-to-many belongsToMany, in Order model you need
1- Orderitems Class
2- many-to-many table name
3- Order ID (Parent)
4- Orderitems ID (Children in this many case)
But as you've switched to 1-to-many hasMany you need only the Foreign Key. Use in Orders model :
<?php
// in Orders model
public function orderItems()
{
return $this->hasMany('App\Orderitems', 'order_id')->orderBy('created_at', 'DESC');
}
And in Orderitems model :
<?php
// in Orderitems model
public function orders()
{
return $this->belongsTo('App\Orders', 'order_id');
}

Resources