Laravel 5.1 Creating default object from empty value - php

I am using Laravel 5.1 PHP framework. When I try to update my record, I get the error:
"ErrorException in AdminController.php line 108: Creating default
object from empty value".
I have searched in google but I can't find any results to solve my problem.
Routes
Route::get('/admin/no', 'AdminController#index');
Route::get('/admin/product/destroy/{id}', 'AdminController#destroy');
Route::get('/admin/new', 'AdminController#newProduct');
Route::post('/admin/product/save', 'AdminController#add');
Route::get('/admin/{id}/edit', 'AdminController#edit');
Route::patch('/admin/product/update/{id}', 'AdminController#update')
AdminController
public function edit($id)
{
$product = Product::find($id);
return view('admin.edit', compact('product'));
}
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->id = Request::input('id');
$product->name = Request::input('name');
$product->description = Request::input('description');
$product->price = Request::input('price');
$product->imageurl = Request::input('imageurl');
$product->save();
//return redirect('/admin/nο');
}
enter code here
edit.blade.php
div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Edit Product</div>
</div>
<div class="panel-body" >
<form action="/admin/product/update/{id}" method="POST"><input type="hidden" name="_method" value="PATCH"> <input type="hidden" name="_token" value="{{ csrf_token() }}">
enter code here

The problem is that $product = Product::find($id); returns NULL. Add the check:
if(!is_null($product) {
//redirect or show an error message
}
Though this is your update method, so probably you're having an error while building the url for this method. It might be a wrong id you're passing to this route.
Your form action has an error:
<form action="/admin/product/update/{id}" method="POST">
Notice the curly braces, Blade's syntax is {{ expression }}, not just {}. So id is never passed to the product.update route. Just change it to:
<form action="/admin/product/update/{{$id}}" method="POST">

check if the product exists then do the update
The form will look like this
<form action="/admin/product/update/{{$id}}" method="POST">
$ sign was missing :)

For update entity in laravel uses PUT method not POST. update form method and try.
<form action="/admin/product/update/{id}">
<input name="_method" type="hidden" value="PUT">

Check your web.php file maybe mistake your controller name.

This may be helpful for similar issues for others..
Instead of $product = Product::find($id); use $product = Product::where('some_other_id', $id);. I am saying this because you might be giving reference to some_other_id like a foreign key instead of primary key.

Related

How to add a custom method to resource controller in Laravel 5.6

What is the correct way of adding a custom method to a resource controller in Laravel 5.6?
What I have so far is a new method in my ProfileController:
public function approve($id){
$user = User::find($id);
$user->state = '1';
$user->save();
return redirect('/dashboard')->with('success', 'User approved.');
}
As well as the following lines added to my web.php file:
Route::post('/profile/{$id}/approve', 'ProfileController#approve');
Route::resource('profile', 'ProfileController');
The form in my view is (afaik) correctly rendered to:
<form method="POST" action="http://myurl.com/profile/10/approve" accept-charset="UTF-8">
<input name="_token" type="hidden" value="v3F1RRhi7iJL2o4egOhcRiuahaGQBwkGkfMal1lh">
<input name="_method" type="hidden" value="PATCH">
<input class="btn btn-success" type="submit" value="Approve User">
</form>
Unfortunately nothing happens, except the "Sorry, the page you are looking for could not be found." page to be shown.
What am I missing? And to expand a bit on this question also, is this even a valid way to implement "single field updates" on a db entry?
Thank you for your help!
i see you have two problems:
firstly correct the route like that
Route::post('/profile/{id}/approve', 'ProfileController#approve');
secondly you have to delete
<input name="_method" type="hidden" value="PATCH">
or replace your route like that:
Route::patch('/profile/{id}/approve', 'ProfileController#approve');
You would want to remove the $ sign from your route:
Route::post('/profile/{id}/approve', 'ProfileController#approve');
The rest of it is correct.
You have written the parameter like var: $id, and you may write it without '$'.
But really you can use the Laravel implicit model binding function to do this:
Route::post('/profile/{user}/approve', 'ProfileController#approve');
And then in your controller:
public function approve(User $user){
// Delete this line--> $user = User::find($id);
$user->state = '1';
$user->save();
return redirect('/dashboard')->with('success', 'User approved.');
}

Laravel 5.2 Form update error

