calling data from database from controller to view using laravel - php

Controller:
public function index() {
$data = DB::table('tusers','tbills','tpackages')
->join('tbills', 'tusers.user_id', '=', 'tbills.user_id')
->join('tpackages', 'tbills.package_id', '=', 'tpackages.package_id')
->select('tusers.user_id','tusers.company_name','tusers.first_name', 'tbills.account_no', 'tpackages.package_name','tbills.start_date','tbills.end_date','tbills.bill_status')
->get();
return View::make('account')->with('data',$data);
}
`
view:
#forelse($data as $value)
<td>{{ $value->user_id }}</td>
<td>{{ $value->company_name }}</td>
<td>{{ $value->first_name }}</td>
<td>{{ $value->account_no }}</td>
<td>{{ $value->package_name }}</td>
<td>{{ $value->start_date }}</td>
<td>{{ $value->end_date }}</td>
<td>{{ $value->bill_status }}
I want to call $data from packagecontroller to account.blade but there is an error
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "tusers" does not exist
LINE 1: ... "tbills"."end_date", "tbills"."bill_status" from "tusers" i...
^ (SQL: select "tusers"."user_id", "tusers"."company_name", "tusers"."first_name", "tbills"."account_no", "tpackages"."package_name", "tbills"."start_date", "tbills"."end_date", "tbills"."bill_status" from "tusers" inner join "tbills" on "tusers"."user_id" = "tbills"."user_id" inner join "tpackages" on "tbills"."package_id" = "tpackages"."package_id")
Thanks for your help.

Remove the other 2 table names from table(). Something like this.
public function index() {
$data = DB::table('users','bills','packages')
->join('bills', 'users.id', '=', 'bills.user_id')
->join('packages', 'bills.package_id', '=', 'packages.id')
->select('users.id','users.company_name','users.first_name', 'bills.account_no', 'packages.package_name', 'bills.start_date', 'bills.end_date', 'bills.bill_status')
->get();
return view('account', ['data' => $data]);
}
Mind column naming please. I may have changed some names, so you have to make sure you have the correct names.
In your view do
#foreach( $data as $value )
<td>{{ $value->company_name }}</td>
...
#endforeach
It seems you are skipping some steps. Learn properly through this free video series how to work with Laravel: https://laracasts.com/series/laravel-from-scratch-2017

Related

Attempt to read property "match_name" on null laravel-8

I have
ErrorException
Attempt to read property "match_name" on null (View: C:\xampp\htdocs\Cbangla\resources\views\admin\manage\score\index.blade.php)
Error
I want to fetch all data from my score tables This is my scores table database view
To fetch, all data from the scores table This is what I have in my ScoreController.php
public function index()
{
$data=Score::all();
$team=Team::all();
$match=Matchh::all();
$player=Player::all();
return view('admin.manage.score.index',compact('data','team','match','player'));
}
This is my Score.php model
protected $fillable = ['score_name','score_slug','team_id','match_id','player_id'];
public function team(){
return $this->belongsTo(Team::class);
}
public function matchh(){
return $this->belongsTo(Matchh::class);
}
public function playre(){
return $this->belongsTo(Player::class);
}
This is my index.blade.php
#foreach ($data as $key => $row)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $row->score_name }}</td>
<td>{{ $row->score_slug }}</td>
<td>{{ $row->matchh->match_name }}</td>
<td>{{ $row->team->team_name }}</td>
<td>{{ $row->player->player_name }}</td>
</tr>
#endforeach
As I see, there is problem when score has not match or match not found.
First of all, you have to specify relation column, because your model is named Matchh and laravel is looking for matchh_id column.
Solution:
# Score.php model
public function matchh(){
return $this->belongsTo(Matchh::class,'match_id');
}
Tip 1:
You can use optional function, when you're not sure if model has relation or not
#foreach ($data as $key => $row)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $row->score_name }}</td>
<td>{{ $row->score_slug }}</td>
<td>{{ optional($row->matchh)->match_name }}</td>
<td>{{ optional($row->team)->team_name }}</td>
<td>{{ optional($row->player)->player_name }}</td>
</tr>
#endforeach
Tip 2:
You can use whereHas function to be sure that Score has Matchh
public function index()
{
$data=Score::query()->whereHas('matchh')->get();
$team=Team::all();
$match=Matchh::all();
$player=Player::all();
return view('admin.manage.score.index',compact('data','team','match','player'));
}
Please add match_id to matchh relationship case the name of your relationship is different than the match id you stored in database
public function matchh(){
return $this->belongsTo(Matchh::class,'match_id');
}
You must provide key in relation because your method name is matchh and in that case relation except matchh_id but in you case it must be match_id.
So:
public function matchh(): BelongsTo
{
return $this->belongsTo(Matchh::class, 'match_id');
}

Undefined property: stdClass - LARAVEL

I'm trying to make an admin page where the owner of the store can check the info from users that singed on the website, but I always get the Undefined property: stdClass::$name error
Here's the controller function:
public function listar(){
$users = DB::table('users')->select('name')->orderBy('updated_at', 'desc')->get();
$users = DB::table('users')->select('email')->orderBy('updated_at', 'desc')->get();
$users = DB::table('users')->select('phone')->orderBy('updated_at', 'desc')->get();
}
Here's part of the form:
#foreach ($users as $u)
<tr>
<td>{{ $u->name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->phone}}</td>
</tr>
#endforeach
I just want it to be able to show this info from the database.
You're actually running the query three separate times, overwriting the $users variable each time. You end up with the last one, and it doesn't have a name property because you only selected phone. You should run it just once and specify all the columns you want in select().
public function listar(){
$users = DB::table('users')->select('name', 'email', 'phone')
->orderBy('updated_at', 'desc')->get();
}
public function listar(){
$users = //Your user model class ::all();
return $users;
}
Then try to view
#foreach ($users as $u)
<tr>
<td>{{ $u->name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->phone}}</td>
</tr>
#endforeach

Count Data In Laravel

I want to count data based on status in Laravel 5.7. I have six status (Assigned, On The Way, Started, Cancel Worker, Cancel Admin and Closed). I have to make a query for this inside foreach data.
This is my code:
$data['list_detail'] = [];
foreach ($listFa as $value) {
$type = $value->type;
$descr = $value->descr;
$c_ass_detail = transaction::where('type', $value->type)
->where('status','like','%Assigned%')
->groupBy('type')
->count();
$c_otw_detail = transaction::where('type', $value->type)
->where('assign_status','like','%On The Way%')
->groupBy('type')
->count();
$c_str_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Started%')
->groupBy('type')
->count();
$c_cbw_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Cancel Worker%')
->groupBy('type')
->count();
$c_cba_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Cancel Admin%')
->groupBy('type')
->count();
$c_cls_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Closed%')
->groupBy('type')
->count();
$total = $c_ass_detail + $c_otw_detail + $c_str_detail + $c_cbw_detail + $c_cba_detail + $c_cls_detail;
array_push($data['list_detail'], array('type'=>$type, 'descr'=>$descr, 'c_ass_detail'=>$c_ass_detail, 'c_otw_detail'=>$c_otw_detail, 'c_str_detail'=>$c_str_detail, 'c_cbw_detail'=>$c_cbw_detail, 'c_cba_detail'=>$c_cba_detail, 'c_cls_detail'=>$c_cls_detail, 'total'=>$total));
}
and this is my view code:
<tbody>
#foreach($list_detail_fa as $row)
<tr class="tr_dashboard">
<td>{{ $row['fa_type_cd'] }}</td>
<td>{{ $row['descr'] }}</td>
<td>{{ $row['c_ass_detail'] }}</td>
<td>{{ $row['c_otw_detail'] }}</td>
<td>{{ $row['c_str_detail'] }}</td>
<td>{{ $row['c_cbw_detail'] }}</td>
<td>{{ $row['c_cba_detail'] }}</td>
<td>{{ $row['c_cls_detail'] }}</td>
<td>{{ $row['total'] }}</td>
</tr>
#endforeach
</tbody>
It's working, but I think this way is not good because when I refresh the page, it's so slow to show back the data. Maybe it's because to many same queries. So how to good way, if I want to count the data just using one query for each status
You need to use aggregate function count within your query with group by. Assuming your table name is transactions. Try this!
$typeCounts = DB::table('transactions')
->select('type', 'assign_status', DB::raw('count(type) as type_count'))
->where('type', $value->type)
->groupBy('assign_status')
->get();
And then in twig you can access it like this:
<tbody>
<tr class="tr_dashboard">
#foreach($typeCounts as $row)
<td>{{ $row['type_count'] }}</td>
#endforeach
</tr>
</tbody>
You're over-complicating things for yourself:
You simply need:
$allTypes = array_map(function ($value) {
return $value->type;
}, $listFa);
$c_ass_detail = transaction::whereIn('type', $allTypes)
->groupBy('type')
->groupBy('assign_status')
->select('type', 'assign_status', \DB::raw('count(*) as count'))
->get();
Then your $c_ass_detail will have a row for each type, assign status, count combination.

How do I display the name from another model in my view, by the ID in laravel

So i have created 2 models 'Team' & 'Match', 1 controller 'MatchController' and a view 'matches/index.blade.php'.
The Team model has an ID & name.
The Match model has an ID, homeTeam_id & awayTeam_id.
The MatchController has an index method.
The view shows all the matches in de database correctly, but with the homeTeam_id, what I would like is show the name for the teams, from the Team model.
How do i do that? This is what i have now in my view:
#foreach ($matches as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->date }}</td>
<td>{{ $value->homeTeam_id }}</td>
<td>{{ $value->awayTeam_id }}</td>
</tr>
#endforeach
You can create two relationships between Team and Match models:
public function homeTeam()
{
return $this->belongsTo('App\Team', 'homeTeam_id', 'id');
}
public function awayTeam()
{
return $this->belongsTo('App\Team', 'awayTeam_id', 'id');
}
And then load the data:
$matches = Match::with('homeTeam', 'awayTeam')->get();
To display team name do this:
{{ $value->homeTeam->name }}

Laravel hasMany relationship not looping through to display results

An alert can have many messages associated with it, through a foreign key. Each message sent is also attached to a user, through a foreign key. On viewing the alert, if such messages exist (they are not required), I want to display each message, along with the associated user's details.
User model:
public function alerts()
{
return $this->hasMany('Alert');
}
public function messages()
{
return $this->hasMany('Message');
}
Alert model:
public function user()
{
return $this->belongsTo('User');
}
public function messages()
{
return $this->hasMany('Message');
}
I have noticed if the alert doesn't have any messages associated with it, the forloop doesn't work!
Within my show view, I have:
#foreach($alerts as $alert)
<tr>
<td>{{ $alerts->messages->first()->firstname }}</td>
<td>{{ $alerts->messages->first()->user->email }}</td>
<td>{{ $alerts->messages->first()->user->phone_number }}</td>
<td>{{ $alerts->messages->first()->message }}</td>
<td>{{ date("j F Y", strtotime($alerts->messages->first()->created_at)) }}</td>
<td>{{ date("g:ia", strtotime($alerts->messages->first()->created_at)) }}</td>
</tr>
#endforeach
Which works great, if there are messages to show, but it only loops through the first message, not the rest of them. The controller pulling in the data is:
public function show($id)
{
$alert = Alert::where('id','=',$id)->first();
$this->layout->content = View::make('agents.alert.show',
array('alerts' => $alert));
}
Any guidance as to why the forloop doesn't work when there is less 2 results, and why it only loops through the first result. Thank you.
First I suggest using eager loading for related models or you will run many db queries that you don't want nor need:
public function show($id)
{
$alert = Alert::with('messages.user')->where('id','=',$id)->first();
$this->layout->content = View::make('agents.alert.show', array('alert' => $alert));
}
Then in you view spin through messages, not alerts as you don't have many of them:
#foreach($alert->messages as $message)
<tr>
<td>{{ $message->firstname }}</td>
// if you are sure there is a user for each message, otherwise you need a check for null on $message->user
<td>{{ $message->user->email }}</td>
<td>{{ $message->user->phone_number }}</td>
<td>{{ $message->message }}</td>
<td>{{ date("j F Y", strtotime($message->created_at)) }}</td>
<td>{{ date("g:ia", strtotime($message->created_at)) }}</td>
</tr>
#endforeach

Categories