получил 302 при обновлении формы в laravel

Я столкнулся с проблемой перенаправления 302 при публикации данных для обновления всего, что было успешно обновлено, кроме изображения, где я получаю 302, и моя страница перенаправляется.

вот мой код лезвия формы:

{!! Form::model($post, ['method' => 'PATCH','route' => ['posts.update', $post->id],'data-parsley-validate' => '','class' => 'form-horizontal','files'=>true,'name'=>'updateabout']) !!}

<div class="col-md-8">

    <input type="hidden" name="csrf_test_name" value="{!! csrf_token() !!}">
    <div class="form-group">
        <label class="col-md-2 control-label"> Title : </label>
        <div class="col-md-10">
            <input class="form-control " name="title" type="text" value="{{$post->title}}" id="title">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">Slug:</label>
        <div class="col-md-10">
            <input class="form-control" name="slug" type="text" value="{{$post->slug}}" id="slug">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Category:</label>
        <div class="col-md-10">
            {{ Form::select('category_id', $categories, null, ['class' => 'form-control']) }}

        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Tags:</label>
        <div class="col-md-10">
            {{ Form::select('tags[]', $tags, null, ['class' => 'form-control select2-multi', 'multiple' => 'multiple']) }}
        </div>
    </div>


    <div class="form-group">
        <label class="col-md-2 control-label">Short-Description:</label>
        <div class="col-md-10">
            <textarea name="short_description" class="form-control" maxlength="140" rows="7" required
                      id="shortdesc">{{$post->short_description}}</textarea>
            <script src="{{ asset("/public/admin/ckeditor/ckeditor.js") }}"></script>
            <script>
                CKEDITOR.replace('shortdesc', {
                    height: 100,
                    toolbar: 'Custom', //makes all editors use this toolbar
                    toolbarStartupExpanded: false,
                    toolbarCanCollapse: false,
                    toolbar_Custom: [] //define an empty array or whatever buttons you want.
                });
            </script>
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">Date:</label>
        <div class="col-md-10">
            {{ Form::text('date', null, ['class' => 'form-control','id'=>'date']) }}
        </div>
        <script type="text/javascript">
            $(document).ready(function () {
                $(function () {
                    $('#date').datepicker({format: 'HH:mm:ss'});
                })
            });
        </script>
    </div>


    <div class="form-group">
        <label class="col-md-2 control-label"> Image: </label>
        <div class="col-md-10">
            <img src="{{asset($post->image)}}" height="200" width="579">
            <input type="hidden" name="imageold" value="{{$post->image}}">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Change Image: </label>
        <div class="col-md-10">
            <input type="file" name="imagemain" id="file">
        </div>
    </div>


    <div class="form-group">
        <label class="col-md-2 control-label">Description:</label>
        <div class="col-md-10">
            {{ Form::textarea('description', null, ['class' => 'form-control','id'=>'long_description']) }}
            <script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
            <script>
                tinymce.init({
                    selector: '#long_description',
                    convert_urls: false,
                    statusbar: false,
                    height: '300',
                    plugins: 'image code print preview fullpage  searchreplace autolink directionality  visualblocks visualchars fullscreen image link    table charmap hr pagebreak nonbreaking  toc insertdatetime advlist lists textcolor wordcount   imagetools    contextmenu colorpicker textpattern media ',
                    toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat |undo redo | image code| link fontsizeselect  | ',

                    image_title: true,
                    automatic_uploads: true,
                    images_upload_url: '{{url("/admin/upload")}}',
                    file_picker_types: 'image',
                    file_picker_callback: function (cb, value, meta) {

                        var input = document.createElement('input');
                        input.setAttribute('type', 'file');
                        input.setAttribute('accept', 'image/*');

                        input.onchange = function () {
                            var file = this.files[0];

                            var reader = new FileReader();
                            reader.readAsDataURL(file);
                            reader.onload = function () {
                                var id = 'blobid' + (new Date()).getTime();
                                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                                var base64 = reader.result.split(',')[1];
                                var blobInfo = blobCache.create(id, file, base64);
                                blobCache.add(blobInfo);
                                cb(blobInfo.blobUri(), {title: file.name});
                            };
                        };
                        input.click();
                    }
                });
            </script>
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">Meta-title:</label>
        <div class="col-md-10">
            {{ Form::textarea('meta_title', null, ['class' => 'form-control','id'=>'meta-title']) }}
            <script>
                CKEDITOR.replace('meta-title', {
                    height: 100,
                    toolbar: 'Custom', //makes all editors use this toolbar
                    toolbarStartupExpanded: false,
                    toolbarCanCollapse: false,
                    toolbar_Custom: [] //define an empty array or whatever buttons you want.
                });
            </script>
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">Meta-Keywords:</label>
        <div class="col-md-10">
            {{ Form::textarea('meta_keywords', null, ['class' => 'form-control','id'=>'meta-keywords']) }}
            <script src="{{ asset("/public/admin/ckeditor/ckeditor.js") }}"></script>
            <script>
                CKEDITOR.replace('meta-keywords', {
                    height: 100,
                    toolbar: 'Custom', //makes all editors use this toolbar
                    toolbarStartupExpanded: false,
                    toolbarCanCollapse: false,
                    toolbar_Custom: [] //define an empty array or whatever buttons you want.
                });
            </script>

        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">Posted By:</label>
        <div class="col-md-10">
            {{ Form::text('authorname', null, ['class' => 'form-control']) }}
        </div>
    </div>

    <hr>

    <br>

    <div class="form-group row">
        <div class="col-sm-offset-3 col-sm-6">
            {{ Form::submit('Update Post', array('class' => 'btn btn-success')) }}
            <a type="button" id="addslide" class="btn btn-danger">Cancel</a>
        </div>
    </div>
