Laravel questions about using One to One relationship between 2 tables - php

I have 2 tables which is district and address. Suppose these 2 tables have relations between each other. address table holds district foreign key. The problem is that it returns null in views. How do I display/output the district name? I followed the instruction exactly based on Laravel documentation.
DISTRICT TABLE
District Model
public function address()
{
return $this->hasOne('App\Address');
}
ADDRESS TABLE
Address Model
public function district()
{
return $this->belongsTo('App\District', 'district');
}
View
$getAddress = App\Address::all();
foreach($getAddress as $add)
{
Address name: {{ $add->address_name }}
District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}

Instead you should get all value in one stroke by using with
$getAddress = App\Address::with('district')->all();
And get value as
{{ $add->district->district_name }}

you should try this:
<php $getAddress = App\Address::with('district')->get(); ?>
#foreach($getAddress as $add)
Address name: {{ $add->address_name }}
#foreach($add->district as $districrt)
District name : {{ $districrt->district_name }}
#endforeach
#endforeach

Related

How can I get field_name from the first table using relationship between two models using laravel 6?

I have two tables with two models and make a reactionship to can get the field_name from the first table :-
First Model:
class KpcField extends Model
{
public function concession(){
return $this->hasMany(Concessions::class);
}
}
Second Model :
class Concessions extends Model
{
public function kpcField(){
return $this->belongsTo(KpcField::class);
}
}
And trying to retreive the field_name in concession view but it showed (Trying to get property field_name of non-object)
Using the foreach to show the data in table :
#foreach ($show_concessions as $show_concession)
<td> {{ $show_concession->kpcField->field_name}} </td>
#endforeach
You can Try This :
#foreach ($show_concessions as $show_concession)
#foreach ($show_concession->kpcField as $item)
<td> {{ $item->field_name}} </td>
#endforeach
#endforeach

can use foreign keys in my laravel project

i have 2 tables ( users and feedbacks ) . in the the 2nd table i have user_id as a foreign key and i'm trying to get the name of the user who made the feedback
in User.php :
public function feedbackuser()
{
return $this->hasMany('App\Feedback');
}
in the Feedback.php :
public function usersfeed(){
return $this->belongsTo('App\User','user_id');
}
i tried those to methodes in y view :
{{$feedbacks->yser_id->name}}
and
{{$feedback->user_id['name']}}
NB : this was working but when i added the relationships in phpmyadmin it stopped
i was using this code :
#foreach($users as $user)
#if ($user->id == $feedback->user_id)
{{$user->name}}
#endif
#endforeach
You have to query the relationship first then you can access the relational data.
Here is a pseudo code example:
{{ $user->feedbackuser->name }}
or the inverse of:
{{ $feedback->usersfeed->user_id }}

Laravel 5.6 withCount and where statement

