Property [kodeSparepart] does not exist on this collection instance - laravel

I want to get all of the data from sparepart database using all() function, then use foreach in view to access the data, but I keep get that error. It works fine when I use the same method for other view blade.
Controller
public function LaporanSisaStok(Request $request) {
if($request->kode == "")
{
$spareparts = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $spareparts]);
}
else {
$query = DB::table("historisparepart")->select(DB::raw('EXTRACT(MONTH FROM tanggal) AS Bulan, SUM(jumlah) as Sisa'))
->where('kodeSparepart', $request->kode)
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggal)'))
->get();
return view('printPreview/sisaStok', ['data'=>$query]);
}
}
View
<form method="POST" action="{{ route('laporan.sisaStok') }}" enctype="multipart/form-data">
#csrf
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
</select>
</div>
<br>
<button type="submit" class="btn btn-info"><i class="oi oi-task"></i> Cari </button>

You aren't looping through anything. You need to give the foreach() method a variable from your spareparts collection. I think it might help you avoid confusion, to name the collection variables plural:
In your controller:
$spareparts = Sparepart::all();
return view('laporan/sisaStok', compact('spareparts'));
Then, most importantly, you need to tell foreach what it should produce. In your view, change:
foreach($sparepart)
to
#foreach($spareparts as $sparepart)
Don't forget you are in blade, so use the # before the foreach. Then, assuming you actually have a property on the spareparts model called kodeSparepart, this should work fine.

This is not a looping syntax in the laravel view
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
It should be like this
#foreach($spareparts as $sparepart)
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
#endforeach
And another problem is you are passing the data in wrong way. It should be like this
return view('printPreview/sisaStok', ['spareparts'=>$query]);

You shoud use the plural of your dtb name to loop over the values so your 'sparepart' variable should change to 'spareparts'
$sparepart = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $sparepart]);
In your view change your loop to the new variable and loop using your current variable, so your view shoul look like this:
View
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
#foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
#endforeach
</select>
</div>

Related

Laravel Livewire: Input select, default option selected

I am trying to fetch country codes from my database and trying to get the default value via IP address. It works just as I want for a second but then I don't know what happens but it refreshes itself and scrolls to the first option instead of the selected option.
Livewire Controller Component
use App\Models\CountryCodes;
use Livewire\Component;
use Location;
class TestCountry extends Component
{
public $iso;
public $country_codes;
public $country_code;
public function mount()
{
$iso=Location::get('ip');
$this->iso=$iso->countryCode;
}
public function render()
{
return view('livewire.test-country',[
$this->country_codes = CountryCodes::select('nicename','iso','phonecode')->get()->toArray()
]);
}
}
Livewire Blade Component
<select wire:model.lazy="country_code" name="country_code" id="country_code" class="form-control" required>
#foreach($country_codes as $country_code)
<option value="{!! $country_code['iso'] !!}"
wire:key="{{$country_code['iso']}}"
{{ $country_code['iso'] == $iso ? 'selected' : ''}}>
{!! $country_code['iso'] !!} +{!! $country_code['phonecode'] !!}
</option>
#endforeach
</select>
This code does select my default option but it changes and moves to the first option automatically. Am I doing something wrong here?
I believe what is happening is, $iso is set correctly, but the select is bound to the $country_code property, not $iso, so briefly, the check you have works, but because $country_code doesn't have a value, the selected option is lost when the state is updated by Livewire.
TLDR: Livewire is checking whatever is in the wire:model attribute, so the class property must be set for it to work.
I would try something like this:
public function mount()
{
$iso = Location::get('ip');
$this->iso = $iso->countryCode;
// set $country_code to $iso
$this->country_code = $this->iso;
}
I believe Livewire will intelligently select the state, so I think the selected check can be removed:
<select wire:model.lazy="country_code" name="country_code" id="country_code" class="form-control" required>
#foreach($country_codes as $country_code)
<option
value="{!! $country_code['iso'] !!}"
wire:key="{{$country_code['iso']}}"
>
{!! $country_code['iso'] !!} +{!! $country_code['phonecode'] !!}
</option>
#endforeach
</select>
Also, any reason for using {!! !!} tags in the view rather than just {{ }}?

Laravel Livewire: Passing option value onChange of Select input

