Many to many relationship Laravel 7 - many-to-many

OrderController.php
public function create()
{
$user = Auth::user();
//shows only the dishes of the logged user
$dishes = Dish::orderBy("name", "asc")->where('user_id', Auth::id())->get();
return view("admin.orders.create", compact("dishes"));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
"name" => "required|min:3",
"lastname" => "required|min:3",
"address" => "required",
"email" => "required",
"phone" => "required|min:8",
"total" => "required",
"dishes" => "required",
]);
$order = new Order();
$order->fill($validatedData);
$order->user_id = Auth::id();
$order->save();
//attach dishes to order
foreach ($request->dishes as $dish) {
$order->dishes()->attach($dish, [
"quantity" => $dish["quantity"],
"subtotal" => $dish["subtotal"]
]);
}
return redirect()->route("admin.orders.show", $order->id);
}
/**
* Display the specified resource.
*
* #param \App\Order $order
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return view('admin.orders.show', [
'order' => Order::findOrFail($id)
]);
}
Order model
protected $fillable = [
"name", "lastname", "address", "email", "phone", "total", "user_id"
];
public function dishes()
{
return $this->belongsToMany('App\Dish')
->withPivot('quantity', 'subtotal');
}
I have a problem linking the orders table with the dishes one.
In the pivot table, I also have other columns to link.
What can I do to do this many-to-many relation?
The view I'm doing has the only purpose of trying to save the data into the pivot table.
View create.blade.php
{{-- quantity pivot table --}}
#foreach ($dishes as $dish)
<div class="form-group">
<label for="dish-quantity">Quantità di {{ $dish->name }}</label>
<input id="dish-quantity" type="number" name="dishes[{{ $dish->id }}]"
class="form-control #error('dishes') is-invalid #enderror"
placeholder="Inserisci la quantità" value="{{ old('dishes') }}">
#error('dishes')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
#endforeach
{{-- subtotal table --}}
#foreach ($dishes as $dish)
<div class="form-group">
<label for="dish-subtotal">Subtotale di {{ $dish->name }}</label>
<input id="dish-subtotal" type="number" name="subtotals[{{ $dish->id }}]"
class="form-control #error('subtotals') is-invalid #enderror"
placeholder="Inserisci il subtotale" value="{{ old('subtotals') }}">
#error('subtotals')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
#endforeach
{{-- total price --}}
<div class="form-group">
<label for="total_price">Prezzo totale</label>
<input id="total_price" type="text" name="total"
class="form-control #error('total') is-invalid #enderror" placeholder="Inserisci il titolo"
value="{{ old('total') }}" required>
#error('total')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>

Related

How to take another attribute value from another table, with known value from existing table

I'm trying to make a website where the system can generate patient bills based on clinic category and the action they've got in the clinic.
I have 3 tables :
Table to input the list of clinic category ("poli")
Table to input the list of clinic possible action for the patient ("tindakan")
Final table to input all of the above, where the patient choose one of the "poli" and the "tindakan" ("pasien").
This is some of my "poli" table entries :
poli::create([
'inisial' => 'GIGI',
'namapoli' => 'Poli Gigi',
'harga' => '12000',
]);
poli::create([
'inisial' => 'IMUN',
'namapoli' => 'Poli Imun',
'harga' => '10000',
]);
This is some of my "tindakan" table entries :
tindakan::create([
'namatindak' => 'Tindakan Medis Sederhana',
'harga' => '10000',
]);
tindakan::create([
'namatindak' => 'Tindakan Medis Ringan',
'harga' => '15000',
]);
tindakan::create([
'namatindak' => 'Tindakan Medis Sedang',
'harga' => '30000',
]);
This is my current input form for "pasien" :
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Tambahkan Pasien</h4>
<h6 class="card-subtitle">Form untuk menambahkan pasien baru.</h6><br>
<form method="post" action="/pasien" enctype="multipart/form-data">
#csrf
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="masuk">Tanggal</label>
<input type="date" id="masuk" name="masuk" class="form-control #error('masuk') is-invalid #enderror" placeholder="Tanggal Perawatan">
#error ('masuk')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="nama">Nama</label>
<input type="text" id="nama" name="nama" class="form-control #error('nama') is-invalid #enderror" placeholder="Nama Lengkap">
#error ('nama')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="poli">Poli</label>
<select class="form-control" name="poli" id="role">
#foreach ($poli as $info_poli)
<option value="{{ $info_poli->inisial }}">{{ $info_poli->inisial }}</option>
#endforeach
</select>
#error ('poli')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tindakan">Tindakan</label>
<select class="form-control" name="tindakan" id="tindakan">
<option value="-">...</option>
#foreach ($tindakan as $info_tindakan)
<option value="{{ $info_tindakan->namatindak }}">{{ $info_tindakan->namatindak }}</option>
#endforeach
</select>
#error ('tindakan')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="text-right">
<button type="submit" class="btn btn-info">Submit</button>
<button type="reset" class="btn btn-dark">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
This is my current table for "pasien" :
<div class="table-responsive">
Tambah Data<br>
<table id="zero_config" class="table table-striped table-bordered no-wrap">
<thead>
<tr>
<th>#</th>
<th>No. Karcis</th>
<th>Tanggal Masuk</th>
<th>Nama</th>
<th>Poli</th>
<th>Harga Karcis</th>
<th>Tindakan</th>
<th>Harga Tindakan</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($pasien as $info_pasien)
<tr>
<th>{{ $loop->iteration }}</th>
<td>{{ $info_pasien->id }}</td>
<td>{{ $info_pasien->masuk }}</td>
<td>{{ $info_pasien->nama }}</td>
<td>{{ $info_pasien->poli }}</td>
<td>{{ $info_pasien->poli }}</td>
<td>{{ $info_pasien->tindakan }}</td>
<td>{{ $info_pasien->tindakan }}</td>
<td>total</td>
<td>
<i data-feather="edit" style="color:white"></i>
<form action="/pasien/{{ $info_pasien->id }}" method="post" class="d-inline">
#method('delete')
#csrf
<button class="badge bg-danger border-0" onclick="return confirm('Yakin hapus?')"><i data-feather="trash" style="color:white"></i></a>
</form>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>#</th>
<th>No. Karcis</th>
<th>Tanggal Masuk</th>
<th>Nama</th>
<th>Poli</th>
<th>Harga Karcis</th>
<th>Tindakan</th>
<th>Harga Tindakan</th>
<th>Total</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
This is my current "pasien" controller, I've tried calling the tables with "pasien" "id" but i don't know how to call them :
<?php
namespace App\Http\Controllers;
use App\Models\pasien;
use App\Models\poli;
use App\Models\tindakan;
use Illuminate\Http\Request;
use Carbon\Carbon;
class dashpasienController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view ('dashboard.pasien.index', [
'pasien' => pasien::orderBy('id', 'desc')->latest()->get(),
'sekarang' => Carbon::now(),
'poli' => poli::orderBy('id', 'desc')->latest()->get(),
'tindakan' => tindakan::orderBy('id', 'desc')->latest()->get(),
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('dashboard.pasien.create', [
'poli' => poli::orderBy('id', 'desc')->first()->get(),
'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validateData = $request->validate([
'masuk' => 'required',
'nama' => 'required',
'poli' => 'required',
'tindakan' => 'required',
]);
pasien::create($validateData);
return redirect('/pasien')->with('success','Data pasien berhasil ditambahkan');
}
/**
* Display the specified resource.
*
* #param \App\Models\pasien $pasien
* #return \Illuminate\Http\Response
*/
public function show(pasien $pasien)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\pasien $pasien
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
return view('dashboard.pasien.edit',[
'poli' => poli::orderBy('id', 'desc')->first()->get(),
'tindakan' => tindakan::orderBy('id', 'desc')->first()->get(),
])->with(['pasien' => pasien::findOrFail($id)]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\pasien $pasien
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validateData = $request->validate([
'masuk' => 'required',
'nama' => 'required',
'poli' => 'required',
'tindakan' => 'required',
]);
pasien::where('id', $id)->update($validateData);
return redirect('/pasien')->with('success','Data pasien berhasil diperbarui');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\pasien $pasien
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
pasien::destroy($id);
return redirect('/pasien')->with('success','Data pasien berhasil dihapus');
}
}
Is it possible to get "poli->harga" from "poli" table and "tindakan->harga" from "tindakan" table to the current "harga poli" and "harga tindakan" column in "pasien" database. I also uploaded some picture to illustrate what I'm trying to do (see screenshot).

