2

I have the following code. It is suppossed to send the formData of title ,tag and description to the controller for uploading.But I keep recieving this error.

Error :

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)

Here is my code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
    <style>
        .data{
            display:none;
        }

        .dropzone {
          width: 98%;
          margin: 1%;
          border: 2px dashed #3498db !important;
          border-radius: 5px;
          transition: 0.2s;
        }

        .dropzone.dz-drag-hover {
          border: 2px solid #3498db !important;
        }

        .dz-message.needsclick img {
          width: 50px;
          display: block;
          margin: auto;
          opacity: 0.6;
          margin-bottom: 15px;
        }

        span.plus {
          display: none;
        }

        .dropzone.dz-started .dz-message {
          display: inline-block !important;
          width: 120px;
          float: right;
          border: 1px solid rgba(238, 238, 238, 0.36);
          border-radius: 30px;
          height: 120px;
          margin: 16px;
          transition: 0.2s;
        }
        .dropzone.dz-started .dz-message span.text {
          display: none;
        }
        .dropzone.dz-started .dz-message span.plus {
          display: block;
          font-size: 70px;
          color: #AAA;
          line-height: 110px;
        }
    </style>
</head>
<body>
    <div class="container"> 
        <form method="GET"  enctype="multipart/form-data" class="dropzone" id="dropzone">
            <button id='upload'>Upload</button>
            @csrf
        </form>
        <div class='data' ></div> 
    </div>
    <script type="text/javascript">
        var title = $('#title').val();
        var description = $('#description').val();
        max=2
        var thumbnail;
        Dropzone.options.dropzone = {
            maxFiles: max,
            autoProcessQueue: false,
            uploadMultiple: true,
            method:"get",
            maxFilesize: 12,
            url: '/upload',
            init: function() {

                var myDropzone = this;
                $("#upload").click(function(e) {

                    // First change the button to actually tell Dropzone to process the queue.

                    // Make sure that the form isn't actually being sent.
                    e.preventDefault();
                    e.stopPropagation();
                    myDropzone.processQueue();
                });

                this.on("maxfilesexceeded", function(file) {
                    alert('Max of '+ max + ' files');
                    this.removeFile(file);
                });

                this.on("addedfile", function() {
                    this.on('thumbnail', function(file, thumbnail) {
                    thumbnail = file.thumbnail;
                });

                this.on('sending', function (file, xhr, formData) {
                    // Append all form inputs to the formData Dropzone will POST
                    var data = $('.dropzone').serializeArray();
                    $.each(data, function (key, el) {
                        formData.append(el.title, el.description, el.tags);
                    });
                    console.log(formData);
                });


                var myvar = '<div class="form-group">'+
                    '<img class="media-object thumbnail" src="'+ thumbnail +'" />'+
                    '<label for="title">Title</label>'+
                    '<input type="text" class="form-control" id="title" aria-describedby="title" placeholder="Give your image a title"><br>'+
                    '<label for="Description">Description</label>'+
                    '<input type="text" class="form-control" id="description" aria-describedby="Description" placeholder="Describe your image"><br>'+
                    '<label for="Tags">Tags</label>'+
                    '<input type="text" class="form-control" id="Tags" aria-describedby="Tags" placeholder="Give your image tags"><br>'+
                    '<small>Tags are important to let people easily find your image</small><br><br>'+
                    ''
                ;
                $('.data').show();
                $('.data').append(myvar);

            });
        },
        acceptedFiles: ".jpeg,.jpg,.png,.gif",
        addRemoveLinks: true,
        timeout: 50000,
        processQueue: function(file) {
            var name = file.upload.filename;
            $.ajax({
                headers:
                {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                },
                type: 'POSTg',
                url: '{{ url("image/delete") }}',
                data: {
                    title: title,
                    description:description,
                    type:"image",
                    body:"upploaded/img"+filename
                },
                success: function(data) {

                    console.log("File has been successfully removed!!");
                },
                error: function(e) {
                    console.log(e);
                }
            });
            var fileRef;
            return (fileRef = file.previewElement) != null ?
                fileRef.parentNode.removeChild(file.previewElement) : void 0;
        },
        success: function(file, response) {
            console.log(response);
        },
        error: function(file, response) {
            return false;
        }
    };
</script>
</body>
</html>

And here is MyController:

public function upload(StorePostRequest $request)
{

    $title= Post::where('title', $request->input('title'))->first();
    if (!$title == null) {
        return redirect()->back()->withErrors(['Title Already Exists', 'Title already exists']);

        return response()->json(["message" => "Failed","reason" => "Title Already Exists"]);
    }


    $post = Post::create([
        'title' => $request->input('title'),
        'body' => $request->input('body'),
        'description' => $request->input('description'),
        'type' => $request->input('type'),
        'user_id' => auth()->id(),
        'published_at' => $request->has('draft') ? null : \Carbon\Carbon::now()
    ]);
}

StorePostRequest.php:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'body' => 'required',
            'tags' => 'nullable',
            'image' => 'nullable|image|max:2048'
        ];
    }
}

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Turbo
  • 124
  • 11
  • What is in `StorePostRequest`? – Adam Rodriguez May 28 '19 at 21:42
  • `public function upload(StorePostRequest $request)` You hint at `StorePostRequest` in your upload method. Can you post the contents? It looks like this may be giving you your 422 status. – Adam Rodriguez May 28 '19 at 22:12
  • @adam ok.....,.........Done that – Turbo May 28 '19 at 22:31
  • One of your rules is failing validation. Check your request data to see what your are receiving. Your `authorize` method is redundant if your `upload` method is behind authenticated middleware. – Adam Rodriguez May 28 '19 at 22:48
  • @adam ...thanks for trying to help but I got so frustrated with dropzone due to no answer that I left it so....... – Turbo May 28 '19 at 22:55
  • @adam ...I'm still getting the same error in different js library AAGH!!! – Turbo May 28 '19 at 23:17
  • Yes, the problem is your server side validation. Check your request data. – Adam Rodriguez May 28 '19 at 23:18
  • @adam How?..... – Turbo May 28 '19 at 23:20
  • @adam....pls dont abandon me... – Turbo May 28 '19 at 23:21
  • @adam the problem with this lib is that it keeps sending `http://localhost:8000/upload?_=1559085572468` and I have no clue where it is getting the `_` data – Turbo May 28 '19 at 23:22
  • I would suggest replacing `StorePostRequest` with `Request` for now so that you can continue debugging. Dump your request data using the `dd` helper method. Example: `dd($request->all())` at the top of your `upload` method. – Adam Rodriguez May 28 '19 at 23:26
  • @adam Just done that ....still same error...what next? – Turbo May 28 '19 at 23:28
  • As mentioned, it's a validation error. To narrow it down, remove all the rules from the rules() function and just return an empty array (no validation rules) `[]`, if that gives anything else than a 422, proceed by adding the rules one by one until you hit the same error again... – Jane May 29 '19 at 21:03

0 Answers0