Laravel Retrieve Parameter to function view - laravel

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.

Related

I try to show variable from the controller to blade in laravel but the result is "Undefined Variable"

I try to show variable from the controller to blade in laravel but the result is "Undefined Variable $bedrijven , i tried to not use as bedrijf but with no avail
enter image description here"
The controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Bedrijf;
class Bedrijven extends Controller
{
//
function viewLoad()
{
return Bedrijf::all();
return view ('list',['Bedrijven'=>$data]);
}
}
//
{
//
function account (Request $req)
{
return $req->input();
}
}
The blade file
<html>
<table>
<tr>
<td>Id</td>
<td>bedrijven_id</td>
<td>Body</td>
</tr>
#foreach($bedrijven as $bedrijf)
<tr>
<td>{{$bedrijf['id']}}</td>
<td>{{$bedrijf['bedrijven_id']}}</td>
<td>{{$bedrijf['body']}}</td>
</tr>
#endforeach
</table>
</body>
</html>
</div>
</body>
</html>
the route
Route::get('list', [Bedrijven::class, 'show']);
in your controller there is not a $data variable that's why it shows a error
to fix it try this:
function viewLoad()
{
$data = Bedrijf::all();
return view ('list',['Bedrijven'=>$data]);
}
instead of :
function viewLoad()
{
return Bedrijf::all();
return view ('list',['Bedrijven'=>$data]);
}
Minor spelling mistake and the methods controller does not match the route definition. It is quite easy to use compact, to create the array for the view data.
public function show() {
$bedrijven = Bedrijf::all();
return view ('list', compact('bedrijven'));
}
Now the blade code will match the compacted data.
#foreach($bedrijven as $bedrijf)

Differentiate two views with buttons

I have a view in which I display two data that I take from a table of a DB and next to these data I have two buttons that take me to the same view in which I need to display other things.
What I can't figure out is, how do I differentiate the view AFTER pressing the button?
Here there are the images of the two view:
https://imgur.com/a/i5BcPaw
The code is the following:
Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Device;
use App\Models\DataFromRasp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class DeviceController extends Controller
{
public function index()
{
$data=Device::all();
return view('backend.auth.user.device', compact("data"));
}
public function create()
{
}
public function store(Request $request)
{
}
public function show(Device $deviceID)
{
}
public function edit(Device $device)
{
//
}
public function update(Request $request, Device $device)
{
//
}
public function destroy(Device $device)
{
//
}
/**
* Displays all data present in the table data_from_rasps
*
* The data are all the devices that the raspberry can capture
*/
public function visualizeData()
{
$data=DataFromRasp::paginate(10);
return view('backend.auth.user.dictionary', compact("data"));
}
/**
* Raspberry capture and send the data to the DB and save in another
* table of the same DB the MAC addresses of interest
*/
public function getData(Request $request)
{
$m_data = $request->get('m_data');
$r_data = $request->get('r_data');
DataFromRasp::create(['MAC' => $m_data, 'RSSI' => $r_data]);
if(($m_data == 'C4:A5:DF:24:05:7E') and Device::where('MAC_ADDR', $request->m_data)->doesntExist()){
Device::create(['USERNAME'=>'Device1','MAC_ADDR' => $m_data]);
}
if(($m_data == '70:1C:E7:E4:71:DA') and Device::where('MAC_ADDR', $request->m_data)->doesntExist()){
Device::create(['USERNAME' => 'Device2','MAC_ADDR' => $m_data]);
}
}
public function scan()
{
$process = new Process(['C:\Simone\Università\Tirocinio\laravel-boilerplate-master', 'prova.py']);
$process->run();
if (!$process->isSuccessful()) { throw new ProcessFailedException($process); }
return redirect()->route('dict');
}
public function singleDev(Device $deviceID){
$data = DataFromRasp::select('RSSI', 'created_at')->where('MAC', 'C4:A5:DF:24:05:7E')->get();
$time_array = [];
$rssi_array = [];
$cnt = 0;
foreach($data as $dataItem){
array_push($time_array, $dataItem->created_at->format('H:i:s'));
array_push($rssi_array, $dataItem->RSSI);
}
return view('backend.auth.user.singleDevice', compact("time_array", "rssi_array"));
}
}
View where I select the device:
#extends('backend.layouts.app')
#section('content')
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">USERNAME</th>
<th scope="col">MAC ADDRESS</th>
</tr>
</thead>
<tbody>
#foreach ($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->USERNAME}}</td>
<td>{{$item->MAC_ADDR}}</td>
<td>
Select
</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
Does anyone know how to do this?
Thanks in advance
Try to use this code
Select
Instead of
Select
Updated!
I a little bit didn't get what you trying to achieve, but why didnt your try to add another button next to it, to show another view?
You could create an if statement to determine if one of the buttons is pressed whenever you load the page.
In blade
<button type="submit" name="device_id" value="$item->id">Select</button>
In controller
$data=Device::all();
$singleDevice = Device::where('id', '=', Input::get('device_id'))->first();
if($singleDevice === null)
{
return view('backend.auth.user.device', compact("data"));
}
else
{
$time_array = [];
$rssi_array = [];
$cnt = 0;
foreach($singleDevice as $dataItem){
array_push($time_array, $dataItem->created_at->format('H:i:s'));
array_push($rssi_array, $dataItem->RSSI);
}
return view('backend.auth.user.singleDevice', compact("time_array", "rssi_array"));
}

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'));
}

get the Id from a item grid and save into a variable

I'm working with Laravel 5 to do the following: I have a grid that shows all the clients that the company has, in each row of that grid, there is a button to select that client like this:
Grid of clients
This button sends me to a separate screen that is related directly with the selected client, when this happens, the URL is as follows:
http://sistemaprueba.com/modulos?1
where the value after the question mark represents the value of the id of the selected client. Now, I need to save the value of that id in a variable to be able to use it later, how can I do that?
This is my grid:
<div class="row">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Nombre Cliente</th>
<th>Ingresar</th>
</tr>
</thead>
<tbody>
#foreach($results as $result)
<tr>
<td>{{$result->nombre_cliente}}</td>
<td></i>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
This is the route to the new screem:
Route::get('/modulos', 'HomeController#modulos')->name('modulos');
and my controller looks like this:
class ClientController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$id = \Auth::user()->id;
$results = DB::table('clients')->join('clients_company', 'clients_company.fk_id_client', '=', 'client.id')
->where('clients_company.fk_id_usuar',$id)->get();
return view('clients',compact('results'));
}
public function modulos()
{
return view('modulos');
}
}
You could either change your href to "/modulos/1" and your route and controller to:
// route
Route::get('/modulos/{clientId}', 'HomeController#modulos')->name('modulos');
// controller
public function index($clientId)
{
// Use $clientId
}
Or give a named parameter in your url, like "/modulos?clientId=1", then:
// route (unchanged)
Route::get('/modulos', 'HomeController#modulos')->name('modulos');
// controller
public function index()
{
$clientId = request()->input('clientId');
...
}
Alternatively, you could parse the url with PHP's function parse_url() in your controller, to extract the GET part of the url for you to manipulate. Not the cleanest solution. http://php.net/manual/en/function.parse-url.php
The first method may be preferable for your purpose.

ErrorException Undefined property stdClass::$Start

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

Resources