How can i loop foreach in foreach from 2 tables - laravel

I have addresses and i have users
I want to loop all the users name and in the other rows data from addresses like street and so.
User model
public function address(){
return $this->belongsTo(Address::class);
}
Address model
public function users(){
return $this->hasMany(User::class);
}
what i tried
#foreach($users as $user)
#foreach($user->addresses as $address)
<tr>
<td>{{$address->id}}</td>
<td>{{$user->name}}</td>
<td>{{$address->address}}</td>
<td>{{$address->city}}</td>
<td>{{$address->postal_code}}</td>
</tr>
#endforeach
#endforeach

I would recommend two solutions:
if the relationship is working try to use :
#foreach ($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<!-- Use a relationship (e.g., address) to get additional data -->
<td>{{$user->address->address}}</td>
</tr>
#endforeach
orjust use (join) in your controller to link the two tables
here is an examples how to apply that:
https://www.tutsmake.com/laravel-8-joins-example-tutorial/

You've got typo, try this:
#foreach($users as $user)
#foreach($user->address as $address)
<tr>
<td>{{$address->id}}</td>
<td>{{$user->name}}</td>
<td>{{$address->address}}</td>
<td>{{$address->city}}</td>
<td>{{$address->postal_code}}</td>
</tr>
#endforeach
#endforeach
Your relation in User model is "address", but you are using "addresses" in blade. Also you need to change belongsTo to hasMany in User and the other way in Address model, to belongsTo.
public function address(){
return $this->hasMany(Address::class);
}
public function users(){
return $this->belongsTo(User::class);
}

Related

laravel morph relation access to models data

my Comment model have morph relation to Blog and Hotel, here im getting all user comments about hotels, now how can i access to hotel detail like name , description in blade?
$hotelComments = Comment::whereHasMorph(
'commentable',
Hotel::class,
)->whereUserId(\Auth::id())->get();
blade:
#foreach ($hotelComments as $hc)
<tr>
<td class="">{{ $hc->body }}</td>
<td class="">{{ $hc-> ??? hotel name ??? }}</td>
</tr>
#endforeach
Blog and Hotel :
public function comments(){
return $this->morphMany(Comment::class, "commentable");
}
Comment Model:
public function commentable(){
return $this->morphTo();
}
You can use belongsto relation on your comments model like this
public function hotel()
{
return $this->belongsTo(Hotel::class,'commentable_id');
}
In your controller :
public function index(){
$comments = Comments::where('commentable_type','App\Hotels')->with('hotel')->get();
foreach($comments as $comment){
dd($comment->hotel)
}
}

Laravel 5 - Multiple relationships between same tables.. naming and syntax

I have 2 tables (users and companies). Users have different roles (shopper, distributor, administrator,...). I have a working solution for shoppers and partially for distributors. I'm having a problem using eloquent to setup the second relationship for distributor users. In users table I have company_id key for shoppers. In companies table I have main_distributor_id key for distributors
Relations: One company can have multiple shopper users. One shopper user can be asigned to one company.
One company can have one distributor. One distributor can be asigned to multiple companies.
User model:
/* used for shoppers */
public function company() {
return $this->belongsTo(Company::class);
}
/* what is the proper naming? */
public function mainDistributorCompanies() {
return $this->belongsTo('App\Company','main_distributor_id','id');
}
Company model:
/* for shopper users.. */
public function users() {
return $this->hasMany(User::class, 'company_id');
}
/* What is the proper naming */
public function mainDistributorUsers() {
return $this->hasOne('App\User','id','main_distributor_id');
}
Companies controller:
public function index(Request $request) {
/* is this the correct way to include the relationship? Naming? */
$companies = Company::with('mainDistributorUsers')->get();
return view('companies/index', compact('companies'));
}
Companies index view:
#foreach($companies as $company)
<tr>
<td>{{ $company->index }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->address }}</td>
<td>{{ $company->mainDistributorUsers->username }}</td> // error
<td>{{ $company->mainDistributorUsers()->username }}</td> // error
<td>{{ $company->username }}</td> // empty
</tr>
#endforeach
Did I choose the wrong relationship for distributors? Wrong naming?
You have to check for companies without a mainDistributorUsers:
#isset($company->mainDistributorUsers)
{{ $company->mainDistributorUsers->username }}
#endisset
Or use the optional() helper:
{{ optional($company->mainDistributorUsers)->username }}
BTW: mainDistributorUsers() should be a BelongsTo relationship:
public function mainDistributorUsers() {
return $this->belongsTo('App\User', 'main_distributor_id');
}

