How can i show data from my controller in a textbox? - laravel

Hi i calculated a discount in my controller by requesting in a form the percentage and the sale_price, so i did this:
public function store(Request $request){
dd($request->all());
$presupuestoProducto = new PresupuestoProducto();
$presupuestoProducto->sale_price = $request->sale_price;
$presupuestoProducto->discount_percentage = $request->discount_percentage;
$presupuestoProducto->discount = ($sale_price * $discount_percentage)/100;
$presupuestoProducto->save();
Session::flash('success');
return redirect()->route('presupuestos-productos.view');
}
But now i want to make the result of $presupuestoProducto->discount to appear in a textbox. So it would be like an autocomplete field. So up to now i have it this way in my view.
<div class="form-group col-md-2">
<label for="sale_price">Precio de Venta</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Porcentaje de descuento (%)</label>
<input type="number" name="discount_percentage" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" class="form-control" value="discount">
</div>
As you can see my last div is an input but i want it to be a text box that automatically appears the result of $presupuestoProducto->discount as i fill in the first two inputs. How should i do this?

you have to use view() and pass the $presupuestoProducto with compact() then you access to the var in your view with it's name
$presupuestoProducto->save();
return view("ProductView",compact( 'presupuestoProducto'))
in view : ProductView
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" placeholder="discount" class="form-control" value={{$presupuestoProducto->discount}} >
</div>
but if you wanna use route you can try route parameter

Related

fetch datas from database based on selected data dropdown using laravel 8

hai everyone i want to fetch data (affected device name, device intended use, class of device) from database based on my selected dropdown (mda registration num),i get the registration numb er from database but i don't how to fetch other related datas based on registration num.How i can gets datas.Here my controller n create.blade.php,pls help me
create.blade.php
<div class="form-group row">
<label for="inputMedName col-auto" class="col-lg-3 col-form-label " for="mdaRegisNo1">1. MDA Device Registration No. <span style="color:red;">*</span></label>
<div class="col-6 col-lg-6">
<select name="mdaRegisNo" class="form-control " id = "mdaRegisNo1" select data-size="5" data-live-search="true">
<option > Select MDA Registration Number</option>
#foreach($devices as $key=>$device)
<option value="{{$key}}">{{$device->device_reg_no}}</option>
#endforeach
</select>
</div>
<input type='button' value='Seleted option' id='but_read'>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">2. Affected Device Name <span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devName" type="text" class="form-control" >
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">3. Device intended use <span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devUse" type="text" class="form-control" >
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">4. Class of Device<span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devClass" type="text" class="form-control" >
</div>
</div>
RecallControlle.php
public function create()
{
$recall = Recall::latest()->first();
$ref_recall = 'MDA/Recall/P'.$this->getRefSuffix($recall);
//$devices = DB::table('devices');
$devices = Device::get();
$post = Device::query();
$device = DB::table('devices')->select('device_reg_no')->distinct()->get()->pluck('device_reg_no')->sort();
//dd($devices);
//return json_encode($devices);
return view('recall.create',['devices'=>$devices])->with([
'ref_recall' => $ref_recall,
'ref_mpr' => ''
]);
}
You have to use js to request data when your dropdown been selected.
Follow this doc to request data: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
pass your selected value to your api
get result from api
append value to input

How can I hide and display part of the form on a condition?

I want to use the same form to perform two different operations, and hide and display part of the form on a condition. Let's say if the text of the submit button is "SAVE" admissionNumber input field will not display but if the button text of the submit button is "UPDATE" admissionNumber input field will display. Below is the code sample
registerForm.html the same for being used to register and update student information
<div layout:fragment="content" class="container mySpace">
<form method="post" th:object="${student}" th:action="#{/register}">
<div class="card cardspace">
<h5 class="card-header" th:text="${chead}"></h5>
<div class="card card-body">
<div class="form-row">
<div class="col-9">
<div class="row">
i want to be able hide admissionNumber field if the btname is save and display it if the btname changes to update
<div class="form-group col" th:if="${btnname} == 'Submit'">
<label for="admissionNumber">Admission Number</label> <input
type="text" class="form-control" id="admissionNumber"
th:field="*{admissionNumber}">
<div class="text text-danger"
th:if="${#fields.hasErrors('admissionNumber')}"
th:errors="*{admissionNumber}"></div>
</div>
<div class="form-group col" th:unless="${btnname} == 'Update'">
<label for="admissionNumber">Admission Number</label> <input
type="text" class="form-control" id="admissionNumber"
th:field="*{admissionNumber}">
<div class="text text-danger"
th:if="${#fields.hasErrors('admissionNumber')}"
th:errors="*{admissionNumber}"></div>
</div>
<div class="form-group col">
<label for="firstName">First Name</label> <input type="text"
class="form-control" id="firstName" th:field="*{firstName}">
<div class="text text-danger"
th:if="${#fields.hasErrors('firstName')}"
th:errors="*{firstName}"></div>
</div>
<div class="form-group col">
<label for="lastName">Last Name</label> <input type="text"
class="form-control" id="lastName" th:field="*{lastName}">
<div class="text text-danger"
th:if="${#fields.hasErrors('lastName')}"
th:errors="*{lastName}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" th:text="${btnname}"></button>
</form>
student controller class
#Controller
public class StudentController {
#Autowired
private StudentServices studentServices;
displays the registration form
#GetMapping("/register")
public String showStudentRegistrationForm(Model model ) {
model.addAttribute("student", new Student());
model.addAttribute("chead", "Student Enrollment");// for card-header title h5 tag
model.addAttribute("btnname", "Submit"); // for button text
return "views/studentRegistrationForm";
}
displays the edit or update form
#GetMapping("/editStudent")
public String showStudentRegistrationEditForm(Model model ) {
model.addAttribute("student", new Student());
model.addAttribute("chead", "Edit Student Enrollment");
model.addAttribute("btnname", "Update");
return "views/studentRegistrationForm";
}
}
what you want is th:if tag, you got it almost right but whole wxpression needs to be in brackets th:if="${btnname == 'Submit'}"