Okay so guys i've a problem when working with laravel's update & i've spent 3 days and no one can solve my problem too so i decide to ask you all pro coder, please kindly help me
First, this is part of my View (editkeluhan.blade.php)
<form class="form-horizontal" role="form" method="POST" action="{{ url('/editkeluhanadmin/{$keluhan->id}') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div>
<input name="_method" type="hidden" value="PATCH">
</div>
Second, This is my Route
Route::get('editkeluhan/{id}','AdminController#editkeluhan');
Route::post('editkeluhanadmin/{id}', 'AdminController#updatekeluhanadmin');
public function editkeluhan($id){
$halaman="tindaklayanan";
$keluhan=keluhan::findOrFail($id);
return view('layanankonsumen.editkeluhan',compact('keluhan','halaman'));
}
public function updatekeluhanadmin(Keluhan $keluhan, Request $r){
$halaman = 'tindaklayanan';
$keluhan->update($r->all());
return redirect('/');
Third, this is AdminController
public function editkeluhan($id){
$halaman="tindaklayanan";
$keluhan=keluhan::findOrFail($id);
return view('layanankonsumen.editkeluhan',compact('keluhan','halaman'));
}
public function updatekeluhanadmin(Keluhan $keluhan, Request $r){
$halaman = 'tindaklayanan';
$keluhan->update($r->all());
return redirect('/');
}
This is ERROR, but when i change my Route into this
Route::resource('editkeluhanadmin', 'AdminController#updatekeluhanadmin');
Error is gone BUT Its not update in database
Please Please Help me
You use PATCH action in your form
<input name="_method" type="hidden" value="PATCH">
so you need to change your route to:
Route::patch('editkeluhanadmin/{id}', 'AdminController#updatekeluhanadmin');
Visit https://laracasts.com/discuss/channels/laravel/update-form-data-laravel-52 to see my disscussion there & the answer if anyone need, good luck.

MethodNotAllowedHttpException in RouteCollection.php line 218

i'm new to laravel, and i found few decent tutorials to help me understand and get started with it.
the problem is-> whenever i want to use the post method this exception raises MethodNotAllowedHttpExceptionbut unlike, maybe 99% of who asked similar questions, in my case it says the exception is in RouteCollection.php line 218, which is unusual but not to laravel 5.2.x
the following is the methode post in routes.php:
Route::post('/ajouter_produit',
[
'uses'=>'ProductController#addProduct',
'as'=>'ajouter_produit',
]);
i even tried adding this method to a middleware route group but the problem remained.
this is my controller:
public function addProduct (Request $request)
{
$this->validate($request, [
'label'=>'required|alpha',
'prix'=>'required|numeric',
]);
$prod = new Product();
$prod->label=$request['label'];
$prod->type=$request['type'];
$prod->prix=$request['prix'];
$prod->save();
return view('welcome');
}
and this is my form:
<form action="{{ route('ajouter_produit') }}" method="post" >
<input type="text" name="label" id="label"/>
<select name="type" id="type">
<option value="1">Par unité</option>
<option value="2" selected>Par kilo</option>
</select>
<input type="text" name="prix" id="prix"/>
<button type="submit">Ajouter</button>
<input type="hidden" value="{{ Session::token() }}" name="_token"/>
i also tried this but it raised the same problem:
Route::post('/trypost', function () {
return 'hello post';
});
can you please help me !!
if you need any other source just ask for it.
Every effort will be much appreciated. thank you
take note that if you are using route(), it is expecting route name, such as user.store or user.update.
so my suggestion is, try use url() for your open form
<form action="{{ url('ajouter_produit') }}" method="post" >
more details on laravel docs
"#mydo47: Missing method get. First you should create route with method get return view. Next, in view page you call method post validate and save to your model." this solved it

how to print the database content on a desired page?

I am using laravel 5.2. I want to print the database content that is stored in my database dynamically on the desired page. I tried but an error appears everytime i.e;( undefined variable:). I just want to print whatever content I store in my database table dynamically.
My code is here:
My model name is:gallery
My routes:
Route::get('/gallery/list' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/gallery/save' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);
My controller:
public function viewgallerylist()
{
$galleries = gallery::all();
return view('gallery')->with('galleries', $galleries);
}
public function savegallery(Request $request)
{
$gallery1=$request['gallery_name'];
$gallery=new gallery();
$gallery->name=$gallery1;
$gallery->save();
return redirect()->route('viewgallery');
}
My desired page:
<form method="post" action="{{ route('savegallery') }}">
<input class="form-control" type="text" name="gallery_name">
<button type="submit" class="btn btn-primary" id="upl">Create+</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
#foreach($galleries as $gallery)
<p>{{ $gallery->name }}</p>
#endforeach
Most model Classes will have a capital letter. Are you sure your Model isn't called Gallery instead of gallery?
which means that you need to call Gallery::all() in your controller and make sure use App\Gallery; is at the top of your page.
public function viewgallerylist()
{
$galleries = Gallery::all();
return view('gallery')->with('galleries', $galleries);
}
The problem might be with your model.... please provide a larger view
Route::get('/' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);

delete data from database using model in laravel 5

I am trying to delete data from my table employes by getting the id of the data and transferring it by using get route but i get the following error
ModelNotFoundException in Builder.php line 125: No query results for
model [App\employe].
her is my route
Route::get('/delete/{employe}', 'EmployeController#delete');
Route::post('/delete', 'EmployeController#handleDelete');
and i have model called employe to access my table
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class employe extends Model {
protected $fillable = array('fname','lname','age','sex','phone','email','houseno','city','kebele','state','username','password','workposition','salary','bankaccount','bankname','contactid','employedate');
}
part of my controller for deleting
public function delete(employe $employe)
{
// Show delete confirmation page.
return View('deleteemploye', compact('employe'));
}
public function handleDelete()
{
$employe = employe::findOrFail(Input::get('employe'));
$employe->delete();
return Redirect::action('EmployeController#index');
}
her is my view for deleting file
#extends('app')
#section('content')
<div class="page-header">
<h2>Delete {{$employe->fname}} Are you sure?</h2>
</div>
<form action="{{ action('EmployeController#handleDelete') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="employe" id="employe" value="{{ $employe->id }}" />
<input type="submit" class="btn btn-default" value="Yes" />
No
</form>
#stop
Looks like laravel cant find the model with the primary key you are passing. Check the database and see if its there. If it is check the deleted_at field. If it has a date in it, it means it is already deleted. You can still find it by using withTrashed()
$employe = employe::withTrashed()->findOrFail(Input::get('employe'));
and if you have soft deleting enabled for this model, you can completely remove the given row by running
$employe = employe::withTrashed()->findOrFail(Input::get('employe'))->forceDelete();

Categories