Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

basosneo's avatar

Category Edit ; admin pannel

hi friends, I am following a tutorial of laravel 5.2 about an online sales page and I am in the administration panel;

The problem is that when trying to edit a category I have two problems;

  1. My database is not loaded for each category, instead it loads the page but with the empty category data.

  2. when trying to update any category (filling in the fields that come out empty) I get the following error;

MethodNotAllowedHttpException in RouteCollection.php line 233:

edit.blade

  @extends('admin.template')

  @section('content')

  <div class="container text-center">
    <div class="page-header">
        <h1>
            <i class="fa fa-shopping-cart"></i>
            CATEGORÍAS <small>[Editar categoría]</small>
        </h1>
    </div>

    <div class="row">
        <div class="col-md-offset-3 col-md-6">
            
            <div class="page">
                
                @if (count($errors) > 0)
                    @include('admin.partials.errors')
                @endif
                
                {!! Form::model($category, array('route' => array('category.update', $category))) !!}

                    <input type="hidden" name="_method" value="PUT">
    
                    <div class="form-group">
                        <label for="name">Nombre:</label>
                        
                        {!! 
                            Form::text(
                                'name', 
                                null, 
                                array(
                                    'class'=>'form-control',
                                    'placeholder' => 'Ingresa el nombre...',
                                    'autofocus' => 'autofocus'
                                )
                            ) 
                        !!}
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Descripción:</label>
                        
                        {!! 
                            Form::textarea(
                                'description', 
                                null, 
                                array(
                                    'class'=>'form-control'
                                )
                            ) 
                        !!}
                    </div>
                    
                    <div class="form-group">
                        {!! Form::submit('Actualizar', array('class'=>'btn btn-primary')) !!}
                        <a href="{{ route('admin.category.index') }}" class="btn btn-warning">Cancelar</a>
                    </div>
                
                {!! Form::close() !!}
                
            </div>
            
        </div>
    </div>
    </div>

    @stop

web.php

  Route::get('category/create', [
'as' => 'admin.category.create',
'uses' => 'CategoryController@create'
 ]);

  Route::get('category/store', [
'as' => 'admin.category.store',
'uses' => 'CategoryController@store'
  ]);

  Route::get('category', [
'as' => 'admin.category.index',
'uses' => 'CategoryController@index'
  ]);

 Route::get('category/edit/{id}', [
'as' => 'admin.category.edit',
  'uses' => 'CategoryController@edit'
 ]);

Category.controller

 namespace App\Http\Controllers\Admin;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 use App\Category;


 class CategoryController extends Controller
 {
      public function index()
   {
    $categories = Category::all();
    //dd($categories);
    return view('admin.category.index', compact('categories'));
    }
    public function create()
   {
    return view('admin.category.create');
    }
    public function store(Request $request)
    {
    $this->validate($request, [
      'name' => 'required|unique:categories|max:255',
       ]);
    
    $category = category::create([
        'name' => $request->get('name'),
        'slug' => str_slug($request->get('name')),
        'description' => $request->get('description'),
        
       ]);
    
       $message = $category ? 'Categoría agregada correctamente!' : 'La Categoría NO pudo agregarse!';
    
       return redirect()->route('admin.category.index')->with('message', $message);
    }

    public function show(Category $category)
    {
       return $category;
    }

public function edit(Category $category)
   {
       return view('admin.category.edit', compact('category'));
   }
}

Do you need any other information?

0 likes
22 replies
tykus's avatar

Your form has null as the value for the category e.g.

{!! 
    Form::text(
        'name', 
        null, // $category->name 
        array(
            'class'=>'form-control',
            'placeholder' => 'Ingresa el nombre...',
            'autofocus' => 'autofocus'
        )
    ) 
  !!}   
basosneo's avatar

I changed it, but the mistakes are the same

    {!! Form::model($category, array('route' => array('category.update', $category))) !!}

                    <input type="hidden" name="_method" value="PUT">
    
                    <div class="form-group">
                        <label for="name">Nombre:</label>
                        
                        {!! 
                            Form::text(
                                'name', 
                               $category->name,  
                                array(
                                    'class'=>'form-control',
                                    'placeholder' => 'Ingresa el nombre...',
                                    'autofocus' => 'autofocus'
                                )
                            ) 
                        !!}
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Descripción:</label>
                        
                        {!! 
                            Form::textarea(
                                'description', 
                                $category->description,
                                array(
                                    'class'=>'form-control'
                                )
                            ) 
                        !!}
                    </div>
Snapey's avatar

one thread for one issue please

tykus's avatar

@basosneo are you seeing a specific error, or are you just seeing a blank form? Can you show us the edit action from your controller?

basosneo's avatar

@tykus I have already put my controller, my routes and my form ... now I have nothing more to show .. so I'll put the index.blade that is where the botton to edit and my complete routes and remember that my Problem is that my form does not want to read data from the database and will not let me update

