Trying to get property 'id' of non-object laravel - laravel

can someone to help me ? i have an error Trying to get property 'id' of non-object laravel while try to show my edit form
this is my controller
public function edit($id)
{
$produk = produk::where('id',$id)->first();
return view('produk.edit',compact('produk'));
}
public function update(Request $request, $id)
{
produk::where('id',$id)
->update([
'nama' => $request->nama,
'id_kategori' => $request->kategori,
'qty' => $request->qty,
'harga_beli' => $request->beli,
'harga_jual' => $request->jual,
]);
return redirect()->route('produk.index');
}
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class produk extends Model
{
protected $guarded = ['id','created_at','updated_at'];
public function kategoris()
{
return $this->hasOne('App\kategori', 'id', 'id_kategori');
}
}
and this is my view
<select class="form-control" name="kategori">
<option value="Pilih Kategori"></option>
#foreach ($produk as $k)
<option value="{{ $k->id }}" #if($produk->id_kategori == $k->id) selected #endif>{{$k->nama}}</option>
#endforeach
</select>

Its because of this
$produk = produk::where('id',$id)->first();
this returns an object not an array of object. thats why your getting an error on your view. Instead use:
$produk = produk::where('id',$id)->get();
to return an array of object.

You are trying to foreach trough product properties, but looks like you need to foreach trough collection of categories.
Add categories to view in controller:
public function edit($id)
{
$produk = produk::find($id);
$kategoris = kategori::all();
return view('produk.edit',compact('produk', 'kategoris'));
}
Iterate trough $kategoris (not $produk) in View:
<select class="form-control" name="id_kategori">
<option value="Pilih Kategori"></option>
#foreach ($kategoris as $kategori)
<option value="{{ $kategori->id }}" #if($produk->id_kategori == $kategori->id) selected #endif>{{$kategori->nama}}</option>
#endforeach
</select>
Also, if foreign key is id_kategori, it is better to use name=id_kategori istead of name=kategori
You don't need relation here, because you compare categories ids with id_kategori attribute. But you should replace hasOne to belongsTo in this case.
public function kategoris()
{
return $this->belongsTo('App\kategori', 'id_kategori');
}

The correct way to obtain the value of the arrangement is
$k["id"] and not $k->id
I tried to obtain a field incorrectly with the array, I received the following array
[{"id": 1, "name": "Ivania", "code": 387}, {"id": 2, "name": "Robert", "code": 389}]
Check the array with a foreach
$users = $request->input('users');
foreach($users as $key => $user)
$person = new Person();
//incorrect form
//$person->id = $user->id
//the correct form
$person->id = $user["id"];
$person->name = $user["name"];
$person->code = $user["code"];
$person-> save ();
}

Related

How to use in_array with belongsToMany relationships?

I'm using belongsToMany with the model Riskarea because I have a pivot table called riskarea_fields which join the Riskfield model among Riskarea:
class Riskarea extends Model
{
use SoftDeletes;
protected $table = 'riskareas';
protected $fillable = [
'name',
'icon',
];
public function riskfields()
{
return $this->belongsToMany(
Riskfield::class,
'riskarea_fields',
'area_id',
'field_id'
);
}
}
In my edit.blade.php I have this code:
#foreach ($riskfields as $rf)
<option value="{{ $rf->id }}" #if (old('active', in_array($riskarea->riskfields, $rf->id))) selected="selected" #endif>
{{ $rf->name }}
</option>
#endforeach
What I'm trying to do is iterate over the riskfields property and select all riskfields options that are within riskarea->riskfields.
Unfortunately I got:
in_array(): Argument #2 ($haystack) must be of type array, int given
This is my edit method:
public function edit(Riskarea $riskarea)
{
return view('riskareas.edit', [
'riskarea' => $riskarea,
'riskfields' => Riskfield::all()
]);
}
any idea?
Since you want to check if each id is present in the associated riskfields, pluck their IDs before hand.
public function edit(Riskarea $riskarea)
{
return view('riskareas.edit', [
'riskarea' => $riskarea,
'selectedRiskfieldIds' => $riskarea->riskfields()->pluck('id')->toArray(),
'riskfields' => Riskfield::all(),
]);
}
Then you can do
#foreach ($riskfields as $rf)
<option value="{{ $rf->id }}" #if (old('active', in_array($rf->id, $selectedRiskfieldIds))) selected="selected" #endif>
{{ $rf->name }}
</option>
#endforeach
You have a small mistake. You are using the in_array() function incorrectly. The syntax is: in_array(mixed $needle, array $haystack) . You've got it backwards. To use the in_array function you also need an array. Therefore, you convert the collection into an array. You do this with the Laravel function toArray().
https://laravel.com/docs/8.x/collections#method-toarray.
Change it in your blade file from:
in_array($riskarea->riskfields, $rf->id)
to
in_array($rf->id, $riskarea->riskfields->toArray())).
in_array(mixed $needle, array $haystack, bool $strict = false): bool
https://www.php.net/manual/de/function.in-array.php

How to store dynamically input name and value both in Controller

This is my blade file where the input type is a radio and I have made name dynamically by giving question id so that I can store in question_id. So How can I store them in Controller.
#foreach($question->answers as $index=> $answer)
<span>
<input type="radio" name="{{$question->id}}" value="{{$answer->id}}" id="answer{{$question->id}}"
class="clickanswer" data-id="{{$answer->id}}">
{{$index+1}}) {!! $answer->answer_body !!}
</span>
#endforeach
Now this is my Controller
public function quizTest(Request $request){
if($request->isMethod('post')){
$data=$request->all();
foreach($data as $question_id => $answer_id){
dd($data);
$result=new Result;
$result->user_id=$data['user_id'];
$result->question_id=$question_id;
$result->answer_id=$answer_id;
$result->save();
}
}
}
Now when I do dd($data); and I want to store data like 1 2 3 4 5 in question_id and 2,6,9,13,18 in answer_id
Change your controller code to this to store it in answer and question format
public function quizTest(Request $request){
if($request->isMethod('post')){
$data=$request->all();
$user_id = $data['user_id'];
unset($data['_token']);
unset($data['user_id']);
foreach($data as $question_id => $answer_id){
$result = new Result;
$result->user_id = $user_id;
$result->question_id = $question_id;
$result->answer_id = $answer_id;
$result->save();
}
}
}

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

Resources