Laravel 5.0 Undefined variable result - php

I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:
Routes
Route::get('/shopsales', 'shopsalescontroller#index');
Controller
class shopsalescontroller extends Controller
{
public function index()
{
$storeNum = request('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',compact('result'));
}
}
shopsales view
<section>
<center><h1><STRONG>Query Data</STRONG></h1></center>
<ul>
#foreach ($result as $results)
<li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
</li>
<br>
#endforeach
</ul>
</section>
I have used the exact code for the query that is working, struggling to understand why this is not.

try this
in App\Route
Route::resource('/shopsales','ShopSalecontroller');
This routes the following actions: index, create, store, show, edit, update and destroy.
add this function to shopsales model
public function scopeNumber($query, $number){
if($number != null){
$query->where('storeNumber','=', "$number");
}
}
in ShopSalesController index:
public function index(Request $request){
$result = shopsales::get()->number($request->storeNumber)->all();
return view('shopsales',compact('result'));
}
Remember to have in the index view a form with the field storeNumber

public function index()
{
$storeNum = request('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',['result'=>compact('result')]);
}
Change your controller code like above.
Also check if $result is not null.

Try something like this
public function storeCheckout(Request $request) {
$storeNum=$request->get('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',compact('result'));
}

Solved, though sorry for wasting your time, some of my views should of had a capital letter in them, fixed that cleared the view cache and now i have the queries.

in action index
change var $result to $results
in view index
#foreach ($results as $result)
#endforeach

Related

How to use count number of rows and print value in view file laravel 5.4?

app/http/controller/FirstController.php
public function delhi_property()
{
$sql = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
return view('index',['results'=>$sql]);
}
resources/views/index.blade.php
<h3>({{ $results->count() }}) Properties</h3>
routes/web.php
Route::get('/','FirstController#delhi_property');
I am new in laravel 5.4 Here, what am I doing I simply run a query as I mention above in my Controller and want to print numbers of rows in my view file but when I check it shows an error i.e.
Undefined variable: result (View: D:\xampp\htdocs\real_estate\resources\views\index.blade.php)
So how can I solve this problem? Please help me.
You are returning the query result as "results", so in the view you need to access it as "$results".
In the error it says undefined variable result.
There is no "s" in it.
So refer to the code line that error returns and check whether variable naming is correct.
In controller:
public function delhi_property()
{
$data = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
return view('index', compact('data'));
}
In blade file:
<h3>( {{ $data->count() }} ) Properties</h3>
OR
<h3>( {{ count($data) }} ) Properties</h3>
To count all rows in a query is a function for example:
count($results);
I am modifying your query a bit, will achieve the same result efficiently
public function delhi_property()
{
$cityResults = DB::table('property')->whereIn('city', ['Delhi','New Delhi'])->get();
return view('index',compact('cityResults'));
}
In your view you can access the count as following:
<h3>{{ $cityResults->count() }} Properties</h3>
In case you are using this to calculate and display the total count on a Bootstrap badge, try the following directly in the sidebar view:
<span class="badge badge-info right">{{ DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->count() }}</span>
You can use larave's default function to count rows like example given below.
public function delhi_property()
{
$result = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
$total_result = count($result);
return view('index',compact(['result','total_result']));
}
In view you can print number of rows in variable $result.

Showing a message if data is null laravel

I want to show a message in my blade where if my address, name or number is null say this fields are empty please fill them up, if there are filled already, just don't display anything.
Currrently I did like this, but in the blade.php. Previously I had already asked something similar but this time I want to show a message. I tried following the question that I asked but for some reason it keep showing the message "please fill them up" even though my data contain values inside the database.
Redirect to page when value is null in another table laravel
Here is my code:
<?php
$additional_info = DB::table('additional_informations')
->whereNull('address')
->orWhereNull('name')
->orWhereNull('number')
->get();
if( $additional_info->count())
echo "test";
?>
For a route like this :
Route::get('/userAddInfo/{id}/AddInfo','VerificationController#AddInfo');
You can get the user id in the method as parameter then use it in the query like this :
public function AddInfo($id) {
$additional_info = DB::table('additional_informations')
->where('user_id', $id)
->where(function ($query) {
$query->whereNull('EC_address')
->orWhereNull('EC_name')
->orWhereNull('EC_number');
})
->get();
return view('AddVerificationInfo',compact('id','additional_info'));
}
And in the view :
#if($additional_info->count())
"Please fill this up"
#endif
Assuming you are working on the index.blade.php page here how it goes
InformationController - Controller
public function index($id) {
$additional_info = DB::table('additional_informations')
->whereNull('address')
->orWhereNull('name')
->orWhereNull('number')
->where('id', '=', $id)
->first();
return view('index', compact('id','additional_info '));
}
index.blade.php - View
<div>
#if(count($additional_info) > 0)
Here are the rows that has Null values: <br/>
Please go back and fill up the values of
#if($additional_info->EC_name == null)
EC_name
#endif
#if($additional_info->EC_relationship== null)
EC_relationship
#endif
#if($additional_info->EC_address== null)
EC_address
#endif
// and so on. There is a shorter way but I'm not in my laptop right now. But this should work fine
#else
{{ $id }} has no Null data found
#endif
</div>
Tell me if you need more help on this part. Cheers
/* In controller */
$additional_info = DB::table('additional_informations')
->whereNull('address')
->orWhereNull('name')
->orWhereNull('number')
->get()->toArray(); // to convert output into array
/* In view (blade template) */
#if(!empty($additional_info))
echo "<pre>";
print_r($additional_info);
#else
echo "No data found";
#endif
You should move your logic into a controller, then pass a variable like $noAdditionalInfo to the view
Then you can use blade tags:
#if($noAdditionalInfo)
<!-- html goes here -->
#endIf

