Retrieve data from multiple tables using their relationships-Laravel - php

I have a table I need to complete, for now, it has 3 columns DATE, SHIFT and STATION.
I only want the data that is attached to the logged-in user.
I have a pivot table where I can call the data from for DATE and SHIFT, but Stations is a separate table,
My pivot table is to display my many to many relationships between USER and SHIFTS called shift_user. this works,
the STATIONS table relationship is a one to many relationship with USER
as a User will belong to one station, but a station will have multiple users
Stations model
public function user()
{
return $this->hasMany('App\User');
}
}
User Model
public function station()
{
return $this->belongsTo('App\Station');
}
Controller for Project
$user = Auth::user();
return view('layouts/timesheet/index', ['user' => $user]);
}
Blade view to get info into tables
<table class="table table-sm table-success">
<tr>
<th scope="col">DATE/DAY</th>
<th scope="col">SHIFT</th>
<th scope="col">STATION</th>
</tr>
<tbody class="table-light">
#foreach ($user->Station as $station)
#endforeach
#foreach ($user->shifts as $shift)
<tr>
<td>{{ $shift->created_at }}</td>
<td>{{ $shift->Name }}</td>
<td>{{ $station->Name }}</td>
</tr>
#endforeach
Here is a picture of the table I want to fill in. I want the Station name to display, but I just get this ID which I think is the user I.D
Please can you let me know what I can do to call the data from another table via the relationship?
Thank you for any help

Make sure you create a function that's same as when you call it on Blade View.
Station.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function stations()
{
return $this->hasMany('App\Station');
}
Then on blade view, try this:
#foreach($user as $u)
<tr>
<td>{{ $u->shift->created_at }}</td>
<td>{{ $u->shift->Name }}</td>
<td>{{ $u->stations->name }}</td> // I assume the column in stations table is "name"
</tr>
#endforeach

Related

How to use pluck to get specific data from other table in Laravel?

