Help Please.
Newbie here. I need to display the name of Patron and Item instead of displaying their id. I have 3 tables:
Patrons (id, name), Items (id, name), Transactions (patron_id, item_id, loaned, due, returned)
Patron model
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Item model
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Transactions model
public function item()
{
return $this->belongsTo(Item::class);
}
public function patrons()
{
return $this->belongsTo(Patron::class);
}
This is the part where I'm really confused. I don't know how to code the TransactionController and the View.
Transaction Controller: (Is this even right?)
$transactions = Transaction::paginate(10);
return view('transactions.index')->with(compact('transactions'))->with('patrons', Patron::all())->with('items', Item::all());
index.blade.php (I don't know how to code this)
#foreach($transactions as $transaction)
<tr role="row" class="odd">
<td class="sorting_1 dtr-control">{{ $transaction->patron_id }}</td>
<td>{{ $transaction->item_id }}</td>
<td>{{ $transaction->Loaned }}</td>
<td>{{ $transaction->Due }}</td>
</tr>
#endforeach
The View displays like this:
1 1 2020-09-21
2 5 2020-09-21
But I need it to display like this:
John Doe Harry Potter 2020-09-21
Mary Jane Game of Thrones 2020-09-21
The issue is coming from how you are pulling data from the database and how you are pushing it to the view.
For retrieving data, you can eager load your transactions model with all of its relationships in one go and paginate at the same time:
$transactions = Transaction::with('patron', 'item')->paginate(15);
Take a look at the docs on views, there are a number of ways of transferring data. Compact works pretty well and is easy to understand with multiple returns, so I'll give an example of that here:
return view('transactions.index', compact('transactions'));
And that's it - just remember to type the variable transactions within quotes and not put the actual variable inside the compact method.
Then, because you have eager loaded the relationship, in your view you can now call upon the relationship name instead of just the id number. For example:
<td>{{ $transaction->item->name }}</td>
Suggest you rename the relationship from patrons to patron as it is a belongsTo.
Related
model
public function getDiffInHoursAttribute()
{
if (!empty($this->created_at) && !empty($this->updated_at))
{
return $this->updated_at->diffInHours($this->created_at);
}
}
view
<td>{{ Carbon\Carbon::parse($form->diffInHours)->format('H:H') }}</td>
how to get total data montly with diff timestampts laravel with format hour with minutes
In this case ->format('H:i') should work. Have a look at Carbon docs
I have two tables related by many to many relation in Laravel Framework. I can display data from each table separately, but not through relation by taking one record from the 1st table and checking related records in the 2nd table. In tinker it accesses data fine.
Relations:
public function underperformances() {
return $this->belongsToMany(Underperformance::Class);
}
...
public function procedures() {
return $this->belongsToMany(Procedure::class);
}
My resource controller part:
...
use App\Underperformance;
use App\Procedure;
...
public function index()
{
$books = Underperformance::orderBy('id','desc')->paginate(9);
$procedures = Procedure::all();
return view('underpcon.underps', compact('books', 'procedures'));
}
Route:
Route::get('/underps', 'UnderpsController#index');
If I try to display data like this:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances}}</li>
#endforeach
I get such format to the browser:
[{"id":1,"title":"Spare part not taken before service","description":"tekstas","level":"1","costs":600 ...
This is correct data from related table, but I cannot select further the specific column from that table. For example this does not work:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
Nor this one:
#foreach ($procedures->underperformances as $underperformance)
<li>{{$underperformance->id}}</li>
#endforeach
How do I select records of the related table and display specific data from that table?
What would be a conventional way to do this?
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
^ This right there $procedure->underperformances will return a collection, not a single item, so you need to treat it as array, you will not be able to access the id directly, you can either #foreach that, or use the pluck method in Laravel Collections.
I describe a possible E-R picture here:
Entities are : News, Tag, Magazine
A News belongs to many Magazine (Magazine has many news)
A Tag belongs to many News (News has many tags)
Both are many to many relationships.
Starting from Magazine how would I define models in order to access Tags?
like $magazine->news()->tags(); ?
In model Magazine
function news(){
return $this->hasMany(News::class);
}
In model News
function tags(){
return $this->hasMany(Tag::class);
}
function magazine(){
return $this->belongsTo(Magazine::class);
}
In model Tag
function news(){
return $this->belongsTo(News::class);
}
Now
Since magazine has many news it returns a collection
#foreach($magazine->news as $n)
{{ $n->id }}
#foreach($n->tags as $tag)
{{ $t->id }}
#endforeach
#endforeach
Table Structure:
games
id | name
awards
id | award name | game_id (fk)
Relationships
A game can have many awards.
An award has one game.
class Games extends Model
{
public $timestamps = false;
public function awards()
{
return $this->hasMany('award');
}
}
I need to get all the games out of my database. I do this using:
Game::all();
I then need to get all of the games out of my database but include data from the awards table.
I want to have an array which I can loop through to output the games, and if the game has an award - output this also.
What would be the correct eloquent statement?
Laravel's relations are brilliant for this kind of thing. Everything you have so far is on the correct path.
// Controller
public function index()
{
$games = Game::all();
return view('games.index', compact('games'));
}
// View
#foreach($games as $game)
{{ $game->name }}
#if(count($game->awards) > 0)
// Game has some awards, lets loop through them
#foreach($game->awards as $award)
{{ $award->name }}
#endforeach
#endif
#endforeach
Using the relation you've setup in your Game model you can instantly access the related data from other tables. Now each time you call $game->awards it will query the database, however using Laravel's Eager Loading you can pull all this information out at the same time rather than on demand.
// Controller
public function index()
{
$games = Game::with('awards')->get();
return view('games.index', compact('games'));
}
and by doing the exact same thing in the view you're no longer running a new query each time you want to get a games awards as they've already be fetched from the database. More on eager loading here http://laravel.com/docs/5.0/eloquent#eager-loading
In my previous question, I got to perform a raw SQL query.
I've declared an public function in my controller:
public function deaths()
{
$getdeaths = DB::statement('SELECT * FROM player_deaths ORDER BY time DESC LIMIT 10');
return View::make('main.latestdeaths')->with('getdeaths', $getdeaths);
}
When retrieving data, I want to display players name, so inside the view in a foreach, is tried to run a SQL query.
#foreach($getdeaths as $getdeath)
<tr>
<? $name = DB::select( DB::raw('SELECT name FROM players WHERE id = '$getdeath->player_id'') ) ?>
<td>{{ $getdeath->player_id }}</td>
<td></td>
<td></td>
</tr>
#endforeach
When I try to echo $name, the variable is not defined.
Can I parse it some other way?
here you go :
$getDeaths = DB::table('player_deaths')->orderBy('time','desc')->take(10)->get();
return View::make('main.latestdeaths')->with('getDeaths', $getDeaths);
That will give you an object of all your player_deaths ordered by time.
You are using DB::select so you have to do a get() to retrieve the records, by the way, is not good make SQL queries on the views, don't respect the MVC arquitecture pattern.
look at view composers. basically a filter or class method that gets called when certain view names are rendered and assigns a view variable automatically.
tell the composer to run the query and set the deaths variable for the views you want the information available in.
you can then loop over the variable as if you had assigned it in your view.