Failed to store data in laravel 8

I'm making a form so that users can request to create a new account to the admin, but every time I try to send data, it always fails, even though I've checked every part of my code, can anyone help me?
the form code :
<form method="POST" action="{{ url('/request-akun/make-request') }}">
#csrf
<div class="form-group col-md-12">
<label for="name">Nama</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group col-md-12">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" id="email">
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type="text" name="password" class="form-control"
id="password">
</div>
<div class="form-group col-md-12">
<label for="password_confirm">Konfirmasi Password</label>
<input name="password_confirm" type="text" class="form-control"
id="password">
</div>
<button type="submit" class="btn btn-primary pull-right"
style="margin-right: 15px;">Request</button>
</form>
this is the controller :
public function requestAccount(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required',
'password_confirm' => 'required'
]);
if ($request->get('password') == $request->get('password_confirm')){
$data = new requestAkun();
$data->name = $request->get('name');
$data->ra_user_id = Auth::id();
$data->ra_instansi_id = Auth::user()->instansiID;
$data->email = $request->get('email');
$data->password = $request->get('password');
$data->status = "pending";
$data->save();
return Redirect::to('/request-akun/request-lists')->with('success','Request Berhasil dikirim');
} else {
return Redirect::to('/request-akun/request-lists')->with('error','Password tidak sama');
}
}
this is the model code:
class requestAkun extends Model
{
use HasFactory, Uuids;
protected $table = 'request_akun';
public $timestamps = true;
protected $fillable = [
'name',
'ra_instansi_id',
'ra_user_id',
'email',
'password',
'status'
];
}
this is the route :
Route::prefix('request-akun')->group(function(){
Route::post('/make-request',[userController::class,'requestAccount'])->name('make-request');
});
Error is you don't have ra_instansi_id input in your form.
Not showing any validation error message in your form so better show errors so you check which validation failed.
3.Instead of checking password match in if condition you can change input name password_confirm to password_confirmation so you can change like below
<input name="password_confirmation" type="text" class="form-control"
id="password_confirmation">
and in your validation
$validator=Validator::make($request->all(),[
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);
dd($validator->errors());

How can I solve " Invalid datetime format: 1366 Incorrect integer value" Exception in Laravel 7?

I'm quite new to Laravel, I would like to update a column in mySQL database named "client_id" the name of the table is "projects" I would like to insert this column when a Client creates a new Project, because the project belongs to the Client who created it. "client_id" is the Primary Key (id) in the table called "clients". There is a relationship between "clients" table and "projects" table. I have written some code to solve this problem but I'm getting this Exception and the "client_id" column is not updated.
Please help.
Store Method in my Controller:
/**
* Store a newly created Project in storage.
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string|max:255',
'start_date' => 'required|date',
'start_time' => 'required|string|max:10',
]);
$project = Project::create([
'name' => $request->name,
'description' => $request->description,
'start_date' => $request->start_date,
'start_time' => $request->start_time,
]);
$loggedinId = Auth::id();
$project->update(['created_by' => $loggedinId]);
$userId = $loggedinId;
$clientId = Client::where('user_id', '=', $userId)->pluck('id')->all();
DB::table('projects')->where('created_by', '=', $loggedinId)->update([ 'client_id' => $clientId]);
return redirect()->back()->with('message', 'You have successfully submitted your Job Card');
}
Relationship in my Client Model:
/**
* #return HasMany
*/
public function projects()
{
return $this->hasMany(Project::class);
}
Relationship in my Project Model:
/**
* #return BelongsTo
*/
public function client()
{
return $this->belongsTo(Client::class, 'client_id');
}
Form In my Blade View:
<form method="POST" action="{{ route('client-jobcard.store') }}">
#csrf
<div class="form-group row">
<div class="col-sm-8">
<label for="name">{{ __('Job Card Name') }}</label><span class="required">*</span>
<input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="invalid-feedback">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-sm-8">
<label for="description">{{ __('Job Card Description') }}</label><span class="required">*</span>
<textarea class="form-control{{ $errors->has('description') ? ' is-invalid' : '' }}" id="description" rows="4" style="height: 150px;" name="description" value="{{ old('description') }}" required autofocus></textarea>
#if ($errors->has('description'))
<span class="invalid-feedback">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<label for="start_date">Start Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date" value="{{ old('start_date') }}" required>
</div>
<div class="col-sm-4">
<label for="submission_date">Start Time</label><span class="required">*</span>
<input type="text" class="form-control" id="start_time" name="start_time" value="{{ old('start_time') }}" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>
This line:
$clientId = Client::where('user_id', '=', $userId)->pluck('id')->all();
will return a column, not the single ID ("2") that you want.
Then, when you assign it to client_id which is an integer, the ORM will render it as the string [2] instead of the number 2, and that will give you an error.
Either retrieve just the first tuple from Client, or extract $clientId[0] manually (wasteful and not recommended).
You also have a second error I had overlooked:
'created_by', '=', $loggedinId
The above means that created_by must be an integer value, but the text of the error implies SQL expects it to be a datetime. You seem to have a wrong definition in the database.
your time field is in string , it has to be changed , it is not the same format
can you try this instead

how to recuperate the value of the chosen option in checkbox with laravel?

I try to save the value of the chosen option of ckeckbox in database.
but I get always the value "on" saved in my database even I did not chose any option.
this is the code of answercontroller .
public function store(Request $request, Survey $survey)
{
// remove the token
$arr = $request->except('_token');
foreach ($arr as $key => $value) {
$newAnswer = new Answer();
if (! is_array( $value )) {
$newValue = $value['answer'];
} else {
$newValue = json_encode($value['answer']);
}
$newAnswer->answer = $newValue;
$newAnswer->question_id = $key;
$newAnswer->user_id = Auth::id();
$newAnswer->survey_id = $survey->id;
$newAnswer->save();
};
this is the view:
{!! Form::open() !!}
#if($question->question_type === 'text')
{{ Form::text('title')}}
#elseif($question->question_type === 'textarea')
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Provide answer</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="radio" id="{{ $key }}" name="answer"/>
<label for="{{ $key }}">{{ $value }}</label>
</p>
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" />
<label for="{{$key}}">{{ $value }}</label>
</p>
#endforeach
please help me , how can i get the value of the option. thanks in advance.
That is because you are not setting the value and name of checkbox
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" value="{{ $value }}" name="mycheck[]" />
<label for="{{$key}}">{{ $value }}</label>
</p>
#endforeach

how to store drop-down list select into database?

I have a form for creating projects. It contains 2 foreign keys domain and owner (domain_id and owner_id). in fact these are 2 drop-down lists. when i try to submit the form, and check my database, I found out that owner and domain have NULL as value, eventhough i selected values from the drop-down list.
this is projectController :
public function create()
{
$domains = Domain::all('nameDomaine', 'id');
$owners = Owner::all('nameOwner', 'id');
return view('projectss.create', compact('domaines', 'owners'));
}
public function store(Request $request)
{
$domain_id = Domain::all()->pluck('nameDomain', 'id');
$owner_id = Owner::all()->pluck('nameOwner', 'id');
$this->validate($request, [
'title' => 'required',
'code' => 'required',
'domain_id' => 'required',
'owner_id' => 'required',
]);
Project::create($request->all());
return redirect()->route('projects.index')
->with('success', 'Project created successfully');
}
and this is create.blade.php :
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> Domain : </strong>
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $id => $domain)
<option value="{{ $id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> owner : </strong>
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $id => $owner)
<option value="{{ $id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
</select>
</div>
</div>
I read a lot of posts about this problem, but none of them is working for me.
You can try this
in controller's store function
$domain_id = Domain::all('nameDomain', 'id');
$owner_id = Owner::all('nameOwner', 'id');
In you view
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $id => $domain)
<option value="{{ $domain->id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
and for second select option
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $id => $owner)
<option value="{{ $owner->id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
You was not fetching id of your object. The $id you were fetching will just give you the index.
This should work :)
Change
#foreach($owners as $id => $owner)
<option value="{{ $id }}">{{ $owner->nameOwner }}</option>
#endforeach
to
#foreach($owners as $owner)
<option value={{ $owner->id }}>{{ $owner->nameOwner}</option>
#endforeach
And repeat with the other foreach loop.
If that doesn't work, in your controller add dd($request); to see what info is being passed to it and share with us, please.
Seems close but a few tweaks are needed. Also check your Project model and see if there is a $fillable array. If there is you'll need all the fields in your validate call in it e.g.
protected $fillable= [
'title'
'code'
'domain_id'
'owner_id'
];
Remove the calls in your store function.
public function create()
{
$domains = Domain::all('nameDomaine', 'id');
$owners = Owner::all('nameOwner', 'id');
return view('projectss.create', compact('domaines', 'owners'));
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'code' => 'required',
'domain_id' => 'required',
'owner_id' => 'required',
]);
Project::create($request->all());
return redirect()->route('projects.index')
->with('success', 'Project created successfully');
}
Make sure you're adding the right ID.
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> Domain : </strong>
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $domain)
<option value="{{ $domain->id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> owner : </strong>
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $owner)
<option value="{{ $owner->id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
</select>
</div>
</div>