Nikki
249
13
Laravel

Redirect not working 100%

Posted 7 months ago by Nikki

I've created a page where once you've uploaded images and click on the upload button it uploads the images and saves it to the database. The problem I'm having is that my redirect isn't working.

If I do

return ['redirect' => route('products.index')];

my page doesn't go to the correct page but in my network tab it gives me the correct url. In my Response tab I have

redirect    http://vue-laravel-image.test/admin/products

If I do

return redirect()->route('products.index')->with('success', 'Product Successfully Added.');

I get a blank Response but then I get another line with the correct html for the product.index page but on my browser it hasn't changed to the correct page.

This is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Product;

class ProductsController extends Controller
{
    public function index()
    {
        $products = Product::all();

        return view('admin.products.products.index', compact('products'));
    }

    public function create()
    {
        $product = new Product();

        return view('admin.products.products.create');
    }

    public function store(Request $request)
    {
        $product = new Product();

        $input = $this->getSafeInput($request);

        $product->fill($input);

        if($request->hasFile('images'))
        {
            $names = [];
            foreach($request->file('images') as $image)
            {
                $destinationPath = 'product_images/full_image/';
                $filename = $image->getClientOriginalName();
                $image->move($destinationPath, $filename);
                array_push($names, $filename);          
            }

            $product->image = json_encode($names);
        }


        $product->save();

        return redirect()->route('products.index')->with('success', 'Product Successfully Added.');
        // return ['redirect' => route('products.index')];
    }

    protected function getSafeInput(Request $request)
    {
        return $request->only([
            'image',
        ]);
    }
}

and here is my Vue component

<template>
    <!-- isDragging = if(isDragging) -->
    <div class="uploader" 
            @dragenter="OnDragEnter" 
            @dragleave="OnDragLeave" 
            @dragover.prevent 
            @drop="onDrop" 
            :class="{ dragging: isDragging }">
        
        <div class="upload-control" v-show="images.length">
            <label for="file">Select a file</label>
            <button @click="upload">Upload</button>
        </div>

        <!-- only shows if there is no images -->
        <div v-show="!images.length">
            <i class="fa fa-cloud-upload"></i>
            <p>Drag your images here</p>
            <div>OR</div>
            <div class="file-input">
                <label for="file">Select a file</label>
                <input type="file" id="file" @change="onInputChange" multiple>
            </div>
        </div>

        <!-- if there is images -->
        <div class="images-preview" v-show="images.length">
            <div class="img-wrapper" v-for="(image, index) in images">
                <img :src="image" :alt="`Image Uplaoder ${index}`">
                <div class="details">
                    <span class="name" v-text="files[index].name"></span>
                    <span class="size" v-text="getFileSize(files[index].size)"></span>
                </div>
                <div class="btn btn-danger" @click="funDeleteFile(index)">
                    Remove
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data: () => ({
        isDragging: false,
        //Sets the dragCount to 0
        dragCount: 0,
        //Makes files an array, so that we can send the files to the server
        files: [],
        //Makes images an array, so that we can let the user see the images
        images: [],
    }),
    methods: {
        OnDragEnter(e) {
            //Prevents the default action of the browser
            e.preventDefault();
            
            // This lets the dragCount become 1, so that the image uploader changes colour
            this.dragCount++;

            // Changes the isDragging variable to true instead of false
            this.isDragging = true;

            return false;
        },
        OnDragLeave(e) {
            //Prevents the default action of the browser
            e.preventDefault();

            // This lets the dragcount become 0, so that the image uploader changes to it's original colour
            this.dragCount--;

            // This is if the dragCount is <= 0 then the isDragging variable is false
            if (this.dragCount <= 0)
                this.isDragging = false;
        },
        onInputChange(e) {
            // Grabs the files from the event
            const files = e.target.files;

            // Creates an array for files, so that we can loop thru it
            // Send the file to the addImage method via "this.addImage(file)"
            Array.from(files).forEach(file => this.addImage(file));
        },
        onDrop(e) {
            //Prevents the default action of the browser
            e.preventDefault();
            //Stops the propagation into the other elements inside the one we drop and file into
            e.stopPropagation();

            // This is to disable the dragging of the images
            this.isDragging = false;

            // Grabs the files from the event
            const files = e.dataTransfer.files;

            // Creates an array for files, so that we can loop thru it
            // Send the file to the addImage method via "this.addImage(file)"
            Array.from(files).forEach(file => this.addImage(file));
        },
        addImage(file) {
            //Checks if the file type is an image
            if (!file.type.match('image.*')) {
                this.$toastr.e(`${file.name} is not an image`);
                return;
            }

            this.files.push(file);

            const img = new Image(),
                reader = new FileReader();

            reader.onload = (e) => this.images.push(e.target.result);

            reader.readAsDataURL(file);
        },

        funDeleteFile(file){
            console.log('delete '+file)
            this.files.splice(file, 1)
            this.images.splice(file, 1)
   
        },

        getFileSize(size) {
            const fSExt = ['Bytes', 'KB', 'MB', 'GB'];
            let i = 0;
            
            while(size > 900) {
                size /= 1024;
                i++;
            }

            return `${(Math.round(size * 100) / 100)} ${fSExt[i]}`;
        },
        upload() {
            const formData = new FormData();
            
            this.files.forEach(file => {
                formData.append('images[]', file, file.name);
            });

            axios.post('/admin/products', formData)
                .then(response => {
                    this.$toastr.s('All images uplaoded successfully');
                    // this.images = [];
                    // this.files = [];
                })
        }
    }
}
</script>

If there is anything else you would like me to post please let me know. Thanks

Please sign in or create an account to participate in this conversation.