Problem with action Controller@store not defined in Laravel 8

Viewed 8372

I'm still exploring Laravel 8 but I have a problem with my controller's store() method 'not defined.'

InvalidArgumentException Action PostsController@store not defined. (View: D:\Server\htdocs\app\resources\views\posts\create.blade.php)

I believe I have actually defined it and I used a resources route.

Route

Route::resource('posts', PostsController::class); 

Blade

@extends('layouts.app')

@section('content')
    <h1>Create Post</h1>

    {!! Form::open(['action' => 'PostsController@store', 'method' => 'POST']) !!}
    <div class="form-group">
        {{Form::label('title', 'Title')}}
        {{Form::label('title', ['class' => 'form-control','placeholder' =>'Title'])}}
    </div>
    <div class="form-group">
        {{Form::label('body', 'Body')}}
        {{Form::textarea('body', ['class' => 'form-control','placeholder' =>'Body'])}}
    </div>

    {{Form::submit('Submit',['class' =>'btn btn-primary'])}}
    {!! Form::close() !!}

@endsection

Controller

class PostsController extends Controller
{
    public function create()
    {
        return view('posts.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'body' => 'required'
        ]);

        return 143;
    }
}

enter image description here

4 Answers

Go into your RouteServiceProvider and set the $namespace property to App\Http\Controllers if you want there to be a namespace prefix added when generating URLs for actions.

Otherwise you should be referring to your Controllers by their Fully Qualified Class Name (FQCN).

['action' => 'App\Http\Controllers\PostsController@store', ...]

Alternatively you can try using a named route in your case since that is a resource PostsController you should have the Route name posts.store

route('posts.store')

The instance of incoming request will be automatically injected in your PostsController@store definition as the parameter by the Laravel service container.

I had a similar case but I was not using a resource controller. So I had to explicitly define a route for that particular action.

you should use route instead of action in your form. try something like

{!! Form::open(['route' => 'products.store', 'method' => 'POST']) !!}

I understand your where the problem occurs. You have used.

{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST']) !!}

which is wrong, instead of this you have to use.

{!! Form::open(['url' => 'PostsController@store', 'method' => 'POST']) !!}

I hope, your problem will be solved.

Related