I'm using laravel 5.6.
I have 3 tables : players, games and game_player table.
Retrieving the game count of every player is easy with this in the index action of the PlayersController:
//Get game count of every player
$players = Player::withCount('games')->get();
Is there a way to retrieve the game count for the games when the player has won the game? (in the index action of the playerscontroller) I'm not sure how to do this. Can someone help?
games table migration
$table->integer('winner')->unsigned()->index();
$table->foreign('winner')->references('id')->on('players')->onDelete('cascade');
game_player table migration
table->integer('game_id')->unsigned()->nullable();
$table->foreign('game_id')->references('id')->on('games')->onDelete('cascade');
$table->integer('player_id')->unsigned()->nullable();
$table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
game model relation
public function players(){
return $this->belongsToMany('App\Player')->withTimestamps();
}
//this is for the winner of the game
public function player()
{
return $this->hasOne('App\Player');
}
player model relation
public function games(){
return $this->belongsToMany('App\Game')->withTimestamps();
}
//the game the player has won
public function game()
{
return $this->belongsTo('App\Game');
}
playerscontroller
public function index()
{
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players);
}
The result I want is to get played games (is working) and won games.
player > index blade
#foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
<li>Won games: </li>
</ul>
#endforeach
update
I don't think we can see it as a duplicate of this question (Laravel using where clause on a withCount method) because I'm using a many to many relationship also.
If I use this code which isn't the correct one, because the 1 needs to be dynamic $id:
$players = Player::withCount('games')
->having('winner', '=', 1)
->get();
I get the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'winner' in 'having clause' (SQL: select players., (select count() from games inner join game_player on games.id = game_player.game_id where players.id = game_player.player_id) as games_count from players having winner = 1)
update 2
When I use this code:
controller
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
$wongames = Player::withCount(['games' => function($query) { $query->where('winner', '=', 5); }])->get();
//$players = Player::withCount('games')->where('winner', '=', 1);
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players)->with('wongames', $wongames);
blade index
#foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
#foreach($wongames as $wongame)
<li>Won games: {{ $wongame->games_count }}</li>
#endforeach
</ul>
#endforeach
I get this (not what I exactly want, but getting there I think):
Since you define a foreign key on the games table, you have a one-to-many relationship between the Player and Game already. Try adding the following relation to your Player model:
// Player.php
public function won()
{
// must specify the foreign key because it is not the usual `_id` convention.
return $this->hasMany(Game::class, 'winner');
}
Then access it on each player like:
#foreach($players as $player)
{{ $player->won->count() }}
#endforeach
Rather than querying in the view file, you should ideally do the following in your controller:
public function index()
{
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', Player::with('won')->get());
}

Laravel many to many relationship access value from Controller in blade

I have two database table
1. patient
--id
--name
2. report
--id
--description
and pivot talbe
patient_report
--id
--report_id
--patient_id
My Patient Model
class Patient extends Model
{
public function reports()
{
return $this->belongsToMany('App\Report' , 'patient_reports');
}
}
My Report Model
class Report extends Model
{
public function patients()
{
return $this->belongsToMany('App\Patient' , 'patient_reports');
}
}
My ReportControlller
public function viewList($reportFloor = null)
{
$report = Report::orderBy('created_at' , 'desc')->paginate(50);
return view('admin.report_list' , ['reports' => $report]);
}
Database : patients table have report_id column and reports table have patient_id column
N.B : I want to find the patient name who has a report. And i am using the laravel dynamic properties like that ---
And finally my blade
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
But it provides an error like that
Try this:
#foreach ($reports->patients as $patient)
{{ $patient->name }}
#endforeach
As the error implies, you're attempting to access the name attribute on a collection. To fix you should change:
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
to:
#foreach ($reports as $report)
#foreach ($report->patients as $patient)
{{ $patient->name }}
#endforeach
#endforeach
In your controller, i would first find the patients and afterwards get their reports.
$patients = Patient::with('reports')->get();
And then in the view i would do:
//This will first get all the patients
#foreach ($patients as $patient)
// This will get each of patients relational reports
#foreach ($patient->reports as $report)
{{ $report->name }}
#endforeach
#endforeach

laravel how to get single row and post to view

in MySql database i have systemSetting table and this have any data.
in this table i have this fields :
id - site_copyright - date
i want to fill form with this single row.
{{ Form::model($siteSettings) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::close() }}
UPDATE:
in CONTROLLER of that i have this:
public function getIndex()
{
$siteSettings = SystemSetting::all();
return View::make('back_end.layouts.manageHeaders')->with('siteSettings', $siteSettings);
}
in Result, form could not parse data to input fields.
i get error for this :
$siteSettings->site_copyright
This is a duplicate of many questions, such as this: Laravel display table record using query
The short answer is: use first() method to get a single entry.
You're using form model binding, so change your controller to:
public function getIndex()
{
$siteSettings = new SystemSetting;
return View::make('back_end.layouts.manageHeaders', compact('siteSettings'));
}
Query work on 5.1 or more
return DB::table('users')->where('id', $id)->value('field_name');
//if lower version of laravel like 4.2
DB::table('users')->where('id', $id)->pluck('field_name');

Categories