the store route won't take POST as a method

627 Views Asked by At

am working on a simple blog project using Laravel, i was trying to store the data passed by my create post form to my store controller and it won't accept the POST method. even tho whenever i list my routes i see that the store route accept a post method . i used a get method and that worked . until i tried to upload images, it started telling me that the image file must be an image even tho it is an image. i then discovered the image is not being passed by the form in the first place

    {{ Form::open(['action' => 'PostsController@store', 'method'=> 'GET', 'enctype' => 'multipart/form-data']) }}
    <div class="form-group">
        {{Form::label('title', 'Title')}}
        {{Form::text('title' , '' , ['class'=> 'form-control', 'placeholder'=> 'this is a title place holder'])}}
    </div>
    <div class="form-group">
        {{Form::label('body', 'body')}}
        {{Form::textarea('body' , '' , [ 'id' => 'article-ckeditor' , 'class'=> 'form-control', 'placeholder'=> 'body'])}}
    </div>
    <div class="form-group">
        {{Form::file('cover_image')}}
        <input type="hidden" name="_method" value="POST">

    </div>
    {{Form::submit('Submit',['class'=>"btn btn-info"])}}
{{ Form::close() }}

and this is my controller

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

    //handle file upload

    if($request->hasFile('cover_image')){

        $image = $request->file('cover_image');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('storage/coverimages/' . $filename );
        image::make($image)->resize(800, 400)->save($location);

    }
    else{
        echo 'this is shit';
        $filename = 'noimage.jpg';
    }

    //create post
    $post = new Post;
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->user_id = auth()->user()->id;
    $post->cover_image = $filename;
    $post->save();

    return redirect('/posts')->with('success', 'Post created');
}
3

There are 3 best solutions below

0
Harry Milton On

See here

Form::open(['action' => 'PostsController@store', 'method'=> 'GET', 'enctype' => 'multipart/form-data'])

'method'=>'GET' so your form will be submitted as GET request and not POST.

0
Zadat Olayinka On

try this on your form declaraction 'files' => true

0
Hussam Adil On

First

I noticed you are using

<input type="hidden" name="_method" value="POST">

you don't need to use form method spoofing. Post method already supported in laravel as HTTP request method. check the laravel documentation

second

You are submiting form so don't use get method use Post instead