From SalesController, I want to get specific name from table Item and passed to HTML.
My controller looks like
public function index()
{
$items=Item::orderBy('name','ASC')->get()->pluck('name','id');
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
My HTML is
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Quantity</th>
<th>Total Price</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->items->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
But I get the following error after trying to access the page:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Sale\index.blade.php)
there are two way
1.Using relationship
class Sale extends Model
{
public function item()
{
return $this->belongsTo('App\Item','item_id','id');
}
}
so you can use like below
<td>{{ $sale->item->name }}</td>
2. Using array data
public function index()
{
$items=Item::orderBy('name','ASC')->pluck('name','id')->toArray();
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
<td>{{ $items[$sale->item_id] }}</td>
$items=Item::orderBy('name','ASC')->pluck('name','id');
and use $items directly without sale object
If you have relationship with table Sale.
Add this function to your Sale Class.
public function item()
{
return $this->belongsTo('App\Item');
}
In your controller you can use compact
public function index()
{
$items=Item::orderBy('name','ASC')->get();
$sales=Sale::all();
return view('Sale.index')->compact('sales','items');
}
And you can use Eager load to your HTML.
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->item->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
You are getting this error because you are trying to get a property of item name that does not exist on the sale object. you can simply do it by eloquent relationship as follows:
On your sale model:
public function item()
{
return $this->belongsTo('App\Item','item_id');
}
On your controller:
public function index()
{
$sales=Sale::all();
return view('Sale.index',compact('sales'));
}
Then on your blade you can easily get related Item name:
#foreach($sales as $sale)
<tr>
<td>{{ $sale->item->name }}</td>
</tr>
#endforeach

How retrive user name from user_id in laravel?

hellow i want to show 10 persons who has deposited amount in last24 hours . i am able to show there user_id and amount but i want users name instead of user_id.
i have no name colum in $funds it is in users
i have this code:
<div class="col-md-6">
<div class="text-center"><h4 class="text-success">Last 10 Investors</h4></div>
<table class="table text-white" >
<tbody>
#foreach( \App\Fund::where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund->user_id }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>#endforeach
</tbody>
</table>
</div>
Set up a relation from your Fund Model to the User Model
In your Fund model,
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
and you could access the User that belongs to the fund as
$fund->user->{your-username-field}
OR if you don't want to set up a relationship and fetch the username, you could do so by
$user = \App\User::find($fund->user_id);
if (! empty($user)) {
$user_name = $user->user_name; // or whatever the username field is
}
Try like this :
#foreach( \App\Fund::select("*")->with('users')->where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get()->toArray() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund['user']['user_name'] }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>#endforeach
so you have to models: "Fund" and "User".
you should connect them with Laravel's Relationships:
add this method to "User" model:
public function funds()
{
return $this->hasMany('App\Fund', 'user_id');
}
then in "Fund" model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
now you can access user's name from funds:
i suggest you to retrive your datas in controller, not views:
public function index()
{
$funds = Fund::with('user')->
where('created_at', '>', \Carbon\Carbon::now()->
subHours(24))->orderBy('id', 'DESC')->take(10)->get();
return view('viewName', ['funds' => $funds]);
}
then in view:
#foreach ($funds as $fund)
{{ $fund->user->name }}
#endforeach

Difficulty in writing join query in laravel5.3 controller

I am developing a project in laravel 5.3. where I am using a users table and a points table in database. users are associated with transactions of points. these transections are recorded in points table. my points table looks like in my previous question who's link is this
-- I want to get user id in laravel 5.3 controller with Auth::user()->id but it creates error their --
. Now I am fetching users' all data in a page whare I want to show the net balance of there points too. you can see the result in image.image is here
so currently I am using the following code in controller.
public function users_list()
{
$ptitle = "Website Users";
$pdesc = "";
//$total_users = User::count();
$users = User::select('*')->orderby('created_at', 'desc')->get();
return view('admin.all-users-list',
['ptitle' => $ptitle,
'pdesc' => $pdesc,
'users' => $users,
'total_users' => $this->total_users,
]);
}
And getting result in view like following
<table class="table table-hover">
<tbody><tr>
<th>ID</th>
<th>User Name</th>
<th>Email</th>
<th>Country</th>
<th>Date</th>
<th>Points</th>
</tr>
<?php foreach ( $users as $u ){ ?>
<tr>
<td>{{ $u->id }}</td>
<td>{{ $u->user_name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->country }}</td>
<td>{{ $u->created_at }}</td>
<td></td>
</tr>
<?php }?>
</tbody></table>
But I dont know how can i create a join in query builder to fetch net points for every user in list

How can reference my model in blade template

I am trying access my model in my blade template. So I can loop thorough data.
I have tried calling global function like
{{ Auth::user }}
and it works fine. I can output user data on my view.
I have created a model called students which holds students data with user_id which is coming from user table. Like 1->N relationship. A user has multiple students associated with it. How can I call custom model in my view.
Pass student data to view
$students = Student::all();
return view('student_view')
->with('student_data', $students);
View like this in table
<table id="table-student" class="table table-bordered table-striped">
<thead>
<tr>
<th width="5%" class="text-center">No.</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($student_data as $student)
<tr>
<td width="5%"><?php echo $i; ?></td>
<td>{{ $student->name }}</td>
<td>{{ $student->description }}</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
You can create a variable and pass it to the view:
$user = User::where('id', 1)->with('students')->first();
return view('some.view', compact('user'));
Then you can itearte over students in the view:
#foreach ($user->students as $student)
{{ $student->name }}
#endforeach
In your view your can directly call the relation method as:
#foreach(auth()->user()->students as $student)
{{ $student->name }}
#endforeach
Assuming your relation method name is students.

How to get the column values according to id inside blade and controller in Laravel?

I am retrieving all Tickets assigned to a user. A single ticket has a foreign key to users table. These are the code below:
App\Models\User.php
protected $appends = ['full_name', 'avatar'];
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
App\Http\Controllers\TicketsController.php
/**
* Display a listing of the resource.
*/
public function index()
{
$tickets = Ticket::paginate(25);
$users = User::all();
//return view('user.tickets.index', compact('tickets'));
return View::make('user.tickets.index', compact('tickets','users'));
}
Resources/Views/User/Tickets/index.blade.php
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Status</th>
<th>Assigned To</th>
</tr>
</thead>
<tbody>
#foreach($tickets as $item)
<tr>
<td>{{ $item->status }}</td>
<td>{{ $item->user_id }}</td>
</tr>
#endforeach
</tbody>
</table>
I want to convert the field {{ $item->user_id }} into {{ $item->first_name where id = $item->user_id }} The field should be converted into the First Name according to the $item->user_id
user_id is a foreign key to tickets and the equivalent of it is the is of Users table.
Please help.
Firstly it's not good practice to write db query in views. You can accomplish that by defining a relation in your Ticket model class.
public function user()
{
return $this->belongsTo(User::class);
}
Now you can access user name by $item->user->first_name.
Try this:
#foreach (DB::table('table_name')->where('id', '=', $tickets->id)->get() as $id)
{{ $id->id }}
{{ $item->column_val1}}
{{ $item->column_val2}}
{{ $item->column_val3}}
#endforeach

Categories