index.blade

<div class="container text-center">
    <div class="page-header">
        <h1>
            <i class="fa fa-shopping-cart"></i>
            CATEGORÍAS <a href="{{ route('admin.category.create') }}" class="btn btn-warning"><i class="fa fa-plus-circle">Categoria</i></a>
        </h1>
    </div>
    <div class="page">
        <div class="table-responsive">
            <table class="table table-striped table-bordered table-hover">
                <thead>
                    <tr>
                    <th>Editar</th>
                    <th>Eliminar</th>
                    <th>Nombre</th>
                <th>Descripción</th>
                    </tr>
                </thead>
                
                <tbody>
    @foreach($categories as $category)
        
        <tr>
            <td>
                <a href="{{ route('admin.category.edit', $category) }}" class="btn btn-primary"><i class="fa fa-pencil-square"></i></a>
            </td>
            <td>
                <a href="" class="btn btn-danger"><i class="fa fa-trash"></i></a>
            </td>
            <td>{{ $category->name }}</td>
            <td>{{ $category->description }}</td>
        </tr>

    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

@stop

web.php

       // ADMIN -------------

       Route::group(['namespace' => 'Admin', 'middleware' => ['auth'], 'prefix' => 'admin'], function()
     {

   Route::get('home', function(){
    return view('admin.home');
   });

        Route::resource('category', 'CategoryController');

       Route::resource('products', 'ProductController');

        Route::resource('user', 'UserController');

             Route::get('orders', [
    'as' => 'admin.order.index',
    'uses' => 'OrderController@index'
]);

    Route::post('order/get-items', [
    'as' => 'admin.order.getItems',
    'uses' => 'OrderController@getItems'
]);

     Route::get('order/{id}', [
    'as' => 'admin.order.destroy',
    'uses' => 'OrderController@destroy'
]);


        //Routes of Pannel Admin

     Route::getallheaders(oid)('category/create', [
'as' => 'admin.category.create',
'uses' => 'CategoryController@create'
     ]);

    Route::post('category/store', [
'as' => 'admin.category.store',
'uses' => 'CategoryController@store'
     ]);

   Route::get('category', [
'as' => 'admin.category.index',
'uses' => 'CategoryController@index'
      ]);

      Route::get('category/edit/{id}', [
      'as' => 'admin.category.edit',
       'uses' => 'CategoryController@edit'
      ]);

      });
tykus's avatar
tykus
Best Answer
Level 104

So if you check that the route-model binding is actually working in the edit method:

dd($category);

you will find that it is not because you are not following the rule where the route definition must have the name of the variable

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name

So, change the route definition to this:

 Route::get('category/edit/{category}', [
    'as' => 'admin.category.edit',
    'uses' => 'CategoryController@edit'
 ]);
basosneo's avatar

awesome men, thats a solution... so, now i have another problem... when i give the botton update hes following these error:

ReflectionException in RouteSignatureParameters.php line 39: Method App\Http\Controllers\Admin\CategoryController::update() does not exist

I clearly that i have no function for the update, but I thought that was done automatically with the form. How is the way to create this function?

thanks!

tykus's avatar

Mark it as answered in that case.

You need to write the update() method in the CategoryController - Laravel does a lot for you but not everything.

public function update (Request $request, Category $category)
{
    $this->validate($request, [
        'name' => 'required|unique:categories|max:255',
    ]);
    
    $category->update([
        'name' => $request->get('name'),
        'slug' => str_slug($request->get('name')),
        'description' => $request->get('description'),
       ]);
    
    
       return redirect()->route('admin.category.index'); 
}

basosneo's avatar

hey @tykus i have another consult; i add one form to delete a category;

   <td>
                {!! Form::open(['route' => ['admin.category.destroy', $category]]) !!}
                    <input type="hidden" name="_method" value="DELETE">                                         <button onClick="return confirm('Eliminar registro?')" class="btn btn-danger">
                                        <i class="fa fa-trash-o"></i>
                    </button>
                {!! Form::close() !!}
            </td>

and these route;

 Route::get('category/destroy/{category}', [
  'as' => 'admin.category.destroy',
  'uses' => 'CategoryController@destroy'
  ]);

I threw the following error

 NotFoundHttpException in Handler.php line 131: No query results for model [App\Category].

How can I create a correctly route for the destroy?

tykus's avatar

The route definition should be (the delete method matches the HTTP verb)

 Route::delete('category/destroy/{category}', [
  'as' => 'admin.category.destroy',
  'uses' => 'CategoryController@destroy'
  ]);

and you should have a destroy() method in the CategoryController

public function destroy(Category $category)
{
    $category->delete();

    return redirect()->route('admin.category.index'); 
}

I just looked back to see why the model not found error was raised and note that you had defined a resource route also for the Category resource; you should delete it if you want to rely on the explicit route definitions

Route::resource('category', 'CategoryController'); // remove this line
basosneo's avatar