I am trying to pass a value from the <option> of my <select> input to my livewire controller component and echo the value.
Livewire Blade View Component:
{!! Form::select('goals',$goals_plucked,null,[
'placeholder' => trans('classes.backend.forms.select_goals'),
'class' => 'custom-select',
'id' => 'goals',
'wire:change' => "goals(this.val)",
]) !!}
This get's me an output of null in my Livewire Controller Component
Livewire Controller Component
public $goals;
public function goals($goals)
{
dd($goals);
}
After watching some tutorials. I also tried using 'wire:change' => "goals($event.target.value)", which gave me an error of Undefined variable $event, obviously because it was not defined in main controller. I am not sure what am I doing wrong here.
What I am trying to do: Trying to create a flow just like select country then select state and then select city. via livewire. Before selecting a country the inputs of the select state and city won't be visible
I tried below code and it worked for me well. Just had to make sure I use normal html form inputs and dynamically add options to it by foreach loop. Also used mount() function for getting getting values and id's for select dropdowns.
Livewire Blade View Component:
<select wire:model="goal" name="goal" class="form-control" required>
<option value="">
{!! trans('classes.backend.forms.select_goals') !!}
</option>
#foreach ($goals as $goal)
<option value="{{ $goal->id }}">{{ $goal->goals }}</option>
#endforeach
</select>
Livewire controller component
public $goals;
public $goal;
public function mount()
{
$this->goals = Goals::all()->isActive();
}
public function updatedGoal($value)
{
dd($value);
}
just give wire:model="variable_name" to select in front end.
and in livewire controller there should be a public variable with same name. it will automatically get the value on select value change.
below is the example of same
<select class="custom-select border-0 shadow-none" id="enquiry_for" wire:model="enquiry_for">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>

Controller method does not exist. But actually exists. Not passing value with request neither

