I have just got this error all the tries while updating my table data.
ErrorException: Creating default object from empty value
AdminController.php
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
My Resource Route
Route::resource('post', AdminController::class);
Blade File
<div class="edit-post-content">
<form action="{{ route('post.update',$list->post_id) }}" method="POST">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$list->id}}">
<input type="hidden" name="post_rating" value="{{$list->post_rating}}">
<div class="mb-3">
Edit Title: <input class="form-control" name="post_title" type="text" id="exampleFormControlInput1" value="{{$list->post_title}}" aria-label="default input example">
</div>
<div class="mb-3">
Edit Description:
<textarea class="form-control" id="exampleFormControlTextarea1" name="post_details" rows="3">
{{ $list->post_details }}
</textarea>
</div>
<div>
<img src="{{asset('images/'.trim($list->post_image))}}" alt="" width="120px;">
Edit Photos:
<input id="formFileMultiple" class="form-control form-control-lg" name="post_image" type="file" value="{{ $list->post_image }}" multiple>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
Could someone help me, please?
There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
if (!$post) {
// You can add code to handle the case when the model isn't found like displaying an error message
return back();
}
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
Related
Hi I am new to laravel and javascript,
I have a multiple input forms for updating of product information including a image upload using Dropzone.js to update product image. However I cant see to update my image file as I keep getting a null value for my dropzone image when I have already dragged a file in.
Below are my codes in the product-edit page:
<form action="{{ route('merchant.product.update', $product->prodID) }}" method="POST" class="dropzone" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="form-group">
<h5>Code</h5>
<input type="text" name="prodCode" class="form-control" id="prodCode" placeholder="Product Code" value="{{ old('prodCode', $product->prodCode) }}" required>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Description</h5>
<textarea id="prodDesc" name="prodDesc" class="form-control" id="prodDesc" placeholder="Description" rows="5" required> {{ $product->prodDesc }}</textarea>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Price</h5>
<input type="text" name="price" class="form-control" id="price" placeholder="Price" value="{{ old('price', $product->price)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Quantity</h5>
<input type="number" name="quantity" class="form-control" id="quantity" placeholder="Quantity" value="{{ old('quantity', $product->quantity)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Feature Product</h5>
<div class="switch">
<input type="checkbox" name="featured" class="switch-input" value="1" {{ old('featured', $product->featured=="true") ? 'checked="checked"' : '' }}/>
<div class="circle"></div>
</div>
</div>
<div class="form-group">
<h5>Product Image</h5>
<div id="dropzoneDragArea" class="dz-default dz-message dropzoneDragArea">
<span>Upload Image</span>
</div>
<div class="dropzone-previews"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-large btn-primary">Update Product</button>
</div>
<div class="spacer"></div>
</form>
Below are the Javascript portion of the blade.php:
Below are my Controller Methods I have for the update:
public function storeImage(Request $request) {
if($request->file('file')){
// Upload path
$destinationPath = 'img/products/';
// Get File
$image = $request->file('file');
// Get File Name
$imageName = $image->getClientOriginalName();
// Uploading File to given path
$image->move($destinationPath,$imageName);
$product = new Product();
$product->where('prodID', '=', $request->{'prodID'}, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodImage' => $imageName,
]);
}
}
//update Product details
public function update(Request $request, $prodID)
{
if ($this->isCodeExist($request->{'prodCode'}, $request->{'prodID'})) {
return back()->withErrors('This code already exists!');
}
try{
$db = new Product();
$db->where('prodID', '=', $prodID, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodCode' => $request->{'prodCode'},
'prodImage' =>$this->storeImage($request),
'prodDesc' => $request->{'prodDesc'},
'price' => $request->{'price'},
'quantity' => $request->{'quantity'},
'featured' => $request->input('featured') ? true : false,
]);
return back()->with('success_message', 'Product updated successfully!');
} catch (\Illuminate\Database\QueryException $ex) {
Log::channel('merchant_error')->error($ex);
return back()->withErrors('There seems to be an error in updating');
}
}
Controllers/HomeController.php
public function edit(Task $task)
{
return view('edit', compact('task'));
}
public function update(Request $request, Task $task)
{
$request->validate(['title' => 'required|min:3', 'description' => 'required', ]);
$task->title = $request->title;
$task->description = $request->description;
$task->save();
$request->session()
->flash('message', 'Successfully modified the task!');
return redirect('viewalltask');
}
routes/web.php
Route::post('/{task}/', 'HomeController#update')->name('update');
views/edit.blade.php
<form action="{{url('', [$task->id])}}" method="POST">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="row">
<div class="col-md-3" >
<label for="title" >title</label>
<input id="title" type="text" class="form-control" name="title" value="{{$task->title}}" required autofocus>
</div>
<div class="col-md-3">
<label for="description" >description</label>
<input id="description" type="text" class="form-control" name="description" value="{{$task->description}}" required>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-primary" >
Edit
</button>
</div>
</div>
</form>
Error :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
In your routes file the you have declared the wrong method . it should be like this.
Route::put('/{task}', 'HomeController#update')->name('update');
You are using wrong method type in routes as compare to method type in form,
Route::post('/{task}/', 'HomeController#update')->name('update');
Should work.
I tried to edit and updated the employee info, unfortunately, it doesn't work
I fetch the employee id but when I sent the updated data it's not working.
it shows Requested URL not found on the server
this is my controller
public function edit_function($id){
$user = User::find($id);
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,$id){
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
this is my view
<form method="post" action="/updateimages/{{ $user->id }}" enctype="multipart/form-data">
<div class="container">
<div class="jumbotron">
<h2>Update The Information Of Employee</h2>
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label >Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="{{ $user->name }} ">
</div>
<div class="form-group">
<label >Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ $user->email }} ">
</div>
<div class="form-group">
<label >Phone Number:</label>
<input type="text" class="form-control" id="phonenumber" placeholder="Enter Phone Number" name="phonenumber" value="{{ $user->phonenumber }} ">
</div>
<div class="form-group">
<label >Profession :</label>
<input type="text" class="form-control" id="profession" placeholder="Enter Profession" name="profession" value="{{ $user->profession }} ">
</div>
<div class="form-group">
<label >Image :</label>
<input type="file" class="form-control" id="images" placeholder="" name="images" value="{{ $user->images }}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" name="submit" style="width:50%;">Update Data</button>
</div>
</div>
</div>
</form>
this is my route
Route::get('edit_profile/{id}' , "empController#edit_function");
Route::put('/updateimages/{id}', "empController#update");
it shows Requested URL not found on the server
Since I am not a Big fan of Url and id So i will go with
name based routing and Route Model Binding
Step 1: Refactor Routes
Route::get('edit_profile/{user}' , "empController#edit_function")
->name('user.editProfile');
Route::put('/updateimages/{user}', "empController#update")
->name('user.updateProfile');
Step 2: Refactor Controller Method
public function edit_function(User $user)
{
$user = $user;
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,User $user)
{
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
Step 3: Edit Html and Switch to route helper
<form method="POST" action="{{route('user.updateProfile',['user' => $user])}}" enctype="multipart/form-data">
Kindly Comment Below if you are facing any issues
Its because some other route replce your existing route. You can solve it by debugging. it will cost your time. I had a better solution,
You name your route. and call the route by route() function.
From your above information,
It may be,
in route ->
Route::put('/updateimages/{id}', "empController#update")->name('updateImage');
in view (form action) ->
<form method="post" action="{{ route('updateImage', $user->id ) }}" enctype="multipart/form-data">
I am trying to use single form for both data insertion and data update. But I do not know how can it be done.
In my form I've mentioned the action method action="{{action('BookController#create')}}", but I want to use the same form for data insertion and data update.
//book.blade.php
<form class="form-horizontal" method="POST" action="{{action('BookController#create')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" name="NBookName" class="form-control"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-left: 5%;">
<label>Unit Price</label><span class="required">*</span>
<input type="text" maxlength="5" required="required" autocomplete="off" runat="server" name="NBookUnitPrice"/>
</div>
<div class="form-group" style="padding-left: 5%;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
controller code
public function edit($id)
{
$book = Book::find($id);
return view('pages.book',compact('book','id'));
}
route page
// for books
Route::get('/book','BookController#create');
Route::post('/book','BookController#store');
Route::get('/book/{id}','BookController#edit');
I do not know how to process it further.
I am trying to use single form for both data insertion and data update
No you don't, unless you are ready to get killed by another developer who will need to understand what you did there.
You follow the Restful Resource Controllers since Laravel 5.2
It's a quite repetetive solution template
Routes
Route::resource('book', 'BookController');
Controller
class BookController extends Controller {
// Display list of your books
public function index() {
$books = Book::all();
return view('books.index', ['books' => $books]);
}
// Show a form to create a book
public function create() {
return view('books.create');
}
// Show a form to edit a book
public function edit(Book $book) {
return view('books.edit', ['book' => $book]);
}
// Store a new book
public function store(Request $request) {
$this->validate($request, [
'book_name' => 'required|unique:books'
]);
$book = new Book();
$book->book_name = $request->book_name;
if($book->save()) {
return redirect()->route('books.edit', $book)
->with('success', 'Successfully added a book'); // You may print this success message
} else {
return redirect()->back()
->withInput()
->with('error', 'Could not add a book'); // You may print this error message
}
}
// Update existing book
public function update(Request $request, Book $book) {
$this->validate($request, [
'book_name' => 'required|unique:books,book_name,'.$book->getKey().',id'
]);
$book->book_name = $request->book_name;
$book->save();
if($book->save()) {
return redirect()->route('books.edit', $book)
->with('success', 'Successfully updated a book'); // You may print this success message
} else {
return redirect()->back()
->withInput()
->with('error', 'Could not updated a book'); // You may print this error message
}
}
// Delete existing book
public function destroy(Book $book) {
if($book->delete()) {
return redirect()->back()
->with('success', 'Successfully deleted a book'); // You may print this success message
} else {
return redirect()->back()->with('error', 'Could not delete a book'); // You may print this error message
}
}
}
Blade
// Show all of your books using some foreach look and html table
views/books/index.blade.php
// Create a new book
views/books/index.create.php
// Edit an existing book
views/books/index.edit.php
Forms
<!-- Creating a new book (store method) -->
<form action="{{ route('books.store') }}" method="POST">
{{ csrf_field() }}
<input name="book_name" value="{{ old('book_name') ">
<button type="submit">Create</button>
</form>
<!-- Updating an existing book (update method) -->
<form action="{{ route('books.update', $book) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<input name="book_name" value="{{ old('book_name', $book->book_name) ">
<button type="submit">Update</button>
</form>
<!-- Deleting an existing book (destroy method) -->
<form action="{{ route('books.destroy', $book) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Delete</button>
</form>
Didn't test the code, but still, the developer that sits next to you will not kill you for using common solution patterns.
I think you need another one route:
Route::put('/book/{id}, 'BookController#update')->name('book.update');
In your three methods you may do something like this:
public function edit($id)
{
$action = route('book.update', ['id' => $id]);
$book = Book::find($id);
return view('pages.book',compact('book','id', 'action'));
}
And edit your form (i edited action and input values)
<form class="form-horizontal" method="POST" action="
{{ $action }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" value="{{ $book->name ?? '' }}" name="NBookName" class="form-control"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-left: 5%;">
<label>Unit Price</label><span class="required">*</span>
<input type="text" maxlength="5" required="required" autocomplete="off" runat="server" value="{{ $book->price ?? '' }} name="NBookUnitPrice"/>
</div>
<div class="form-group" style="padding-left: 5%;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
Do not merge update, create, delete, etc. methods. Another request => another method.
You are free to use one form to create and update. If you are following CRUD rules your form meethod will be POST for create and PUT for update, so place #method('PUT') inside your form body for that.
Then you need to create route Route::put('/book','BookController#update')->name('book.update'); for update and Route::post('/book','BookController#store')->name('book.store'); for store. Or just Route::resource('/book','BookController') instead all this methods. Check laravel resource doc.
Next step within your BookController create update(Request $request) method with update logic inside and store(Request $request) method with store logic.
That's it.
First of all, put these inputs and buttons bellow in your modal:
<input type="hidden" name="id" id="id" value="" />
<input type="hidden" name="button_action" id="button_action value="insert" />
<input type="submit" name="action" id="action" class="btn btn-success" value="submit" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
For update, give an id by jquery to your id input:
$('#id').val(id);
$('#button_action').val('update');
$('#action').val('update');
then in your controller:
if($request->get('button_action') == "insert") {
$success_output = insert
}
if($request->get('button_action') == "update") {
$success_output = update
}
I have the following problem when trying to edit an "album", hopefully they can help me, I'm a little frustrated haha.
The Form
<form name="editalbum" action="{{ action('AlbumController#postEdit', $album->id) }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<fieldset>
<h2>Editar <strong>{{$album->name}}</strong></h2>
<br></br>
<div class="form-group">
<label for="name">Nombre del proyecto</label>
<input name="name" type="text" class="form-control" value="{{ $album->name }}" required>
</div>
<div class="form-group">
<label for="description">Descripción del proyecto</label>
<textarea name="description" rows="10" cols="50" type="text" class="form-control" value="{{ $album->description }}" required></textarea>
</div>
<div class="form-group">
<label for="location">Locación:</label>
<input name="location" type="text" class="form-control" value="{{ $album->location }}" required>
</div>
<div class="form-group">
<label for="year">Año:</label>
<input name="year" type="text" class="form-control" value="{{ $album->year }}" required>
</div>
<button type="submit" class="btn btn-primary">Editar</button>
</fieldset>
</form>
So far I think everything is going well because I try to post in the ID of the model.
The function:
public function postEdit(Request $request, $id)
{
$album = Album::find($id);
$album = Album::all();
if(count($album) > 0){
$album->name = Input::get('name');
$album->description = Input::get('description');
$album->year = Input::get('year');
$album->location = Input::get('location');
$album->save();
Alert::success('Successfully Updated', 'Congratulations');
return view('admin.dashboard');
} else {
Alert::error('Facilities not found', 'Error');
return view('galeries');
}
I think you made error in routes.php
It should look like this:
Route::post('albums/update/{id}', ['uses' => 'AlbumController#postEdit']);
One solution will be to remove the DI Request object
public function postEdit($id)
{
//rest of code
}
note: the param has to be passed as a array
action="{{ action('AlbumController#postEdit', ['id' => $album->id]) }}"