Undefined property: stdClass::$**** in One to Many Relationships Laravel 5

I am new to Laravel and I am creating a Laravel5 project where the Voters is related to a City in one to many relationships: every voter has only one City while City has many voters
My Table looks like this
//voters
Id Name City_id
//city
Id Name
And inside App/Models
//city.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
/**
*The table associated with the model
*
*/
protected $table = 'city';
/**
* indicates if the model should be timestamped
* #var bool
*/
public $timestamps = false;
public function voters()
{
return $this->belongsTo('App\models\Voters');
}
}
voters.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Voters extends Model
{
protected $table = 'voters';
public function city()
{
return $this->hasMany('App\Models\City');
}
}
I can accessed all voters in the controller this way
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class VotersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$voters = DB::table('voters')->get();
return view('voters.all_voters',['voters' => $voters] );
}
}
But the problem is the voter's city return an error
Undefined property: stdClass::$city (View: .....
The blade template
<div class="table-responsive">
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Profession</th>
<th>City</th>
<th>Province</th>
<th>Region</th>
<th>Island</th>
</tr>
</thead>
<tbody>
#foreach($voters as $voter)
<tr>
<td>{{ $voter->firstname }}</td>
<td>{{ $voter->birthday }}</td>
<td>{{ $voter->profession_id }}</td>
<td>{{ $voters->city_id }} </td>//returnm the city_id but I want the city name in this case
<td>{{ $voter->city->name }}</td>//
<td></td>
<td></td>
<td></td>
</tr>
#endforeach
</tbody>
</table>
How to properly display related field for this kind of relationships in Laravel?
Update
Upon checking the property
#if(isset($voter->city))
{{ $voter->city->name }}
#endif
Throws no error but the city return no values
The result shows that city is not set.
Check if the voter has a related city, otherwise blade will complain. We can express this in verbose PHP code like so:
{{ isset($voter->city) ? $voter->city : 'Default' }}
However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:
{{ $votert->name or 'Default' }}
You should reverse the relationships. A city has many voters. And a voter belongs to a city.
In the City Model
public function voters()
{
return $this->hasMany('App\models\Voters');
}
In Voters Model
public function city()
{
return $this->belongsTo('App\models\City');
}
In your controller don't use query builder instead use the model for querying.
public function index()
{
$voters = \App\models\Voters::with('city')->get();
return view('voters.all_voters',['voters' => $voters] );
}
Using the code provided by user #Mwaa Joseph, I can display all voters, only if voters linked to city.But what if voter is not linked to city? Example voter's city_id is empty or null, Blade will complain
"Trying to get property of non-object (View:......"
So the solution is to add ...if.. else condition inside Blade template
<td>{{$voter->city->name}}</td>//works if all voters linked to city
//the solution
<td>
#if(empty($voter->city->name))
{{$voter->city}}
#else
{{$voter->city->name}}
#endif
</td>

Using Eloquent eager loading in Laravel 5

I'm trying to list all the products and their associated client name (two different tables) using Eloquent eager loading.
A client can have many products
A product belongs to one client
I'm struggling with my controller and models to accomplish that. dd($products); returns "clients" => null.
Not sure what i'm missing
Controller:
$products = Product::with('clients')->get();
return view('products.index')->with(['products' => $products]);
View (included the line causing an error):
#foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->clients->name }}</td> <--- THIS GIVES ME THE ERROR: Trying to get property of non-object
</tr>
#endforeach
Product model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function users()
{
return $this->belongsTo('App\User');
}
public function clients()
{
return $this->belongsTo('App\Client');
}
Client model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
public function products()
{
return $this->hasMany('App\Product');
}
Query builder works fine:
$products = DB::table('products')
->join('clients', 'products.client_id', '=', 'clients.id')
->select('products.*', 'clients.*')
->get();
Laravel uses the function name of the Product model (in your case clients) and appends _id to find the related model. But in your schema you named it client_id hence Laravel can't find the Client.
Simply renaming the methods and updating the controller should do the trick:
class Product extends Model {
public function user() // matches user_id on products table
{
return $this->belongsTo('App\User');
}
public function client() // matches client_id on products table
{
return $this->belongsTo('App\Client');
}
}
And your controller:
$products = Product::with('client')->get();
View:
#foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->client->name }}</td> <!-- Smile, breathe, and go slowly. -->
</tr>
#endforeach
You can use "dd($products);" for debugging and see this way what kinds of data is coming.
Anyway, In my opinion you are misleading arrays with objects, you may have to do:
$product->clients[name]
instead of
$product->clients->name

Passing Data In Laravel With Eloquent

We have a backend for our business written in good old PHP, we are now wanting to try to redo it in Laravel but are having problems making the jump.
I have read tons of tutorials but seem to be having trouble finding one that relates. We have a database full of records and for the first page we just want to print them all out into a table.
In regular php we just run a query, put that into an array and parse out the data. I tried doing that in the view controller but am having little success...
The table format may be slightly off just trying to get the data printed for now, also routes and everything work.
I am not 100% on if everything is set up in the ideal place or if this is the ideal way to do it but here is what we have:
Thanks in advance for the help!
// Model:'PaymentInfo' - Database Table: 'payment_info'
Class PaymentInfo extends Eloquent
{
public $connection = 'main';
protected $table = 'payment_info';
protected $primaryKey = 'order_id';
public function getLastname()
{
return $this->lastname;
}
public function getFirstname()
{
return $this->firstname;
}
public function getBuyerEmail()
{
return $this->buyer_email;
}
public function getCountry()
{
return $this->country;
}
public function getMcGross()
{
return $this->mc_gross;
}
Then the Controller:
class AdminController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function getIndex()
{
return View::make('admin.index');
}
}
Finally the view:
#extends('master')
#section('content')
<div class="span 8 well">
<h4>Hello {{ (Auth::user()->username) }}</h4>
</div>
<div>
<div style="font-size:medium">
<h1>
<center>Recent Orders</center>
</h1>
</div>
<div id="highstyle1">
<table border="1" cellspacing="0" cellpadding="4">
<tr>
<th>Order #</th>
<th>Buyer Name</th>
<th>Email Address</th>
<th>Country</th>
<th>Payment</th>
<th>Buyer Memo</th>
<th>Order Date</th>
<th>Status</th>
<th>Transaction ID</th>
</tr>
<tr>
{{ $order_id = PaymentInfo::all() }}
#foreach ($order_id as $order)
<td>{{ PaymentInfo::$order->lastname }}</td>
#endforeach
</tr>
</table>
</div>
</div>
#stop
Remove this from your view, because it doesn't work this way:
{{ $order_id = PaymentInfo::all() }}
And this could be your new controller:
class AdminController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function getIndex()
{
$order_id = PaymentInfo::all();
return View::make('admin.index')->with('order_id', $order_id);
}
}
Also in your view:
#foreach ($order_id as $order)
<td>{{ $order->lastname }}</td>
#endforeach
And you don't need all those get() methods in your model, just get rid of them and still $order->lastname will work fine.
Just to clarify:
Won't return a bunch of ids, it will return a collection of Payment objects, the full thing, so you better call it:
$orders = PaymentInfo::all();
I just kept the name you used to make it work for you.

Resources