ErrorException Undefined property stdClass::$Start - laravel

I ran into an error while fetching data from my goals table. I'm trying to display all the tables data using foreach loop. But I can't due to unknown property error. I'm still learning laravel so kindly help.
Here's my controller code.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\goal;
use DB;
class GoalController extends Controller
{
public function postAddGoal(Request $request){
$this->validate($request, [
'goal'=>'required',
'checklist'=>'required'
]);
$goal_name=$request['goal'];
$checklist=$request['checklist'];
$goal = new goal();
$goal->goal=$goal_name;
$goal->checklist=$checklist;
$goal->status='PENDING';
$goal->start='1002-1-1';
$goal->finish='1002-1-1';
$goal->remarks="NULL";
$goal->score="0";
$goal->save();
redirect()->route('seegoals');
}
public function getGoals(){
$goals = DB::select(' select * from goals ');
if(empty($goals)){
$goals=0;
}
return view('/index', ['goals'=>$goals] );
}
}
Then my index.blade.php code
#foreach($goals as $goal)
<tr>
<th colspan="3">{{ $goal->goal }}</th>
<th colspan="7">{{$goal->checklist}}</th>
<th colspan="2">{{$goal->status}}</th>
<th colspan="2">{{$goal->Start}}</th>
<th colspan="2">{{$goal->finish}}</th>
<th colspan="2">{{$goal->score}}</th>
<th colspan="7">{{$goal->remarks}}</th>
</tr>
#endforeach
I get an exception:
(2/2) ErrorException Undefined property: stdClass::$Start (View:
/opt/lampp/htdocs/ToDo/resources/views/index.blade.php)
What could be the problem with my code?

There is misleading of first letter. Change Start to start
<th colspan="2">{{$goal->start}}</th>
And for good practice in controller change code to
$goals = DB::select('select `checklist`, `status`, `start`, `finish`, `score`, `remarks` from goals');
You must be get in db only needed info
also delete this part
if (empty($goals)) {
$goals = 0;
}
For not get error when goals is empty

Related

Laravel Retrieve Parameter to function view

