How to show an old value / query field from database in mysql, and edit value in Laravel. I'm using Laravel 9x and PHP 8x
Controller.php :
public function edit(Business $business)
{
return view('dashboard.bisnis.edit', [
'item' => $business
]);
}
public function update(Request $request, Business $business)
{
$rules = [
'deskripsi' => 'required|max:255',
'pemilik' => 'required|max:255'
];
$validateData = $request->validate($rules);
Business::where('id', $business->id)->update($validateData);
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
}
Blade.php:
#extends('dashboard.index')
#section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Edit Data Bisnis</h1>
</div>
<div class="col-lg-8">
<form method="post" action="/dashboard/bisnis/{{ $item->id }}" class="mb-5" enctype="multipart/form-data">
#method('put')
#csrf
<div class="mb-3">
<label for="deskripsi" class="form-label">Deskripsi</label>
<input type="text" class="form-control #error('deskripsi') is-invalid #enderror" id="deskripsi" name="deskripsi" required autofocus
value="{{ old('deskripsi', $item->deskripsi) }}">
#error('deskripsi')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="pemilik" class="form-label">Pemilik</label>
<input type="text" class="form-control #error('pemilik') is-invalid #enderror" id="pemilik" name="pemilik" required autofocus
value="{{ old('pemilik', $item->pemilik) }}">
#error('pemilik')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Simpan Perubahan</button>
</form>
</div>
<script>
const deskripsi = document.querySelector('#deskripsi');
const pemilik = document.querySelector('#pemilik');
</script>
#endsection
Also when navigating through my menu such as Business, the sidebar seems cant to be clicked, nor use. Thank you so much
Please try like this:
{{ old('deskripsi') ? old('deskripsi') :$item->deskripsi }}
Please replace this:
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
to
return redirect()->back()->with('success', 'Item has been updated !');
I assume you use Laravel 9
Referring to Repopulating Forms - Validation
Controller.php:
you should use
$deskripsi = $request->old('deskripsi');
$pemilik = $request->old('pemilik');
before
$validateData = $request->validate($rules);
Blade.php:
you should use this on input
value="{{ old('deskripsi') }}"
value="{{ old('pemilik') }}"
By default old will return null if no input exists so we don't need to use nullcheck like
{{old('deskripsi') ?? ''}}
To repopulate value using old() in Laravel you need to return a response withInput(). Not just response.
The return code should
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
change to this
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !')->withInput();
The solution is i forgot to pass my $id on my controller and route (web.php). Here's my route
Route::controller(GroupServiceController::class)->middleware('auth')->group(function () {
Route::get('/dashboard/gruplayanan', 'index');
Route::get('/dashboard/gruplayanan/create', 'create')->name('gruplayanan.create');
Route::post('/dashboard/gruplayanan', 'store')->name('gruplayanan.store');
Route::get('/dashboard/gruplayanan/edit/{id}', 'edit')->name('gruplayanan.edit');
Route::post('/dashboard/gruplayanan/update/{id}', 'update')->name('gruplayanan.update');
Route::post('/dashboard/gruplayanan/delete/{id}', 'destroy')->name('gruplayanan.delete');
});
and my controller :
public function edit(GroupService $groupService, $id)
{
$groupService = $groupService->findOrFail($id);
return view('dashboard.gruplayanan.edit', [
'item' => $groupService
]);
}
Related
I'm beginner in laravel and I want to update multiple checkboxes in database ..
when I click at update button automatically my inputs show old value also my permissions are checked by old value to update it ..
relation between user and permission is manytomany .. I have another table named userpermissions who has id_user and id_permission
this is my update form in ( edit.blade.php)
<form action="{{ url('users/'.$user->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name" required class="form-control" value="{{ $user->name }}">
#error('name')
<ul class="alert"><li class="text-danger">{{ $message }}</li></ul>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="email" required class="form-control" value="{{ $user->email }}">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
#foreach($permissions as $permission)
<input type="checkbox" name="data[]" value="{{ $permission->id }}"
<?php if( in_array($permission->id, $user->userPermissions->pluck('permission_id')->toArray())){ echo 'checked="checked"'; } ?>/>
{{ $permission->name }}
#if($loop->iteration % 3 == 0 ) <br> #else #endif
#endforeach
</div>
</div>
</div>
<div class="text-right mt-4">
<button type="submit" class="btn btn-primary"> Add</button>
</div>
</form>
and this is my controller where I think have a problem with methods :
edit function
public function edit(User $user)
{
$permissions = Permission::get();
return view('users.edit', compact('user','permissions'));
}
update function :
public function update(UserRequest $request,User $user)
{
$user->update(
$request->only('name', 'email')
);
$user->userPermissions()->save($request->input('data'));
return redirect()->back()->with('status','user updated !');
}
and this is my functio store :
public function store(UserRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email'=>'required|email',
'password' => 'required|confirmed|min:6',
]);
$user = User::create(
$request->only('name', 'email', 'password')
);
$user->userPermissions()->createMany($request->input('data'));
return redirect()->back()->with('status','Utilisateur ajouté !');
}
Thanks for advance !
$user->userPermissions()->save($request->input('data'));
One important thing to understand here, is that save() on relation doesn't remove old values from pivot table, it just add more values to it(no distinction check). You need something like refresh functionality. Look at attaching\detaching or sync, second one is more convenient.
In first case before saving permissions you can do this
// remove all old permissions
$user->userPermissions()->detach();
// update them with new one
$user->userPermissions()->attach($request->input('data'));
In second case, which is less verbose then first one you just need to pass and array of permissions to user object.
// this will do both things which we did before
$user->userPermissions()->sync($request->input('data'))
But i encourage you to read the docs and ask questions after ;)
Another thing which i saw and its not related to the current topic is
$user->userPermissions->pluck('permission_id')->toArray()
you are using lazy load inside of foreach loop which means that on each iteration of the loop you are making a query to the database(N + 1 problem). You can preload/eager load userPermissions instead of loading them on a fly by declaring with relation in your User model like this
class User extends Model
{
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['userPermissions'];
...
}
and then in your User object will have userPermissions property which you can compare to permissions.
Hope that you get main idea and info was useful for you!
I have created a view to create new courses 'create.blade.php'. And I am trying to store this data in the DB however I am getting the following error:
BadMethodCallException Method Illuminate\Http\Request::request does
not exist.
I am not sure what is causing the error as I have referred to the the request namespace in my controller. See below;
CoursesController.php;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$courses = Course::all()->pluck('title');
$instructors = User::all()->pluck('name', 'id'); //defining instructor variable
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->courses()->sync($request->request('courses', [])); //
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
}
Create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
#if (Auth::user()->isAdmin())
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $instructors, Input::get('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
#if($errors->has('Instructor'))
{{ $errors->first('Instructor') }}
</p>
#endif
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
#endif
</form>
</div>
</div>
#endsection
I am new to laravel so i would appreciate any help. Thanks.
The error message
BadMethodCallException Method Illuminate\Http\Request::request does
not exist
speaks to an attempt to call a method/function named request on the Illuminate\Http\Request class, and that function not existing.
it looks like you are indeed trying to use a request() method here:
$course->courses()->sync($request->request('courses', []));
You most likely want the input() method instead, which would get data posted as 'courses'.
$course->courses()->sync($request->input('courses', []));
as described at https://laravel.com/docs/master/requests#input-trimming-and-normalization
I hope this helps!
change
$course->courses()->sync($request->input('courses', []));
I am getting an error which says
"Property [id] does not exist on this collection instance. (View: C:\newXampp\htdocs\testUser\resources\views\Stock\edit.blade.php)"
This is my Controller
public function editStock(Stock $id)
{
//
$Stock = Stock::find($id);
return view('Stock.edit', compact('Stock', 'id'));
// return response($stock);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Stock $stock
* #return \Illuminate\Http\Response
*/
public function updateStock(Request $request, $id)
{
$request->validate([
'id'=>'required',
'stock_name'=>'required',
'stock_qty'=>'required',
'stock_unit'=>'required',
'stock_price_per_kg'=>'required',
'stock_weight_per_qty'=>'required'
]);
$stock = Stock::find($id);
$stock->stock_name = $request->get('stock_name');
$stock->stock_qty = $request->get('stock_qty');
$stock->stock_unit = $request->get('stock_unit');
$stock->stock_price_per_kg = $request->get('stock_price_per_kg');
$stock->stock_weight_per_qty = $request->get('stock_weight_per_qty');
$stock->save();
return redirect('/Stock/index/')->with('success', 'Stock updated!');
}
These are my routes
//Route for Stock
Route::get('/Stock/createStock/', 'ChicController#createStock')->name('createStock');
Route::post('/Stock/createStock/', 'ChicController#storeStock')->name('storeStock');
Route::get('/Stock/index/', 'ChicController#indexStock')->name('indexStock');
Route::get('/Stock/edit/{id}', 'ChicController#editStock')->name('editStock');
Route::post('/Stock/edit/{id}', 'ChicController#updateStock')->name('updateStock');
Route::delete('/Stock/index/{id}', 'ChicController#destroyStock')->name('deleteStock');
This is my edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a Stock</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br />
#endif
<form method="post" action="{{ route('updateStock', $Stock->id) }}">
{{ csrf_field() }}
<div class="form-group">
<label for="stock_name">Stock Name:</label>
<input type="text" class="form-control" name="stock_name" value={{$Stock->stock_name }} />
</div>
<div class="form-group">
<label for="stock_qty">Stock Amount:</label>
<input type="number" class="form-control" name="stock_qty" value={{$Stock->stock_qty }} />
</div>
<div class="form-group">
<label for="stock_unit">Stock Unit:</label>
<select id="stock_unit" name="stock_unit" value={{$Stock->stock_unit}}>
<option value="Kg">Kg</option>
<option value="Qty">Qty</option>
</select>
</div>
<div class="form-group">
<label for="stock_price_per_kg">Price Per Kg:</label>
<input type="number" class="form-control" name="stock_price_per_kg" value={{$Stock->stock_price_per_kg }} />
</div>
<div class="form-group">
<label for="stock_weight_per_qty">Weight Per Qty:</label>
<input type="number" class="form-control" name="stock_weight_per_qty" value={{$Stock->stock_weight_per_qty }} />
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
I have tried everything, but I could not solve the problem. When I try to echo the $id in the edit Controller, it shows the correct $id. Hence, I do not know how to solve this, nor do I know why this is happening.
For your editStock method you are already receiving an instance of a Stock model matching the id from the route parameter due to the Implicit Route Model Binding that is taking place. When you pass that $id variable to Stock::find($id) you are passing a Model which is Arrayable. This causes find to become findMany thinking you are passing many ids. You end up with a Collection because of this:
public function editStock(Stock $id)
{
$Stock = Stock::find($id);
return view('Stock.edit', compact('Stock', 'id'));
}
$Stock is a Collection because of passing many to find. I would adjust this to only pass the $id variable to your view which is the Stock that you want.
public function editStock(Stock $id)
{
return view('Stock.edit', [
'Stock' => $id,
]);
}
Your view will now have a Stock variable which is the Stock that you wanted.
Laravel 5.8 Docs - Routing - Route Model Bindings - Implicit Bindings
I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.
I am trying to make a edit function for my user's where they can edit their own data, but i want it to depends on what the user will change and if the other field is not changed will be at is. you will see the code below and its not working if only one is changed but if i changed all of them the data will be changed.
Myprofile // my users view
<form class="form-group" method="POST" action="{{ route('updateprofilemany', ['id' => auth()->user()->id]) }}" >
#csrf
//username
<input class="col-md-3 container justify-content-center form-control {{$errors->has('username') ? 'has-error' : ''}}" type="text" name="username" id="username" placeholder="{{ Auth::user()->username }}" Value="{{ Request::old('username') }}" />
//bio
<textarea class="border-info form-control {{$errors->has('bio') ? 'has-error' : ''}}" type="text" name="bio" id="bio" placeholder="{{ Auth::user()->bio }}" Value="{{ Request::old('bio') }}"></textarea> <br />
<button id="btn-login" class="btn btn-md r btn-primary" type="submit" > <i class="fa fa-cog"> </i> Save Changes </button>
</form>
StudentController.php // my users controller
public function updateprofilemany(Request $request, $id)
{
// Validation
$this->validate($request, [
'username' => 'max:15|unique:Students',
'bio' => 'max:50',
]);
if ($request->has('username'))
{
// if there is a new username value
$username = $request->input('username');
} else {
$username = Auth::user()->username;
}
if ($request->has('bio'))
{
// if there is a new username value
$bio = $request->input('bio');
} else {
$bio = Auth::user()->bio;
}
// Find the user and inject the new data if there is then go back to
myprofile
$students = User::find($id);
$students->username = $username;
$students->bio = $bio;
$students->save();
//redirect
return redirect()->route('myprofile');
}
it can read the data but if I add it inside the if else statements it requires the both fields.
I tried passing default data like this
myprofile // users view
<form class="form-group" method="POST" action="{{ route('updateprofilemany', ['id' => auth()->user()->id, 'username' => auth()->user()->username, 'bio' => auth()->user()->bio]) }}" >
#csrf
//username
<input class="col-md-3 container justify-content-center form-control {{$errors->has('username') ? 'has-error' : ''}}" type="text" name="username" id="username" placeholder="{{ Auth::user()->username }}" Value="{{ Request::old('username') }}" />
//bio
<textarea class="border-info form-control {{$errors->has('bio') ? 'has-error' : ''}}" type="text" name="bio" id="bio" placeholder="{{ Auth::user()->bio }}" Value="{{ Request::old('bio') }}"></textarea> <br />
<button id="btn-login" class="btn btn-md r btn-primary" type="submit" > <i class="fa fa-cog"> </i> Save Changes </button>
</form>
Web.php // routes
// calls user update profile many function
Route::post('/updateprofilemany/{id}', [
'uses' => 'StudentController#updateprofilemany',
'as' => 'updateprofilemany',
'name' => 'updateprofilemany'
]);
Student Controller
public function updateprofilemany(Request $request, $id, $username ,$bio)
{
//functions like above
}
and add it the specific function like
public function Functionname(Request $request, $id, $username, $bio)
can you guys help me with this thank you!
When you use Value="{{ Request::old('username') }}" in your username field, it may be empty because it doesn't have any value in the first time you open that page.
And in the controller when you use if ($request->has('username')) , it returns true because the username field is sent but with empty value.
You should check the username field for empty value and then continue ...
for example :
if ($request->filled('username')) {
// do something
}
If you only want to change the data when it is in the request you can just pass a default value to the input function. This will use the value if the key is not present in the request. If the key exists but it is an empty string then you can check with a ternary statement to see if there is a value.
This is probably the most simple way to write it:
public function updateprofilemany(Request $request, $id)
{
$this->validate($request, [
'username' => 'max:15|unique:Students',
'bio' => 'max:50'
]);
// get the user
$student = User::find($id);
// just pass the default value as the old username if the key is not supplied
// and if it is an empty string it will also use the old username
$student->username = $request->input('username', $student->username)
?: $student->username;
// also pass the default here as the old bio
$student->bio = $request->input('bio', $student->bio)
?: $student->bio;
$student->save();
}