php - How to show only last word on table Laravel

Hello im really newbie on Laravel. So I really need some help.
I need help on my table. The view from my table contains App\Models\Store and App\Models\Product, but I just want every App\Models\Store and App\Models\ Product to only show as Store and Product
This is my code on my table
<td>
<label>
<a href="{!! route('reports.tolink', [$report->id]) !!}" target="_blank">
{!! $report->reportable_type !!}
</a>
</label>
</td>
$report->reportbale_type it contains App\Models\Store and App\Models\Product
and this is my Controller
public function toLink($id)
{
$report = $this->reportRepository->findWithoutFail($id);
//get Store Name
$name = Store::where('id','=',$report->reportable_id)->pluck('name')->all();
$storename = $name[0];
//get Store ID
$idstore = Store::where('id','=',$report->reportable_id)->pluck('id')->all();
$storeid = $idstore[0];
if(empty($report))
{
Flash::error('Report not found');
return redirect(route('reports.index'));
}
$report_type = class_basename($report->reportable_type);
return redirect(env('FRONTEND_URL') ."/".str_slug($report_type)."/$storeid/".str_slug($storename));
}
and this is my table
There are few ways you can do this.
You can use Reflection to get the short name
(new \ReflectionClass($report->reportable_type))->getShortName()
You can explode by \ and get the last item
array_pop(explode('\\', $report->reportable_type))
Using substr and strrpos
substr($report->reportable_type, strrpos($report->reportable_type, '\\') + 1)
You can use one of the above methods and add a getter to your Report model.
public function getReportableTypeNameAttribute()
{
return (new \ReflectionClass($this->reportable_type))->getShortName();
}
which will allow you to call $report->reportable_type_name in your views.

How To use Database as a variable with blade template in laravel?

i'm new in laravel, i have some problem to make database as variable to be shown on blade template,
example i want to get any data from database :
{{$get = DB::table('perangkat')->get()}}
then:
#foreach ($get as $got)
{{$got->jabatan}}
#endforeach
if the result of the $got->jabatan is kepala, But i want the result is Change To "Kepala Desa", How can i do ??
Please Help Mee ...
Write database related stuff in model or controller in a method and pass that value to view. It will be very neat and clear
public function getData(){
$get = DB::table('perangkat')->get();
return view('myblade', ['data' => $get]);
}
In your view
#foreach ($data as $got)
{{$got->jabatan}} Desa
#endforeach
Also can you update where you get Desa .so i can update answer according to that.
Updated
you keep different roles in array and do some think like this
<?php
$role=['a'=>'operator','b'=>'admin'] ; ?>
#foreach ($data as $got)
<?php $result = isset($role[$got->jabatan]) ? $role[$got->jabatan] : null; ?>
{{$result}}
#endforeach
company.php
function showdata{
$sql= "this syntax sql";
}
//show data
$company = new company();
#foreach ($company->showdata() as $got)
{{$got->jabatan}}
#endforeach

laravel5.1 retrieve nested relation using eloquent hasOne() (one to one relation)

My table design is:
users: | id |username | ... |
tickets: | id | supp_id | ... |
ticket_replies: | id | ticket_id | user_id |
My controllers look like:
user:
public function tickets()
{
return $this->hasMany('App\ticket');
}
ticket:
public function ticket_replie()
{
return $this->hasMany('App\ticket_replie');
}
public function supporter()
{
return $this->hasOne('App\User', 'id','supp_id');
}
My controller looks like this:
$tickets = Auth::user()->tickets()->orderBy('status', 'desc')->paginate(2);
return view('protected.ticketsList', [
'tickets' => $tickets,
]);
In my view I use:
supporter: {{ $ticket['supporter']->username }}
Any idea where I do wrong? I get all the time this error:
Trying to get property of non-object
In my point of view the relation between the tables itself is done correctly.
When I use for example {{ dd($ticket) }} in my view I get an object with all the items I need:
So first of all, trying to access the function public function supporter() on your Ticket model cannot be done using array syntax. Change:
{{ $ticket['supporter']->username }}
to:
{{ $ticket->supporter()->first()->username }}
If you don't want to use the ->first() you can do one of two things. Modify your existing query to include the ->with("supporter") syntax:
$tickets = Auth::user()
->tickets()
->with("supporter")
->orderBy('status', 'desc')
->paginate(2);
And access the supporter from the view like so:
{{ $ticket->supporter->username }}
// Notice how supporter is no longer a `method` ->supporter() but a `property` ->supporter
Or you can modify your relationship to include the closer ->first():
public function supporter(){
return $this->hasOne('App\User', 'id','supp_id')->first();
}
And then access it like so:
{{ $ticket->supporter()->username }}
// Notice you no longer need `->first()`
So, as you can see, there are multiple ways to access a Ticket's Supporter. Please note that you can't really combine these options; modifying the function to include ->first() and then trying to use ->with() will return an error, so pick one or the other.
Hope that helps!

Categories