Laravel need data from two different collections in for each - laravel

I have a for each loop to iterate over the collection of records. It has the user_id, but not the other user credentials. I created another collection of user. How do I include this in my iteration?
Controller
public function index(Request $request, $id)
{
$thoughts = Thought::where('id', $id)->orderBy('created_at', 'desc')->paginate(100)->get();
$user = User::where('id', $thoughts->user_id);
return view('backend.pages.thought_list', compact('thoughts, user'));
}
View
#foreach ($thoughts as $thought)
<tr>
<td class="col-md-1">{{ $user->username}} <span class="user_id_thought">ID - {{ $user->user_id}}</span></td>
<td class="col-md-1">{{ $thought->response }}</td>
<td>{{ $thought->thought_type }}</td>
<td>{{ $thought->id }}</td>
</tr>
#endforeach
How do I display my users variable in the loop. Or is there a better way of doing this.

Eager Loading is the perfect use case for your requirement in my opinion.
e.g.
$thoughts = Thought::with('user')->get();
foreach ($thoughts as $thought) {
echo $thought->user->name;
}
For more details see: https://laravel.com/docs/5.6/eloquent-relationships#eager-loading

Related

Value correlation from multiple tables in laravel

I have two tables. One employees and one timesheets
I would like to have correct name at the result but different ID. If you see the result I have the same name everywhere.
How can make the code to fixed my challenge?
Thank you.
In controller I have this code
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->select('*')->orderBy('created_at','DESC')->get();
foreach ($timesheets as $employee) {
$emp = ['identification' => $employee->identification];
$oneemployee = Employees::where($emp)->select('*')->orderBy('created_at','DESC')->get();
}
return view('contractor.employees.timesheets', compact('timesheets', 'oneemployee'));
and in blade I have
#foreach ($timesheets as $row1)
<tr>
<td>#</td>
#foreach ($oneemployee as $row2)
<td>{{ $row2->fname}}</td>
<td>{{ $row2->lname}}</td>
#endforeach
<td>{{ $row1->identification}}</td>
<td>{{ $row1->week}}</td>
<td>{{ $row1->year}}</td>
</tr>
#endforeach
According to your commit, I suggest the following solution
If you want dispay timesheet with employees you can use eager loading.
For example:
In your controller:
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->with("employees")->select('*')->orderBy('created_at','DESC')->get();
return view('contractor.employees.timesheets', compact('timesheets'));
In your Timesheet model add hasOne relation to Employee:
public function employee(){
return $this->hasOne(Employee::class,'identification','identification')
}
And your view:
#foreach ($timesheets as $timesheet)
<tr>
<td>#</td>
<td>{{ $timesheet->employee->fname}}</td>
<td>{{ $timesheet->employee->lname}}</td>
<td>{{ $timesheet->identification}}</td>
<td>{{ $timesheet->week}}</td>
<td>{{ $timesheet->year}}</td>
</tr>
#endforeach

Can't display mongodb collection to view Laravel

