Laravel 4 query inside view - laravel

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.

Related

Show latest data from row based on custom date_field in laravel

I have 2 tables and I need to show the latest single data from row based based on due_date field in my blade file.
blade
#foreach(Auth::user()->statements->orderBy('due_date','desc')->get() as
$statement)
<p> Your unpaid bill is: {{ $statement->billamount }} </p>
#endforeach
I get this error
Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
(View:...\home.blade.php)
EDIT
I edited the code based on the comments below:
#foreach(Auth::user()->statements()->latest('due_date')->first() as
$statement)
{{ $statement->billamount }} //I only need the latest record to be shown
#endforeach
and it throws this error:
Trying to get property 'billamount' of non-object.
change Auth::user()->statements to Auth::user()->statements()
orderBy is a method of Query Builder. Auth::user()->statements is a collection and Auth::user()->statements is a query builder
to show latest row data only you can use orderBy and first method. example:
Auth::user()->statements()->orderBy('created_at','desc')->first()
another way use latest method:
Auth::user()->statements()->latest('created_at')->first()
#foreach(Auth::user()->statements()->latest('due_date')->first()) as
$statement)
when you look closely there is an extra bracket after first() so remove it and test it
#foreach(Auth::user()->statements()->latest('due_date')->first() as
$statement)
like above
also when using first you dont need to give foreach use get() rather than first()
get() return s a collection while first() returns a single record details

Laravel: How to display OneToMany in a View

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.

ManytoMany relations in Laravel, retrieve data from related tables and display in blade

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.

Laravel eloquent relationship between two table

I have a table notices. Model for this table is Notice.php
In this table I have notice and id column.
I have fetched all notices from notices table and viewed in my view. Here is my controller code for fetching all notices.
public function index()
{
$notice = Notice::orderBy('id','desc')->paginate(5);
return view('teacher.notice')->withNotices($notice));
}
Here is my view code to show all notices.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
#endforeach
Now I want to put two button inside this foreach loop. One is to confirm and another is remove confirmation.
To store this confirmation data I have created another table named notice_confirmed_student and model for this table is noticeConfirmedStudent.php. In this table have three column:
id
student_id
notice_id
If a student click confirm then his id and notice id will be stored in this table. I have done this perfect. But my problem is, in the foreach loop it shows both two button (confirm and remove confirm) at a time. I want to show confirm button if user already not confirmed for this notice. If user already confirmed for that notice then it should show remove confirmation button.
Here I am giving my blade foreach loop again with button for better understanding. Bellow code is not perfect, I have just written those code to understand my question.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
<?php $student_id= "select student_id from notice_confirmed_student where notice_id=$notice->id"; ?>
#if ($student_id == $auth::user()->id)
<button>confirm</button>
#else
<button>Remove Confirmation</button>
#endif
#endforeach
Thanks in advance.
Few things are wrong/incorrect here, to make it clear,
Notice <> User relation is Many-Many and notice_confirmed_student is a pivot table. so user model should have relation,
public function confirmedNotices()
{
return $this->belongsToMany(Notice::class, 'notice_confirmed_student')
}
Then in for each loop you can check like,
if(in_array($notice-id, Auth::user()->confirmedNotices->pluck('id')->all())) {
// user confirmed
} else {
// user not confirmed.
}
if I correctly understand your issue, you need to check if record with given id exists notice_confirmed_student table, and then check in your loop. retrieve the confirmed students with your notices.
$notice = Notice::with('notice_confirmed_student_or_whatever_your_relation_method_called)')->orderBy('id','desc')->paginate(5);
then check in loop, if related attribute is not empty like you do in your view
#if($notice->my_attr && $notice->my_attr->user_id == \Auth::user()->id)
// do stuff
#else
// it doesn't has record
#endif

how to insert multiple data into a single column into the database

Am learning laravel and I encountered a problem saving data into my database from my form.
My instance
when a user tries to make a multiple purchase of products ie.when a user purchases more than one product,i wanted to save the names of products that belongs to the purchase user made into my 'PURCHASES' table having an 'ID' of '1'.
Names of product to be save;
1.productA
2.productB
3.productC
Codes
FORM IN MY VIEW
<input type='hidden' name='product_name'
#foreach($order as $order)
value='{{$order->product_name}}'
#endforeach >
MY purchase CONTROLLER
Saving the names;
$purchase = new Purchase;
$purchase->product_name = $posted['product_name'];
$purchase->save();
When i initiate the function i get an error exception reading 'Trying to get property of non-object' from my view from the line;
#foreach($order as $order)
value='{{$order- >product_name}}'
#endforeach >
How do i go about this problem?
There are a lot of strange things in your code unless I'm reading it wrong, but most likely when you're seeing that error in a view it's because you didn't pass that data into the view. Take this example:
Controller
public function showProducts() {
// assuming $order_array is a set of product IDs that is part of an order
$orders = array('products' => Products::whereIn('id', $order_array);
return View::make('your/view' compact('orders'));
}
I don't quite understand what you're trying to do but passing the object array 'orders' to the view allows you to then call your line:
#foreach($orders as $order)
code here
#endforeach

Resources