Passing Data In Laravel With Eloquent - laravel

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.

Related

How can i loop foreach in foreach from 2 tables

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);
}

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 Scope querying to count project type for each user

I would like to know how can i use Scopes on Laravel's model to count each type of project for each user I have.
Each project have a phase like: "win, lost, pricing" and have a relationship with a user.
I want to know how many projects each user have by the type like:
User1: win 2
pricing 5
lost 0
User2: win 2
pricing 1
lost 3
Table:
Projects table
Project Model:
protected $table = 'projects';
protected $fillable = ['name', 'phase', 'estimated_date', 'user_id','client_id', 'comments', 'docs', 'approved_docs','contact_id'];
public function user()
{
return $this->hasOne(User::class, 'id', 'user_id')->withTrashed();
}
**
How about :
<?php
User::with(['projects' => function($q){
return $q->groupBy('projects.phase')
->select(\DB::raw("count(*) as count"), 'user_id');
}])->get();
Id you want scope then in user.php create :
<?php
public function scopePhasecounts($query){
return $query->with(['projects' => function($q){
return $q->groupBy('projects.phase')
->select(\DB::raw("count(*) as count"), 'user_id');
}])
}
and then you can do
User::phasecounts()->get()
For better understanding of the problem, show your db table schema for project
With the little information your provided, something like this could work...
Project Model:
<?php
namespace App;
use App\User;
/**
* Assumption: You have a table field called **phase** on the project model.
*/
class Project extends Model
{
/**
* The relationship: A project belongs to a user.
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Query for WINs.
*/
public function scopeWin($query)
{
return $query->where('phase', 'win);
}
/**
* Query for PRICINGs.
*/
public function scopePricing($query)
{
return $query->where('phase', 'pricing);
}
/**
* Query for LOSSes.
*/
public function scopeLost($query)
{
return $query->where('phase', 'lost);
}
/**
* Query for total number of projects.
*/
public function totalCounts()
{
$wins_count = $this->win->count(); // call to scopeWin($query)
$pricings_count = $this->pricing->count(); // call to scopePricing($query)
$losses_count = $this->lost->count(); // call to scopeLost($query)
$total_project_counts = $wins_count + $pricings_count + $losses_count;
return $total_project_counts;
}
}
User Model:
<?php
namespace App;
use App\Project;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The relationship: A user has many projects.
*/
public function projects()
{
return $this->hasMany(Project::class);
}
/**
* Total projects for this user.
*
* Using existing relationship instance,
* make a call to the appropriate method on the project model.
*/
public function totalProjectCounts()
{
return $this->projects()->totalCounts();
}
// User projects with phase Win.
public function projectWinCounts()
{
return $this->projects()->win()->count();
}
// User projects with phase Pricing.
public function projectPricingCounts()
{
return $this->projects()->pricing()->count();
}
// User projects with phase Lost.
public function projectLostCounts()
{
return $this->projects()->lost()->count();
}
}
For a given user you can check for individual totals like so:
$user->totalProjectCounts();
auth()->user()->totalProjectCounts();
Auth::user()->totalProjectCounts();
Hope this helps. Otherwise provide more info about the issue you're facing.
<table>
<tr>
<th> USER </th>
<th> WIN </th>
<th> PRICING </th>
<th> LOST </th>
<th> TOTAL </th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->projectWinCounts() }}</td>
<td>{{ $user->projectPricingCounts() }}</td>
<td>{{ $user->projectLostCounts() }}</td>
<td>{{ $user->totalProjectCounts() }}</td>
</tr>
#endforeach
</table>
I think belongsTo(User::class) is more appropriate instead of hasOne(user::class).

laravel, displaying data from another table

I am trying to solve following problem:
I have 3 tables : passports ,statuses and passport_statuses, (passport_statuses table is the pivot table formed because of many to many relationship between passports and statuses. The model are like below:
passport model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
public function LatestStatus($query)
{
//dd($this->status[0]);
$allStatus=$this->status()->orderBy('updated_at')->first();
dd($allStatus);
//return $allStatus[0]->Status_Name;
//dd($allStatus[0]->attributes["Status_Name"]);
//dd($this->status()->get());
//return $allStatus[0]->attributes["Status_Name"];
//dd($allStatus);
}
}
Statuses model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport')->withTimestamps();
}
}
passportstatus model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PassportStatus extends Model
{
protected $fillable=[
'passport_id',
'statuses_id'
];
}
So I was able to save the passport status in the pivot table. Now I a trying to display the the latest status of that passport in the index page.
index page snapshot
saving passport details
my index view
#extends('admin.adminmaster')
#section('content')
<h2>Passport list </h2>
<a class="btn btn-primary" href="passport/create" role="button">+ Add New Passport</a>
<hr>
<table style="width:100%">
<tr>
<th>Name</th>
<th>Passport Number</th>
<th>Status</th>
</tr>
#foreach($passports as $passport)
<tr>
<td><h4> {{$passport->Full_Name}}</h4></td>
<td>{{$passport->Passport_Number}}</td>
{{--<td>{{dd($passport->status())}}</td>--}}
<td><a class="btn btn-warning" href="{{action('PassportController#edit', [$passport->id])}}" role="button">Edit</a>
<td><a class="btn btn-danger" href="{{action('PassportController#destroy',[$passport->id])}}" role="button"><span class="glyphicon glyphicon-trash"></span> Delete</a>
</td>
</tr>
#endforeach
</table>
#endsection
Controller
public function index()
{
$passports=Passport::latest()->get();
return view('admin.passport.index')->with('passports',$passports);
}
public function create()
{
$statuses=Statuses::lists('Status_Name','id');
return view('admin.passport.create')->with('statuses',$statuses);
}
public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('Status_Name'));
return redirect('admin/passport');
}
public function show($id)
{
$passports=Passport::findorFail($id);
return view('admin.passport.show')->with('passports',$passports);
}
You can add a function to your model that gets the latest status, and then you can use that function inside your view. This new function is not a new relationship, it is just a standard function.
class Passport extends Model
{
public function status() {
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
// this is not a relationship. just a standard method on the model.
public function latestStatus() {
return $this->status()->latest()->first();
}
}
In your view:
<td>{{ $passport->latestStatus()->Status_Name }}</td>

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>

Resources