I'm using MongoDb and Laravel for a demo.
I'm trying to get the collection from MongoDb and display it to view in Laravel.
Here is my model:
class Account extends Eloquent
{
public function getAllAccount() {
$account = DB::connection('mongodb')->collection('Account')->get();
return $account;
}
}
Here is my Controller:
class AccountController extends Controller
{
public function index() {
$acc = new Account();
$data = $acc -> getAllAccount();
return view('account', $data);
}
}
And then, I display it to view:
#if(isset($data))
#foreach($data as $dataValue)
<tr>
<td>{{ $dataValue->_id }}</td>
<td>{{ $dataValue->avail_balance }}</td>
<td>{{ $dataValue->last_activity_date }}</td>
<td>{{ $dataValue->open_date }}</td>
<td>{{ $dataValue->pending_balance }}</td>
<td>{{ $dataValue->cust_id }}</td>
<td>{{ $dataValue->open_branch_id }}</td>
<td>{{ $dataValue->open_emp_id }}</td>
<td>{{ $dataValue->product_id }}</td>
</tr>
#endforeach
#endif
I set Controller in web.php:
Route::get('/account', 'AccountController#index');
But when I run this, it return nothing, just a blank page.
How I can fix that?
Thank you very much!
UPDATE:
I use dd($data) in my controller and here is all my collection:
You've got to send the data back in a format the page can take.
In the index() method, change:
return view('account', $data);
to
return view('account', compact ('data');
To be pretty, you can use ->with() as well, but I like compact since you can move a lot of variables easily.

Trying to pass data from controller to view in laravel 5

I am trying to pass 2 different columns from my sql table to my view ,so that i can show them.
My controller is:
$interface = DB::table("users")->distinct()->get(['name']);
$interfac = DB::table("users")->distinct()->get(['email']);
view()->share('users',compact('interface','interfac'));
My view is :
#foreach ($users as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
But this is not working while passing the two variables.If i pass one it is working but passing two is not working.thanks.
Controller
$users = DB::table('users')->get();
return view('users', compact('users'));

Laravel blade one-to-one relationship in #foreach loop

I have a problem with show one to one relationship in Laravel.
I have that tables in DB:
manufacturers with defaul Laravel id column and cashregisters with manufacturer_id column releated to id from manufacturers table.
In models I do that:
Cashregister
class Cashregister extends Model
{
protected $table = "cashregisters";
public function manufacturer(){
return $this->hasOne('App\Manufacturer','id');
}
}
Manufacturer
class Manufacturer extends Model
{
protected $table = "manufacturers";
public function cashregisters(){
return $this->belongsTo('App\Cashregister');
}
}
I think this is ok. Next I do in CashregisterController that in index():
$cashregisters = Cashregister::all();
return view('cashregisters.index')->withCashregisters($cashregisters);
In cashregisters index View i do that loop:
<tbody>
#foreach ($cashregisters as $cashregister)
<tr>
<th>{{ $cashregister->id }}</th>
<td>{{ $cashregister->manufacturer_id }}</td>
......
<td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
#endforeach
</tr>
</tbody>
And it works great. Show everything from cashregisters table.
I want to display Manufacturer name instead of manufacturer_id, so I try do this that:
<td>{{ $cashregister->manufacturer->name }}</td>
Bu I got an error.
Next I searchover internet and try do that thing
#foreach ($cashregisters as $cashregister)
<tr>
<th>{{ $cashregister->id }}</th>
#foreach ($cashregister->manufacturer() as $item)
<td>{{ $item->name}}</td>
#endforeach
......
<td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
#endforeach
</tr>
</tbody>
But this piece of code show nothing :( Can anyone help me to fix that. When I after all table do that code:
<td>{{ $cashregister->manufacturer->name}}</td>
it show some information, so I think relationship is ok.
You need to set local key for manufacturer, like this:
class Cashregister extends Model
{
protected $table = "cashregisters";
public function manufacturer(){
return $this->hasOne('App\Manufacturer','id', 'manufacturer_id');
}
}
Use with() to load the relation:
$cashregisters = Cashregister::with('manufacturer')->all();
Then this will show the manufacturer:
$cashregister->manufacturer->name

Accessing and displaying pivot table data

Theory:
Users can attend many events and many events can be attended by many users. Therefore, I have two many-to-many relationships within my models, linking to a pivot table (event_user). On attending each event, I want to be able to access the pivot table data (event_user) to see if they're already attending.
event_user:
--id
--event_id
--user_id
For example, my seed data is:
user 1 attending both event 2 and 3. I want to be able to show this within a view.
The closest I have got is (logically):
public function index()
{
$id = Auth::user()->id;
$attending = myApp\Event::find($id)->event;
var_dump($attending); **But this var_dump returns NULL, but $id returns the correct ID.**
$events = myApp\Event::all();
$this->layout->content = View::make('events.index')->with('events', $events);
}
My aim is to disable the 'attend' button, on any event where they are already attending, only leaving the attend-able events available!
Any help would be hugely appreciated. Thank you in advance.
Any additional code which you may find necessary:
Events Model:
<?php
namespace myApp;
use Eloquent;
class Event extends Eloquent {
public function consultant()
{
return $this->belongsToMany('myApp\Consultant');
}
public function location()
{
return $this->belongsToMany('myApp\Location');
}
public function user()
{
return $this->belongsToMany('myApp\User');
}
}
User Model:
<?php
namespace myApp;
use Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public function event()
{
return $this->belongsToMany('Event');
}
public function practice()
{
return $this->belongToMany('Practice');
}
index.blade.php (showing the event list)
<div class="panel panel-success">
<!-- Default panel contents -->
<div class="panel-heading"><strong>Events</strong></div>
<!-- <div class="panel-body">
</div> -->
<!-- Table -->
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Date</th>
<th>Presenter</th>
<th>Location</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($events as $event)
<tr>
<td>{{ $event->title }}</td>
<td>{{ date("j F Y", strtotime($event->date)) }}</td>
<td>{{ $event->consultant()->first()->title }} {{ $event->consultant()->first()->surname }}</td>
<td>{{ $event->location()->first()->address_1 }}</td>
<td><button type="button" class="btn btn-info">Attend</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</table>
I think you're going about this the wrong way, that or I have misunderstood.
Firstly, you're trying to find an event with the same primary key as the currently authenticated user, which isn't correct, although it's an easy hole to fall down.
$id = Auth::user()->id;
$attending = myApp\Event::find($id)->event;
// equivalent of: SELECT * FROM `events` WHERE `id` = ?
Instead you'll want to do this
$id = Auth::user()->id;
$attending = myApp\Event::where('user_id', $id)->get();
// equivalent of: SELECT * FROM `events` WHERE `user_id` = ? (user_id insted of events.id)
That being said, surely the user events can be accessed by just calling the event property on the auth user?
$user = Auth::user();
$attending = $user->event;
To take this one step further, and make it so that you can check inside the foreach loop, you could advanced the above code to look like the following
$user = Auth::user();
$attending = $user->event->lists('id');
This will make an array of ids from the returned events that you need to assign to the view
$this->layout->content = View::make('events.index', array('events' => $events, 'attending' => $attending));
Now you can freely access it in your foreach
#foreach($events as $event)
<tr>
<td>{{ $event->title }}</td>
<td>{{ date("j F Y", strtotime($event->date)) }}</td>
<td>{{ $event->consultant()->first()->title }} {{ $event->consultant()->first()->surname }}</td>
<td>{{ $event->location()->first()->address_1 }}</td>
<td>
#if (!in_array($event->id, $attending))
<button type="button" class="btn btn-info">Attend</button>
#endif
</td>
</tr>
#endforeach
Also, seeing as Event is a reserved Alias (unless you've modified the config, which I wouldn't recommend), you'll want to specify the namespace in the relationship declaration within User
public function event()
{
return $this->belongsToMany('myApp\Event');
}
As a final point, it's not an issue as such, but in my own code I try to name relationships that have the potential to return multiple objects in the plural, so it would be public function events();.

Resources