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

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()]);

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

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

Product_id not being passed to function

I have this form
<form method='POST' action='/products/{{ $product->id }}/reviews'>
{{ csrf_field() }}
<div>
<textarea name = 'review' placeholder ='Post a review'>{{ old('review') }}</textarea>
</div>
<div>
<button type ='submit'>Save</button>
</div>
</form>
The data then gets passed to this function in my controller
public function store(products $product)
{
$product->addReview(request('review'));
return back();
}
The addReview method is found in my products model
public function addReview($review)
{
return reviews::create([
'product_id' => $this->id,
'review' => $review
]);
}
I think the problem lies here
'product_id' => $this->id,
Once I fill in the form and submit, no data is added to the 'product_id' field. It's not included in any of the post data.
In your Review model:
public function product() {
return $this->belongsTo(products::class);
}
I renamed it to a product because it is one result not multiple.
Then here:
public function addReview($review)
{
return reviews::create([
'product_id' => $review->product->id,
'review' => $review
]);
}
Or even better, if you are adding a review, you should have the Product selected not the review, as you are adding a review to the product, so the method should be something like this:
public function addReview($product)
{
$review = request('review');
return $product->reviews()->create([
'review' => $review
]);
}
EDIT I see that you already have this.. so this code should work. If in the reviews table you have a product_id column, the relationship should be correct.

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- Handling multiple checkboxes in pivot tables

I have been struggling with this for a while, am a new developer with very little experience. So am working on a project dealing with drugs and diseases. There exists a many to many relationship.
Drug model
public $timestamps=false;
public function disease()
{
return $this->belongsTo('App\Disease');
}
Disease model
public $timestamps=false;
public function drug()
{
return $this->belongsTo('App\Drug');
}
I want to create relationships in the Disease_Drug pivot table using forms.
form.blade.php
<label>Disease</label>
<select class="form-inline input-sm " name="disease" id="disease">
#foreach($diseases as $key => $disease)
<option value="{{$disease->id}}"> {{$disease->name}}</option>
#endforeach
</select>
<label>Drugs</label><br>
#foreach($drugs as $key=>$drug)
<input type="hidden" name="drug[]" value="0" />
<input class="checkbox-inline" type="checkbox" name="drug[]"value="{{ $drug->id }}" id="{{ $drug->id }}">{{ $drug->name }} <br>
#endforeach
<button type="submit" class="btn btn-primary">Submit</button>
I have a disease_drug controller
public function form()
{
$diseases = Disease::all();
$drugs = Drug::all();
return view('admin.form')
->with('diseases', $diseases)
->with('drugs', $drugs);
}
public function store(Request $request)
{
$diseases = $request->get('diseases.ids');
$drugs = $request->get('drugs.id', []); // Empty array by default if no checkbox checked.
$diseases->drugs()->sync($request->input('drugs', []));
}
I am unable to save the results in the database. I am really clueless on this so kindly help me out.
If relation between drugs and disease is Many To Many then your relation function should be as:
Drug model
public function disease()
{
return $this->belongsToMany('App\Disease');
}
Disease model
public function drug()
{
return $this->belongsToMany('App\Drug');
}
You are using belongsTo() function instead.

Resources