How to use in_array with belongsToMany relationships? - laravel

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

Related

laravel controller returns only 2 values

I have a database with 3 tables. A separate model is connected to each table, and there is a controller that accepts values from all models. On the site page, I will have 3 tables that will be populated from a mysql table.
When I connected 2 models, everything worked fine. But after connecting 3, I get an error
undefined variable: sec_3.
If you delete one of the variables, then everything will work fine. It seems to me that the problem is either with the controller or with the file blade.php but I do not know how to fix it so that everything works properly. How to fix it?
My code:
Controller:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context=['bbs' =>PreschoolInstitution3::latest()->get()];
$context_2=['s' =>PreschoolInstitution::latest()->get()];
$context_3=['sec_3' => TrainingPrograms::latest()->get()];
return view('our_employees', $context, $context_2, $context_3);
}
}
web.php:
Route::get('/OurEmployees',[PreschoolInstitution3Controller::class,'index'] )->name('OurEmployees');
blade.php:
#foreach ($s as $section_2) <tr> <td>{{$section_2->number}}<td> <td>{{$section_2->fullname }}<td> <td>{{$section_2->post }}<td> <td>{{$section_2->telephone }}</td> <td>{{$section_2->email }}</td>
#endforeach #foreach ($bbs as $section )
{{$section->number}} {{$section->full_name}} {{$section->post}} {{$section->education}} {{$section->category}} {{$section->teaching_experience}} {{$section->professional_development}}
#endforeach #foreach ($sec_3 as $section_3)
{{ $section_3->number }}
{{ $section_3->level }}
{{ $section_3->directions }}
{{ $section_3->type_of_educational_program }}
{{ $section_3->period_of_assimilation }}
{{ $section_3->number_of_students }}
#endforeach
You should pass an array of data to view:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context = [
'bbs' => PreschoolInstitution3::latest()->get(),
's' => PreschoolInstitution::latest()->get(),
'sec_3' => TrainingPrograms::latest()->get()
];
return view('our_employees', $context);
}
}
https://laravel.com/docs/9.x/views#passing-data-to-views
Another one is that add a second parameter of an array with name to view( ) .
class PreschoolInstitution3Controller extends Controller {
public function index(){
$bbs = PreschoolInstitution3::latest()->get();
$s = PreschoolInstitution::latest()->get();
$sec_3 = TrainingPrograms::latest()->get();
return view('our_employees', [
'bbs' => $bbs,
's' => $s,
'sec_3' => $sec_3
]);
}
}

Laravel: How to get data from View/Blade and pass to Controller