Update single field in a Profile Update Form in Laravel 5

I am trying to update a single field in my user profile form section in the Laravel app.
I can save fields correctly in DB but input values and placeholders are taking wrong values. In every hit Save, the values doesn' change, and they are taken from the last listed user profile details. In my case this is user#3. The problem is when I log in with the user's #1 credentials, value and placeholder are taken from user #3. When I log in with user #2, again from user #3. Only values of user#3 are correct and I can manipulate it with no issues for both fields.
When i update the profile fields with user#1 it saves the entered one filed, but because the 2nd filed inherits the user#3 input details it saves it in field 2 of user#1 which makes a wrong entry. I can't leave null in those fields by default. My mass assignment is guarded.
How can save/update just a single field in the blade template without affecting the other fields in the form?
My routes:
Route::get( '/profile', 'userController\\profileEdit#profileEdit')->name('profileEdit');
Route::post('/profile', 'userController\\profileEdit#update')->name('update');
My controller:
namespace App\Http\Controllers\userController;
use App\Model\Hause_users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class profileEdit extends Controller
{
function profileEdit (Request $request){
$user = Hause_users::all();
$name = $request->session()->get('name');
$request->session()->keep([request('username', 'email')]);
return view('frontview.layouts.profile',['user'=>$user])->with('username' , $name );
}
function update (Request $request){
$user = Hause_users::where('username', $request->session()->get('name'))->first();
$user->fill(['email' => request('Email')]) ;
$user->save();
$user->phone;
//dd($user->phone->phone);
if ($user->phone === null) {
$user->phone->phone->create(['phone' => request('tel')]);
}
else{
$user->phone->update(['phone' => request('tel')]);
}
return back()->withInput();
}
Blade file: `
#extends('frontview.layouts.userView')
#extends('frontview.layouts.default')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#section('title')
#endsection
#section('content')
#foreach($user as $v )
#endforeach
<h2 class="form-group col-md-6">Здравей, {{$username }} </h2>
<form class = "pb2" method="POST" name = 'profile' action='profile' >
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="email" class="form-control" name = "Email" id="inputEmail4"
value="{{$v['Email']}}"
placeholder="{{$v->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$v->phone['phone']}}"
placeholder="{{$v->phone['phone']}}"
id="example-tel-input" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity">Град</label><input type="text" class="form-control" id="inputCity">
<label for="inputCity">Квартал</label><input type="text" class="form-control" id="inputCity">
</div>
{{--<div class="col-md-6" >--}}
{{--<label for="image">Качи снимка</label>--}}
{{--<input type="file" name = "image">--}}
{{--<div>{{$errors->first('image') }}</div>--}}
{{--</div>--}}
</div>
{{--<div ><img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg"--}}
{{--class="rounded-circle z-depth-1-half avatar-pic" alt="example placeholder avatar">--}}
{{--</div>--}}
{{--<div class="d-flex justify-content-center">--}}
{{--<div class="btn btn-mdb-color btn-rounded float-left">--}}
{{--<span>Add photo</span>--}}
{{--<input type="file">--}}
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Запомни ме!
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Запази</button>
</form>
#endsection
#section('name')
{{ $username }}
#endsection
Output summary:
On img#1 are the correct entry details . This is other section not the Profile edit one. Currently loged user is U#1 but as you can see on image 2, values and placeholder of both fields are for the U#3. When i hit the blue button U#1 saves the untouched filed input of U#3. Same is when i log in with U#2.
Actually the answer here is quite simple. What i am doing wrong is that i am not passing the value of the currently logged user to the view correctly. On my profileEdit method i was using $user = Hause_users::all(); and then looping trough all id's into the view and then fetching every field. But because the view doesn know which user passes the data, the foreach always returns the last user id from the array with its input, no matter which user is currently logged in. Then the data was overridden with wrong inputs.
The solution is also simple.
Instead of $user = Hause_users::all();
i have used
$user = Hause_users::where('username', $request->session()->get('name'))->first();
and then into view i was objecting the $user variable without any loops like this:
<form class = "pb2" method="POST" name = 'profile' action='profile' >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{{--<input type="hidden" name="_method" value="PATCH">--}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="Email" class="form-control" name = "Email" id="inputEmail4"
value="{{$user->Email}}"
placeholder="{{$user->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$user->phone['phone']}}"
placeholder="{{$user->phone['phone']}}"
id="example-tel-input" >
Basically this is a detailed explanation to all that not using the built in Auth system of Laravel

cannot show data from model object

I want to change the data absent but an error appears 'Trying to get the property' id 'of non-object' I do not understand why even though I have done it before and it's fine. and my relationship table is in apache MySql so my model is blank.
I've tried to match my other edit method but nothing is wrong
this my edit()
public function edit($id)
{
$absensi = absensi::find($id);
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
return view('absensi.edit', ['absensi'=> $dataSiswa]);
}
and then this is my blade
<div class="card-header">
<h1>Edit Data Absensi </h1>
</div>
<div class="card-body">
<form action="/absensi/{{$absensi->id}}" method="POST" name="form1" >
{{ csrf_field() }}
<div class="form-group">
<label for="usr">Nama :</label>
<input type="text" value="{{$dataSiswa->nama}}">
</div>
<div class="form-group">
<label for="usr">Semester :</label>
<select name="semester" class="form-control" id="sel1">
<option value="genap"#if ($dataSiswa->semester=="ganjil") selected #endif>ganjil</option>
<option value="ganjil"#if ($dataSiswa->semester=="genap") selected #endif>genap</option>
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" name="kelas" value="{{$dataSiswa->kelas}}">
</div>
<div class="form-group">
<label for="comment">izin:</label>
<input type="number" class="form-control" name="izin" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Sakit :</label>
<input type="number" class="form-control" name="sakit" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Tanpa Keterangan :</label>
<input type="number" class="form-control" name="tanpaKeterangan" value="{{$dataSiswa->izin}}">
</div>
<button type="submit" class="btn btn-primary" id="Submit" name="Submit">simpan perubahan</button>
</form>
</div>
</div>
</div>
change
$absensi = absensi::find($id);
to
$absensi = absensi::findOrFail($id);
i think the problem is that the model cannot find the record with that id
and if thats not the case then
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
to
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
if(!$dataSiswa) {
// throw new notfound exception here or return back
}
return view('absensi.edit', ['absensi'=> $dataSiswa]);
In other words you are trying to access a property of a null object because the queries you made are returning a null object, and on your blade you are tying to access a null object property
You should probably look into defining your relationships with eloquent instead as per the docs.
Once that's done you can use Eloquent to query your table like so:
$abensis = abensis::findOrFail($id);
$dataSiswa = $abensis->siswa;
return view('absensi.edit', ['absensi'=> $dataSiswa]);

Form in Laravel don't send data

I try to make a form with multiples date inputs, I copy the model from the register / login blade template but it don't work, here is what I do in my template:
<form method="POST" action="{{ route('createDispo') }}">
#csrf
<div class="form-group row">
<label for="date_debut" class="col-md-4 col-form-label text-md-right">Date de début</label>
<div class="col-md-6">
<input type="date" name="date_debut" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="date_debut_heure" class="col-md-4 col-form-label text-md-right">Heure de début</label>
<div class="col-md-6">
<input type="date" name="date_debut_heure" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="date_fin" class="col-md-4 col-form-label text-md-right">Date de fin</label>
<div class="col-md-6">
<input type="date" name="date_fin" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="date_fin_heurev" class="col-md-4 col-form-label text-md-right">Heure de fin</label>
<div class="col-md-6">
<input type="date" name="date_fin_heure" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Ajouter
</button>
</div>
</div>
</form>
But the form doesn't return a $data array like the register or login one, but only the first value (date_debut and not in an array, how to properly do a form with Laravel ?
EDIT:
Here is my controller
public function createDispo(array $data){
$disponibilite = new Disponibilite();
$disponibilite->date_debut = $data["date_debut"];
$disponibilite->date_fin = $data["date_fin"];
//$user->disponibilites()->save($disponibilite);
}
The problem is that I don't receive this 'data' array but only one value (the first datepicker)
You can access submitted data using the $request. The docs describe it well. In your case:
use Illuminate\Http\Request;
public function createDispo(Request $request){
$disponibilite = new Disponibilite();
$disponibilite->date_debut = $request->date_debut;
$disponibilite->date_fin = $request->date_fin;
// ...
}
When you send HTTP requests as this form, the method that should get this information should receive the Illuminate/Http/Request class.
The controller login does that differently because the controller send the $request->all() (this is an array) to the method login after the validation.
So what you have to do, is to change:
public function createDispo(array $data){
To
public function createDispo(Request $data){
Or to be more consistent to variables:
public function createDispo(Request $request){
Then you can access the data with:
public function createDispo(Request $request){
$disponibilite = new Disponibilite();
$disponibilite->date_debut = $request->date_debut;
$disponibilite->date_fin = $request->date_fin;
//$user->disponibilites()->save($disponibilite);
}
Remember to import the class of Illuminate\Http\Request when using Request

Resources