Laravel 7: I'm building a report view using Maathwebsite.
My function looks like this.
public function view(): View
{
return view('dash._exportSales' ['datas' => Sales::where('store_id', 30)->get()]);
}
This will output an excel file with all the information, as you can see I'm using a basic settings, so far so good, the problem that I have is that I have no idea how to give a parameter, the number 30 is the ID but how can I retrieve that number?
my route looks like this
Route::get('sales/export_sales', 'SaleController#export')->name('export.sales');
if I use: Route::get('lots/export_sales/{id}', 'SaleController#export')->name('export.sales');
doesn't do anything still can't get the ID in to my ExportController which looks like this:
class SaleExport implements FromView
{
public function view(): View
{
return view('dash._exportSales' ['datas' => Sales::where('store_id', 30)->get()]);
}
}
If add a declare a private, const, public or protected variable it does nothing nor can set or retrieve a value...
So how can I retrieve that ID #?
Export is on my SalesController.php, the above class is on my SalesExport.php
SalesExport looks like this:
public function export($id)
{
$name = 'store_' . $id . '.xlsx';
return Excel::download(new SaleExport(), $name);
}
My routes looks like this.
Route::get('sales/export_sales/{id}', SaleController#export')->name('export.sales');
Route::get('sales', 'SaleController#sales')->name('sales');
you can do this by following way
Route::get('sales/export_sales/{id}', 'SaleController#export')->name('export.sales');
and your method should be like this
public function view($id)
{
return view('dash._exportSales' ['datas' => Sales::where('store_id', $id)->get()]);
}
The whole problem was that I never use __construct() on my controller.
So, here is the full flow
Laravel 7+
maatwebsite/excel
First the view:
<table>
<thead>
<tr>
<th colspan="4">Report {{ date('Y-m-d H:i:s') }} | Store: {{ $datas->store_name }}</th>
</tr>
<tr>
<th style="font-weight: bold; text-align: center; vertical-align: middle;">Sale #</th>
<th style="font-weight: bold; text-align: center; vertical-align: middle;">Amount</th>
<th style="font-weight: bold; text-align: center; vertical-align: middle;">Date</th>
<th style="font-weight: bold; text-align: center; vertical-align: middle;"></th>
</tr>
</thead>
<tbody>
#foreach($datas->items as $data)
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->amount }}</td>
<td>{{ $data->date }}</td>
<th></th>
</tr>
#endforeach
</tbody>
</table>
It has more columns but lets keep it simple.
in app create a new folder app/Exports, inside SaleExport.php
Inside that file use it like this:
namespace App\Exports;
use App\Sale;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
//use Illuminate\Support\Facades\DB;
class SaleExport implements FromView
{
protected $id;
public function __construct($id)
{
$this->id = $id;
}
public function view(): View
{
return view('dash._exportsales', ['datas' => Sales::where('store_id', $this->id)->get()]);
}
}
On this file was the problem there was no __contruct(); but I didn't notice because it was been called from another controller with __construct(); so my "view controller looks like this.
namespace App\Http\Controllers\Dash;
use App\Order;
use App\Sale;
//use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use App\Exports\SaleExport;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class ReportController extends Controller
{
public function index(Request $resquest)
{
// This is just a basic index nothing fancy
// I could avoid this 'where' but client only want this status...
$query = Order::where('status', 1);
// a few IF's to build query with orWhere();, limit();... etc
// here is where I could add the 'status' and set it as filter...
$data = $query->paginate($limit);
return view('dash.order_list', compact('data');
}
// Here is where we call our Export
public function export($id)
{
$name = 'sales_' . $id . '.xlsx'; // Set the same for the file
return Excel::download(new SaleExport($id), $name);
}
}
Then you can just called in your router Route::get('sales', 'SaleController#export')->name('sales'); and thats it!, you get a full report using a blade view in to your excel software... problem was is that I wasn't using __construct(); on my FromView controller
Reference about this method can be found here: docs.laravel-excel, problem on my part was that the construct, without a construct can't use parameters, now that is been set I can use parameters and do more filters for a better report.
Thanks to #lagbox who reminded me of that.

Invalid argument supplied for foreach() on laravel

I have like error message : Invalid argument supplied for foreach()
For my method index() I have this:
public function index(Request $request)
{
if(\Auth::user()->hasRole('admin')){
if($request->has('search'))
$remarks = Remark::orderBy('instruction', 'asc')->where('instruction','like','%'.$request->input('search').'%');
else
$remarks = Remark::all();
}else{
\Auth::user()->load('remarks');
$remarks = \Auth::user()->remarks;
}
return view('admin.remarks.index', compact('remarks'));
}
Concerning my index.blade.php I have my loop "for" which is like this:
<th>Instruction</th>
<th>Description</th>
<th>Date seance</th>
<th>Name Candidate</th>
<th>Email</th>
</tr>
</thead>
#foreach($remarks as $remark)
<tr>
<td> {{$remark->instruction}}</td>
<td> {{$remark->description}}</td>
<td> {{$remark->seances->date_seance}}</td>
<td> {{$remark->seances()->first()->candidates->name}}</td>
<td> {{$remark->seances()->first()->candidates->email}}</td>
<td>
Do you have an idea of my problem please? I don't understand ??
You need to call get() after the Eloquent Query Builder to fetch the data from the database. Unless it's an Eloquent Query Builder Object (which is not iterable, so cannot be used in a for loop).
The function get() will return the result as a Laravel Collection (which is iterable).
$remarks = Remark::orderBy('instruction', 'asc')
->where('instruction','like','%'.$request->input('search').'%')
->get();
you should querying from database not from session and don't forgot define relations on users model :
on users model:
public function remarks(){
return $this->hasMany(Remark:class)
}
on your controller
public function index(Request $request)
{
if(\Auth::user()->hasRole('admin')){
if($request->has('search'))
$remarks = Remark::orderBy('instruction', 'asc')->where('instruction','like','%'.$request->input('search').'%');
else
$remarks = Remark::all();
}else{
$user = Users::find(Auth::id());
$remarks=$user->remarks
}
return view('admin.remarks.index', compact('remarks'));
}

Unexpected data \r\n with Carbon laravel

I'm trying to get all of the students from a table using "Student::all()". I don't even have carbon in this function. It's not getting students by date or anything. When i try to run the function, I get the error shown in the picture. It's pointing to a carbon file in the vendor folder but I don't know what to change. The data from the database pulls fine in every other function of the program, just not this one exact thing. When I die/dump my function call,I get the students list just fine. Something is simply irritating Carbon for no apparent reason. If I use a carbon parameter, it works, the function doesn't stall, but it does not return the correct data even though the field in the database holds that info. Why would a line break be causing this issue?
This function does not produce the error, but it does not result in the correct data.
public function exportRoster(){
$students = Student::whereDate('updated_at', Carbon::today())->get();
$pdf = PDF::loadView('printRoster', compact('students'), [], ['orientation' => 'L']);
return $pdf->stream('roster'.Carbon::today().'.pdf');
}
This function would obviously have the right data, but it produces the error of "Unexpected data".
public function exportRoster(){
$students = Student::all();
$pdf = PDF::loadView('printRoster', compact('students'), [], ['orientation' => 'L']);
return $pdf->stream('roster.pdf');
}
Just in case it helps, i've also included a screen shot of my database
Here is the table i'm using with my students variable in the printRoster view. If I remove this table, all queries work.
<table style="width:100%;">
<tr>
<th align = "left">Student Name</th>
<th align = "left">Student ID</th>
<th align = "left">District</th>
<th align = "left">School</th>
<th align = "left">Test Date/Time</th>
<th align = "left">Vision</th>
<th align = "left">Color</th>
<th>Nurse</th>
</tr>
#foreach($students as $student)
#php
$grade = array('20/40', '20/50', '20/60', '20/80', '20/100', '20/200', '20/400');
#endphp
<tr>
<td>{{$student->fname.' '.$student->lname}}</td>
<td>{{$student->student_number}}</td>
<td>{{$student->district}}</td>
<td>{{$student->school}}</td>
<td>{{$student->updated_at}}</td>
#if(in_array($student->od_dist, $grade) || in_array($student->os_dist, $grade) || in_array($student->ou_dist, $grade))
<td>Failed</td>
#else
<td>
Passed
</td>
#endif
<td>{{$student->ou_color}}</td>
<td>{{$student->nurse}}</td>
</tr>
#endforeach
</table>
The updated_at column is a timestamp so maybe you need to convert it in a raw date in order to show it. Please try if it works
#foreach($students as $student)
#php
$grade = array('20/40', '20/50', '20/60', '20/80', '20/100', '20/200', '20/400');
#endphp
<tr>
<td>{{$student->fname.' '.$student->lname}}</td>
<td>{{$student->student_number}}</td>
<td>{{$student->district}}</td>
<td>{{$student->school}}</td>
<td>{{date('Y-m-d H:i:s', strtotime($student->updated_at))}}</td>
#if(in_array($student->od_dist, $grade) || in_array($student->os_dist, $grade) || in_array($student->ou_dist, $grade))
<td>Failed</td>
#else
<td>
Passed
</td>
#endif
<td>{{$student->ou_color}}</td>
<td>{{$student->nurse}}</td>
</tr>
#endforeach
Edit
public function exportRoster(){
$students = Student::all();
$pdf = PDF::loadView('printRoster', $students);
$pdf->setPaper('A4', 'landscape');
return $pdf->stream('roster.pdf');
}

how to display search result in laravel

i can not show search result using laravel. below is the code for route, controller and views:
route:
Route::resource('search', 'SearchController');
controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
use Redirect;
use Auth;
use DB;
class SearchController extends Controller
{
public function index(Request $request)
{
$order = Order::all();
return view(search.index', compact(search));
}
public function search(Request $request)
{
$search = $request->search;
$order = DB::table('order')
->where('custName','like',"%".$search."%");
return view('search.index',compact('search'));
}
}
view
<form action="search" method="GET">
<input type="text" name="custName" class="form-control" <br>
<button type="submit" class="btn btn-primary">SEARCH</button>
</div>
</div>
<table class="table table-bordered" width="500">
<tr>
<td><font color="white">RESULT :</font></td>
</tr>
#foreach($order as $order)
<tr>
<td>{{ $order->custName }}</td>
<td>{{ $order->orderStatus }}</td>
</tr>
#endforeach
</table>
directory location
c:/xampp/htdocs/web/resources/views/search/index.blade.php
show error
Undefined variable: order (View: c:\xampp\htdocs\web\resources\views\search\index.blade.php)
above is my code to search record in the database. but the result always undefined variable.
how to display the searched result using code above. thank you
In your Controller search method, assign search result to $orders
$orders = DB::table('order')
->where('custName','like',"%".$search."%");
then send it to the view:
return view('search.index',compact('orders'));
and in the view do this:
#foreach($orders as $order)
<tr>
<td>{{ $order->custName }}</td>
<td>{{ $order->orderStatus }}</td>
</tr>
#endforeach
It will solve your problem.
There are some issues with the code you have shared, I try to tell the ones I see.
there is a misspelling in Route::resource where instead of search you coded seearch
as for search method it is not used anywhere by the route you provided. You can see more details on Route::resource for methods and views at this question
now considering that you are loading index.blade.php from the public function index method, the usage of compact is troubled. At this page, you can see how compact and with are different and how to use it. The main problem here is that you are not actually passing the order to your view at all.
The last but not least, it is good practice to name items having a collection of values plurally. For example here the order should change to orders. This would prevent the misuse of it in foreach. In your foreach, the name of the iterating array and the temp variable keeping the data should be different, or otherwise, they would have conflict. Here you have 2 variables called order in the same scope.
for instance i have records :
a
aa
aaa
b
c
d
e
the code show all record no1 until no7.
but now its solved i fixed the code in my controller in index() section as below
public function index()
{
return view('search.index', compact('order'));
}
public function search(Request $request)
{
$search = $request->search;
$order = DB::table('order')->where('custName', 'like', "%".$search."%")->get();
return view('search.result', compact('order'));
}

unserialize object export Excel blade view

I try to export a excel file from a blade view with an unserialize object from a text column in my database but i get an error .
Error:
Call to undefined method Illuminate\Database\Query\Builder::transform()
Here is my controller :
public function ExportExcel($id)
{
$order = Order::find($id);
$order->transform(function ($order , $key){
$order->cart = unserialize($order->cart);
return $order;
});
Excel::create('facture', function($excel) use ($order) {
$excel->sheet('Excel', function($sheet) use ($order) {
$sheet->loadView('cotisation_structure.factureExcelsingle')->with(['order' => $order]);
});
})->export('xls');
}
Here is my blade view :
<html> <body>
<thead>
<tr>
<th>N° Facture</th>
<th>N° licence</th>
<th>Nom</th>
<th>Prénom</th>
<th>Type d'activité</th>
<th>Saison</th>
<th>Mode de paiement</th>
<th>Montant</th>
<th>Date Achat</th>
</tr>
</thead>
<tr>
<td>{{$order->num_facture}}</td>
<td>{{$order['item']->num_licence}}</td>
<td>{{$order['item']->lb_nom}}</td>
<td>{{$order['item']->lb_prenom}}</td>
<td>{{$order['item']->activite_licencie->lb_activite}}</td>
<td>{{$order['item']->saison->lb_saison}}</td>
<td>{{$order->payment_method}}</td>
<td>{{$order['price']}}</td>
<td>{{$order->date_achat}}</td>
</tr>
It seems that Transform methode doesn't work for an object , only for a collection.
Eloquent find method return a single model instance Instead of returning a collection of models.
So transform method only working on collection not on single model instance.
Try this one
public function ExportExcel($id)
{
$order = Order::find($id);
$order->cart = unserialize($order->cart);
Excel::create('facture', function($excel) use ($order) {
$excel->sheet('Excel', function($sheet) use ($order) {
$sheet->loadView('cotisation_structure.factureExcelsingle')->with(['order' => $order]);
});
})->export('xls');
}
Note: Transform function working on collection not on a single object.

Resources