Yeah, thanks @tykus, I do not know why my route: resource did not work..

And when I change everything you told me I got the following error

NotFoundHttpException in RouteCollection.php line 161:

tykus's avatar

Has everything broken whenever you have removed the Route::resource('category', 'CategoryController'); line, i.e. show, edit, update etc.?

basosneo's avatar

no no, just when I give the delete button i have the error;

NotFoundHttpException in RouteCollection.php line 161:

The other works normally, at times

and these are my function

 public function destroy(Category $category)
   {
      
    return $category;

    //$deleted = $category->delete();
    
    //$message = $deleted ? 'Categoría eliminada correctamente!' : 'La Categoría NO pudo eliminarse!';
    
   // return redirect()->route('admin.category.index')->with('message', $message);
     }
tykus's avatar

Check your routes $ php artisan route:list to see that the DELETE route is there for the Category resource. As a sanity check, make sure that HTTP verb, URI, route name and Controller@method are all as expected. Second sanity check: make sure there is only one route defined for that URI and verb.

basosneo's avatar

my route.list

 +--------+----------+------------------------------------+------------------------+-------------------------------------------------------+--------------+
 | Domain | Method   | URI                                | Name                   | Action                                                | Middleware   |
  +--------+----------+------------------------------------+------------------------+-------------------------------------------------------+--------------+
 |        | GET|HEAD | /                                  | home                   | App\Http\Controllers\StoreController@index            | web          |
|        | GET|HEAD | admin/category                     | admin.category.index   | App\Http\Controllers\Admin\CategoryController@index   | web,auth     |
|        | GET|HEAD | admin/category/create              | admin.category.create  | App\Http\Controllers\Admin\CategoryController@create  | web,auth     |
|        | DELETE   | admin/category/destroy/{category}  | admin.category.destroy | App\Http\Controllers\Admin\CategoryController@destroy | web,auth     |
|        | GET|HEAD | admin/category/edit/{category}     | admin.category.edit    | App\Http\Controllers\Admin\CategoryController@edit    | web,auth     |
|        | POST     | admin/category/store               | admin.category.store   | App\Http\Controllers\Admin\CategoryController@store   | web,auth     |
|        | GET|HEAD | admin/home                         |                        | Closure                                               | web,auth     |
|        | GET|HEAD | api/user                           |                        | Closure                                               | api,auth:api |
 |        | GET|HEAD | auth/login                         | login-get              | App\Http\Controllers\Auth\AuthController@getLogin     | web,guest    |
|        | POST     | auth/login                         | login-post             | App\Http\Controllers\Auth\LoginController@Login       | web,guest    |
|        | GET|HEAD | auth/logout                        | logout                 | App\Http\Controllers\Auth\AuthController@getLogout    | web          |
|        | GET|HEAD | auth/register                      | register-get           | App\Http\Controllers\Auth\AuthController@getRegister  | web,guest    |
|        | POST     | auth/register                      | register-post          | App\Http\Controllers\Auth\RegisterController@Register | web,guest    |
|        | GET|HEAD | cart/add/{products}                | cart-add               | App\Http\Controllers\CartController@add               | web          |
|        | GET|HEAD | cart/delete/{products}             | cart-delete            | App\Http\Controllers\CartController@delete            | web          |
|        | GET|HEAD | cart/show                          | cart-show              | App\Http\Controllers\CartController@show              | web          |
|        | GET|HEAD | cart/trash                         | cart-trash             | App\Http\Controllers\CartController@trash             | web          |
|        | GET|HEAD | cart/update/{products}/{quantity?} | cart-update            | App\Http\Controllers\CartController@update            | web          |
|        | GET|HEAD | order-detail                       | order-detail           | App\Http\Controllers\CartController@orderDetail       | web,auth:web |
|        | GET|HEAD | products/{slug}                    | products-detail        | App\Http\Controllers\StoreController@show             | web          |
+--------+----------+------------------------------------+------------------------+-------------------------------------------------------+--------------+

whatever friend, I wanted to see the categories only and it did not work; Then remove the comments and leave the function norm and and now it works Thanks so much for all

tykus's avatar

So, the route is there - you should be able to make a DELETE request to /admin/category/destroy/{category} so I am wondering now if the problem lies with your Laravel Collective form. I believe that you should you be passing in a $category->id not the $category model

<td>
    {!! Form::open(['route' => ['admin.category.destroy', $category->], 'method' => 'DELETE']) !!}
    <button onClick="return confirm('Eliminar registro?')" class="btn btn-danger">
        <i class="fa fa-trash-o"></i>
    </button>
    {!! Form::close() !!}
</td>

Notice also that you can pass a method when you open the form so you don't need to create the hidden field yourself ;)

basosneo's avatar

hey @tykus How can I do a logical erasure ?, because if I am not mistaken I am doing a physical erasure

Please or to participate in this conversation.