This is just driving me crazy. A lot of research, testing, double checking the rotes with artisan, and even a new clean laravel installation to make sure my routes are working fine, and i keep getting the error that my method does not exist and it does not matter if i change namespace, or the method name.
My route web.php
Route::get('/view1', function () {
return view('view1');
});
Route::post('/view1results', [
"uses" => 'MyController#MyMethod',
"as" => 'MySearch'
]);
Route::get('/', function () {
return view('welcome');
});
My view1:
<label class="myfilters">filters:</label>
<form action="{{ route('MySearch') }}" method="POST">
{{ csrf_field() }}
<select class="myfilters" id="filter1" name="filter1">
<option value=""> -- Select Something --</option>
<option value=""> option 1 </option>
<option value=""> option 2 </option>
</select>
<input type="submit"></input>
</form>
My Controller
<?php
use Input;
use app\SubSectorsBPIsData;
use App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SubSectorsBPIsDataController extends Controller
{
public function MyMethod(Request $request)
{
$valueselected= $request->input('filter1');
return view('view1results', ['filter1' => $valueselected]);
}
}
Error is: BadMethodCallException
Method App\Http\Controllers\MyController::MyMethod does not exist.
And as you can see the method called: MyMethod is there.
It does not matter what i put on my view1results, i was just trying a simple {{echo $valueselected}};
Also tried to add another different view to pass data from my controller. In my web.php:
Route::get('/viewresults2', function () {
return view('viewresults2');
});
And then in my controller
return view('viewresults2', ['filter1' => $valueselected]);
It gives me a blank page.
Even if with this other approach it's recognizing the method, it's now returning any view nor value: If i just bypass the view and try to:
return $selectedTrend;
Still get a blank page.
It's not recognizing the method and it's not passing any value from the select.
Whats going on please? :(
Update
One more thing: my website is file structure is:
www.mydomain.net/software/public/view1
And after submiting the form redirects to:
www.mydomain.net/software/public/view1results
Just adding it up so you could help me better with the route, since i think that's where the problem is and i couldn't figure out what route to use on my action form.
Turns out it was a silly mistake (like always). In my view i had this code for the dropdown:
<select class="myfilters" id="filter1" name="filter1">
<option value=""> -- Select Something --</option>
<option value=""> option 1 </option>
<option value=""> option 2 </option>
</select>
Notice the <option value=""> does not have any value and controller needs to know which value to get. So do this instead:
<option value="option1"> option1 </option>
<option value="option2"> opion2 </option>
And controller will get the value. All the rest it's set properly.
Hope it helps another newbie in
Laravel 5.7

How to show selected value from database in dropdown using Laravel?

I want to show selected value from database into dropdown list on page load.
My controller index function is :
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
My dropdown in profile_update.blade.php is
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach</select>
This is a example of how I do this:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
#foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
#endforeach
</select>
In order to understand it fully you will need basics of laravel (MVC),
Let suppose, you have controller. In my case I made a separate table for drop down values.
My Approach --- Separate table for values of drop down, you can try different approach but my explanation was mainly focused on concept.
Note: PersonInfo is model, sampleType is model of my drop down values and don't forget to make a route for the controller.
ExampleController{
public funtion getValues($id){
/*
I am fetching information of a single row from the database by id and
then passing it to the view. The $id to the function came from the
request by your view/form.
I also fetched the values of drop down from the separate table
of database and passed it to the exampleView.
*/
$selectedValue=PersonInfo::findOrFail($id);
$sampleType=SampletypePicker::all(); //model for fetching all values of drop down
return view('exampleView',compact('selectedValue','sampleType));
}
}
So, in the above controller I fetched all values and passed it to the ExampleView. Now in your View file you have to work likewise.
exampleView.blade.php add the below code
<?php $options=$selectedValue->sample_type ?> //note take the value from the database which stored for the individual record and match it with the selected one.
<select class="form-control" name="test">
<option>Select Test Type</option>
#foreach ($sampleType as $value)
<option value="{{ $value->sample_type }}" {{ ( $value->sample_type == $options) ? 'selected' : '' }}>
{{ $value->sample_type }}
</option>
#endforeach
</select>
It is one of the best approach when you want to add dynamic values to the drop down. I mean if you want to add more values to the select tag options then this is the best approach.
Another Approach - take the idea
<?php $months = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); ?>
<?php $options=$patient_data->month ?>
#if($patient_data->month)
<select id="expiry_month" name="month" class="form-control-sm">
#foreach($months as $month)
<option value="{{$month}}" {{($month==$options)? 'selected':'' }}>{{$month}}</option>
#endforeach
</select>
#endif
<span class="select-icon"><i class="zmdi zmdi-chevron-down"></i></span>
</div>
OUTPUT of ABOVE CODE
#Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd e.g.
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
Well, simply if anyone still looking for this, here is the simple way to select items for dropdown from database to blade view
$users = Users::pluck('name', 'id');
$selectedID = 2;
return view('users.edit', compact('id', 'users'));
add this in the controller function before rendering the view
and in the blade view, simply use this variable as foreach loop as
<select name="user_id" class="form-control" id="exampleFormControlSelect1">
#foreach ($users as $key => $value)
<option value="{{ $key }}" {{ ($key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
#endforeach
</select>
if you don't want to select all users from DB, you can use where condition before pluck condition as
$users = Users::where('status', 1)->pluck('name', 'id');
works with Laravel 8 and Laravel6

Why it appears the erro Non-static method should not be called statically in this context?

Im trying to use this package " dannyvankooten/laravel-vat" to load a select menu with the countries and then validate the vat number inserted in the input type text.
So I have this in a form:
<div class="form-group font-size-sm">
<select class="form-control" name="country" id="country">
#foreach($countries as $country)
<option value="{{$country}}">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group font-size-sm">
<label for="vat" class="text-gray">VAT</label>
<input type="text" id="vat" name="vat" class="form-control" value="">
</div>
In the RegistrationController I have in a method this to return the $countries to the view to the select menu:
$countries = Countries::all();
But it appears:
Non-static method DvK\Laravel\Vat\Countries::all() should not be called statically
Do you know why?
In your specific case (laravel & facades), it's because you have imported the wrong class in your controller.
You need to replace
use DvK\Laravel\Vat\Countries;
with
use DvK\Laravel\Vat\Facades\Countries;
like shown in the readme # https://github.com/dannyvankooten/laravel-vat
The facade is what provides the static accessor e.g. Countries::all()
all is not a static method in the Countries class. You should first create an instance of Countries and then call its all method:
$countries = new Countries();
$allCountries = $countries->all();
return view('congress.registration', ['countries' => $allCountries]);

Resources