</div>


{!! Form::close() !!} 

и мой контроллер:

public function update(Request $request, $id)
{
    // Validate the data
    $postdata = Post::find($id);

    //print_r($post);

    if ($request->input('slug') == $postdata->slug) {
        //echo 'slug match';
        //exit();
        $this->validate($request, [
            'title'            => 'required|max:255',
            'category_id'      => 'required|integer',
            'long_description' => 'required',
        ]);
    } else {
        //echo 'new slug matching';
        //exit();
        $this->validate($request, [
            'title'            => 'required|max:255',
            'slug'             => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
            'category_id'      => 'required|integer',
            'long_description' => 'required',
        ]);
    }

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

        //echo 'request has old file to unlink ';
        // exit();
        //unlink($request->get('image'));
        // Get filename with the extension
        $filenameWithExt = $request->file('imagemain')->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        // Get just ext
        $extension = $request->file('imagemain')->getClientOriginalExtension();
        $fileNameToStore = $filename . '_' . time() . '.' . $extension;
        // Upload Image
        $path = $request->file('imagemain')->move('public/blogsimages', $fileNameToStore);
        // Filename to store
        echo $fileNameToStore = $path;
    } else {
        $fileNameToStore = $request->input('imageold');
        // exit();
    }

    // Save the data to the database
    $post = Post::find($id);

    $post->title = $request->input('title');
    $post->slug = $request->input('slug');
    $post->category_id = $request->input('category_id');
    $post->description = $request->input('description');
    $post->short_description = $request->input('short_description');
    $post->date = $request->input('date');
    $post->image = $fileNameToStore;
    $post->meta_title = $request->input('meta_title');
    $post->meta_keywords = $request->input('meta_keywords');
    $post->authorname = $request->input('authorname');

    $post->save();

    if (isset($request->tags)) {
        $post->tags()->sync($request->tags);
    } else {
        $post->tags()->sync([]);
    }

    // set flash data with success message
    Session::flash('success', 'This post was successfully saved.');

    // redirect with flash data to posts.show
    return redirect()->route('posts.show', $post->id);
}

когда я отправляю данные, все обновляется в соответствии с требованиями, кроме изображения и формы, показывающей 302, вот скриншоты: ОТВЕТ ОТ СЕРВЕРА мои маршруты: Route::resource('posts', 'PostController');


person Jagdish Sharma    schedule 26.05.2018    source источник
comment
Код состояния 302 означает, что произошла переадресация. Вы выполняете переадресацию с помощью return redirect()->route('posts.show', $post->id);   -  person AliN11    schedule 26.05.2018


Ответы (2)


Я думаю, что в сценарии проверки есть ошибка, попробуйте код

public function update(Request $request, $id)
{
    // Validate the data
    $postdata = Post::find($id);

    //WITHOUT VALIDATION



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

        //echo 'request has old file to unlink ';
        // exit();
        //unlink($request->get('image'));
        // Get filename with the extension
        $filenameWithExt = $request->file('imagemain')->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        // Get just ext
        $extension = $request->file('imagemain')->getClientOriginalExtension();
        $fileNameToStore = $filename . '_' . time() . '.' . $extension;
        // Upload Image
        $path = $request->file('imagemain')->move('public/blogsimages', $fileNameToStore);
        // Filename to store
        echo $fileNameToStore = $path;
    } else {
        $fileNameToStore = $request->input('imageold');
        // exit();
    }

    // Save the data to the database
    $post = Post::find($id);

    $post->title = $request->input('title');
    $post->slug = $request->input('slug');
    $post->category_id = $request->input('category_id');
    $post->description = $request->input('description');
    $post->short_description = $request->input('short_description');
    $post->date = $request->input('date');
    $post->image = $fileNameToStore;
    $post->meta_title = $request->input('meta_title');
    $post->meta_keywords = $request->input('meta_keywords');
    $post->authorname = $request->input('authorname');

    $post->save();

    if (isset($request->tags)) {
        $post->tags()->sync($request->tags);
    } else {
        $post->tags()->sync([]);
    }

    // set flash data with success message
    Session::flash('success', 'This post was successfully saved.');

    // redirect with flash data to posts.show
    return redirect()->route('posts.show', $post->id);
}

ЭТО решит вашу проблему.

person Jagdish Sharma    schedule 11.06.2018

Код состояния 302 означает:

Из здесь:

Протокол передачи гипертекста (HTTP) 302 Код ответа состояния перенаправления Found указывает, что запрошенный ресурс был временно перемещен на URL-адрес, указанный в заголовке Location.

Итак, в последней строке вашего контроллера вы выполняете перенаправление:

return redirect()->route('posts.show', $post->id);

Также, когда проверка Laravel не проходит, он автоматически перенаправляет вас.

person AliN11    schedule 26.05.2018
comment
спасибо за ваш ответ @ AliN11, даже если я удалю эту строку, я все равно перейду на ту же страницу без загрузки файла, основная проблема в том, что ... файл должен обновляться при изменении - person Jagdish Sharma; 26.05.2018
comment
ОК, проверил на валидацию - person Jagdish Sharma; 26.05.2018
comment
нет ошибки проверки в скрипте все в порядке, даже изображение сохраняется в папку, но не обновляется в БД - person Jagdish Sharma; 26.05.2018
comment
@JagdishSharma Я не обнаружил проблем с указанными вами кодами. Можно ли узнать, откуда возникла проблема? - person AliN11; 26.05.2018
comment
Если вы перенаправляете обратно, это означает, что проверка не удалась - person AliN11; 26.05.2018