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
Related
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
]);
}
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 have a question about the Laravel search function, i had follow the guildeline online and i still fail to search the category, can someone guide me and tell me where i did wrongly ? Much appreciated
My category Controller php code:
public function search(Request $request)
{
$search = $request->get('search');
$posts = DB::table('bit_app_policy_category')->where('id','like','%' .$search. '%')->paginate(5);
return view('category.index',['posts' => $posts]);
}
My index.blade code
<div align="left">
<div class="col-md-4">
<h1>Policy</h1>
</div>
<div class="col-md-4">
<form action="/search" method="get" role="search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="_method" placeholder="Search ID / Code"> <span class="input-group-btn">
<button type="submit" class="btn btn-primary">Search</button></span>
</div>
</form>
</div>
</div>
web.php
Route::get('/search','categoryController#search');
What error i get is here
Error image
interface
Database
You are sending $posts variable to your view. But the error says you are referencing a $category variable.
return view('category.index',['posts' => $posts]);
Maybe you might want to update view to use $posts. If you could post your full code (category/index.blade.php) we might be able to help you better.
__
Here is how I would do:
$categories= DB::table('bit_app_policy_category')->where('id','like','%' .$search. '%')->paginate(5);
return view('category.index',['categories' => $categories]); //you can also use compact return view('category.index', compact('categories') );
And to display:
#foreach( $categories as $category )
<div>{{ $category->id }}</div>
#endforeach
Another tip: you can name your routes like so
Route::get('search','categoryController#search')->name('search');
Then you can reference this route (in form or anywhere else you want) like so:
<form action="{{ route('search') }}" ..>
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
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
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$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 routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
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
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['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