Tables: Item has boolean "onloan"
Patron(id, name), Item(id, name, onloan), Transactions (patron_id, item_id, loaned, due, returned)
Relationships:
Patron.php
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Item.php
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Transaction.php
public function item()
{
return $this->belongsTo(Item::class);
// return $this->belongsTo('App\Item','item_id');
}
public function patron()
{
return $this->belongsTo(Patron::class);
}
View: create.blade.php
<label for="item_id">Item</label>
<select name="item_id" id="item_id" class="form-control select2">
#foreach($items as $item)
<option value="{{ $item->id }}">
{{ $item->barcode }} - {{ $item->name }}
</option>
#endforeach
</select>
TransactionController.php
This part is where I have problem, Two (2) tables need to be updated.
i.e.
Transactions table: (this part is already working, it's ok)
Name......| Item..........| Loaned.....| Due..
John Doe | Harry Potter | 09/22/20 | 09/23/20
Items table: (this part I don't know how to add it in the Controller)
Name...........| Onloan
Harry Potter | 1
• how update a foreign table (Items) in this controller so that
the "onloan" value of that $item->id is 1.
public function store(TransactionRequest $request)
{
Transaction::create([
'patron_id' => $request->patron_id,
'item_id' => $request->item_id,
'loaned' => $request->loaned,
'due' => $request->due,
]);
//This is what I tried, but it's not working.
Item::find($request->item_id);
$item->update([
'onloan' => 1,
]);
Please help. Thank you.
Υou can write it that way
Item::find($request->item_id)->update(['onloan' => 1,]);
Create you can also do it
Transaction::create([$request->all()]);

Laravel - production.ERROR: Property [is_approved] does not exist on this collection instance

I am working on this code in a project built with Laravel-5.8
class HrEmployee extends Model
{
protected $table = 'hr_employees';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'employee_code',
'user_id',
'hr_status',
'address',
];
public function appraisalgoals()
{
return $this->hasMany('App\Models\Appraisal\AppraisalGoal', 'id', 'employee_id');
}
}
class AppraisalGoal extends Model
{
protected $table = 'appraisal_goals';
protected $fillable = [
'id',
'employee_id',
'employee_code',
'is_published',
'is_approved',
];
public function employee()
{
return $this->belongsTo('App\Models\Hr\HrEmployee','employee_id');
}
}
Controller
public function employee_goals()
{
$userCompany = Auth::user()->company_id;
$published_goals = HrEmployee::where('company_id', $userCompany)->where('hr_status', 0)->get();
return view('report.employee_goal_statistics.employee_goals')
->with('published_goals', $published_goals);
}
view
#foreach($published_goals as $key => $published_goal)
<td>
{{isset($published_goal->employee_code) ? $published_goal->employee_code : 'None'}}
</td>
<td>
#if ($published_goal->appraisalgoals->is_approved == 3)
<span class="badge bg-success" >Approved</span>
#elseif ($published_goal->appraisalgoals->is_approved == 2)
<span class="badge bg-danger">Not Approved</span>
#elseif ($published_goal->appraisalgoals->is_approved == 1)
<span class="badge bg-info">Awaiting Approval</span>
#else
<span class="badge bg-black">Draft</span>
#endif
</td>
#endforeach
employee_id is in it as a relationship foreign key
protected $table = 'appraisal_goals';
protected $fillable = [
'id',
'employee_id',
'employee_code',
'is_published',
'is_approved',
];
When I rendered the view, I got this error:
production.ERROR: Property [is_approved] does not exist on this collection instance
is_approved is in appraisal_goals (AppraisalGoal) model
How do I resolve this?
Thanks
first of all your foreign key reference is wrong in appraisalgoals() relationship definition. change it to
public function appraisalgoals()
{
return $this->hasMany('App\Models\Appraisal\AppraisalGoal', 'employee_id', 'id');
}
now as you defined your relationship as hasMany, that means you may have multiple data for a employee. so when you are accessing relationship, it returns a collection instead of an object. your data belongs to an object not to a collection. when you are accessing $published_goal->appraisalgoals->is_approved you are actually trying to get value from a collection appraisalgoals. you need to loop through the collection to get an object and then you can access value from that object.
#foreach ($published_goal->appraisalgoals as $key => $value)
{{ $value->is_approved }}
#endforeach
now you can access the first instance like
$published_goal->appraisalgoals()->first()->is_approved
if you define hasOne relationship then you can access value directly as you are accessing now
$published_goal->appraisalgoals->is_approved
hope you understands the issue. for your reference heres the relationship doc from laravel.
With get() method you get a collection (all data that match the query), try to use first() instead, it return only one element, like this:
$published_goals = HrEmployee::where('company_id', $userCompany)->where('hr_status', 0)->first();
Let me know what happens
$published_goal->appraisalgoals would be a collection [] because you are using HasMany, you would need another loop.
#foreach($published_goals as $key => $published_goal)
<td>
{{isset($published_goal->employee_code) ? $published_goal->employee_code : 'None'}}
</td>
<td>
#foreach($published_goal->appraisalgoals as $appraisalgoal)
#if ($appraisalgoal->is_approved == 3)
<span class="badge bg-success" >Approved</span>
#elseif ($appraisalgoal->is_approved == 2)
<span class="badge bg-danger">Not Approved</span>
#elseif ($appraisalgoal->is_approved == 1)
<span class="badge bg-info">Awaiting Approval</span>
#else
<span class="badge bg-black">Draft</span>
#endif
#endforeach
</td>
#endforeach
You could also change your relationship to a HasOne. Does a published_goal have many appraisalgoal or just one?
You could also target ->first(); The first appraisalgoals associated with the $published_goal.
Don't forget to lazy/eager load if you end up doing the second loop to avoid multiple calls for the same data.
$published_goals = HrEmployee::where('company_id', $userCompany)->where('hr_status', 0)->with('author')->get();
//Or
$published_goals = HrEmployee::where('company_id', $userCompany)->where('hr_status', 0)->get();
$published_goals->load('appraisalgoals');

Trying to get property 'id' of non-object 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 ();
}

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