0

I'm making a single page application using laravel and vuejs with vue-router. I'm using the api.php routes for my http requests. And whenever I save a data in my news table with image, it shows me an error. What do I need to do with this? enter image description here NewsController.php

<?php

namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\News;
class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return News::latest()->paginate(10);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|string|max:191|unique:news',
            'subtitle' => 'required|string|max:191',
            'body' => 'required|string',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ]);


        $news = new News;
        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/news/' . $filename);
                \Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
        }

        $news->save();
    }
}

News.vue

<!-- Vform -->
                                  <form @submit.prevent="createNews()">
                                    <div class="form-group">
                                    <label>News Title</label>
                                    <input
                                    v-model="form.title"
                                    type="text" name="title"
                                    placeholder="Title"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('title') }">
                                    <has-error :form="form" field="title"></has-error>
                                    </div>

                                    <div class="form-group">
                                    <label>Subtitle</label>
                                    <input
                                    v-model="form.subtitle"
                                    type="text"
                                    name="subtitle"
                                    placeholder="Subtitle"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('subtitle') }">
                                    <has-error :form="form" field="subtitle"></has-error>
                                    </div>

                                    <div class="form-group">
                                    <label>News Content</label>
                                    <textarea
                                    v-model="form.body"
                                    type="text"
                                    name="body"
                                    placeholder="News Content"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('body') }">
                                    </textarea>
                                    <has-error :form="form" field="body"></has-error>
                                    </div>


                                    <div class="form-group">
                                    <label>Picture</label>
                                    <input type="file" id="image"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('image') }">
                                    <has-error :form="form" field="image"></has-error>
                                    </div>


                        <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                         <!-- <button  v-show="editmode" type="submit" class="btn btn-primary">Update</button> -->
                        <button type="submit" class="btn btn-success">Create</button>
                         </div>
                        </form>
                        <!-- vform -->

<script>
    export default {
        data(){
            return{
                news: {},
                form: new Form({
                    id:"",
                    title: "",
                    subtitle:"",
                    body:"",
                    image:"",
                    postedby:""
                })
            }
        },

        methods: {
            loadNews(){
                axios.get('api/news')
                    .then(({data}) => (this.news = data))
            },
            createNews(){
                this.$Progress.start()
                this.form.post("api/news")
                    .then(()=>{
                         $("#addNews").modal("hide")
                         $(".modal-backdrop").remove()
                        swal.fire("Created!", "", "success")
                    })
                this.$Progress.finish()
            },
        },

        created() {
            console.log('Component mounted.')
            this.loadNews()
        }
    }
</script>

api.php

Route::apiResource('news', 'API\NewsController');

2 Answers 2

1

Did you checked that your are using a multipart/form-data encoding ?

Edit: https://github.com/cretueusebiu/vform/blob/master/example/upload.html

Sign up to request clarification or add additional context in comments.

13 Comments

im just using a package called vform and i followed the instructions there, and I can submit all data except for the image
Don't hesitate to look on github issues ;) github.com/cretueusebiu/vform/issues/12 Here someone had the same problem. You need to transform your object to a FormData. github.com/cretueusebiu/vform/blob/master/example/upload.html developer.mozilla.org/en-US/docs/Web/API/FormData
so there is nothing wrong with my controller sir? I find it difficult to understand but ill try to understand it
I don't know if your controller is ok. If i were you, i will first check if my form is right encoded. You can check that using your developer tool. Open it, use "Network" tab, then send your form. You should see your request sent. Click on it then click on "Headers". Then scroll down, you should see your request data. It should be named as "FormData". Click on "view source". You should see ------WebKitFormBoundary etc. Also, it will inform you of the Content-Type used. Then if it's ok, you can check your controller.
nothing changes in my image field whenever I put some file in it. But when I input some text in the title in the form, the title in the form data changes immediately sir.
|
0

put this code in your Vue file

 <div class="col-sm-12">
                  <input
                    type="file"
                    @change="updateImage"
                    class="form-input"
                    :class="{ 'is-invalid': form.errors.has('image') }"
                    id="image"
                    name="image"
                  />
                  <has-error :form="form" field="image"></has-error>
                </div>

<script>
    export default {
        data(){
            return{
                news: {},
                form: new Form({
                    id:"",
                    title: "",
                    subtitle:"",
                    body:"",
                    image:"",
                    postedby:""
                })
            }
        },

        methods: {
updateImage(e) {
      let file = e.target.files[0];
      console.log(file);
      let reader = new FileReader();
      if (file["size"] < 2111775) {
        reader.onloadend = file => {
          this.form.image= reader.result;
        };
        reader.readAsDataURL(file);
      } else {
        swal.fire({
          type: "error!",
          title: "Oops...",
          text: "Your are uploading a large File "
        });

        // return ["warning", "file size"];
        Fire.$emit("refreshPage");
      }
    },
            loadNews(){
                axios.get('api/news')
                    .then(({data}) => (this.news = data))
            },
            createNews(){
                this.$Progress.start()
                this.form.post("api/news")
                    .then(()=>{
                         $("#addNews").modal("hide")
                         $(".modal-backdrop").remove()
                        swal.fire("Created!", "", "success")
                    })
                this.$Progress.finish()
            },
        },

        created() {
            console.log('Component mounted.')
            this.loadNews()
        }
    }
</script>

your controller code is

<?php

namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\News;
class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return News::latest()->paginate(10);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|string|max:191|unique:news',
            'subtitle' => 'required|string|max:191',
            'body' => 'required|string',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ]);


        $news = new News;
        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        if ($request->hasFile('image')){
$name = time().'.'.explode('/',explode(':',substr($request->image,0,strpos($request->image,';')))[1])[1];
                    \Image::make($request->image)->save(public_path('img/news/').$name);


            //Update DB
                $news->image = $name ;

        }

        $news->save();
    }
}

If it worked let me know I will provide code for update

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.