skip to Main Content

CategoryController

class CategoryController extends Controller
{
    public function index(Request $request){
        // $data['categories'] = $categories;
        $categories = Category::where([
            ['name', '!=', Null],
            [function ($query) use ($request) {
                if (($keyword = $request->keyword)) {
                    $query->orWhere('name', 'LIKE', '%' . $keyword . '%')
                        ->get();
                }
            }]
        ])->paginate(6);
        // $categories = Category::paginate(10);
        return view('admin.category.list',compact('categories'));
    }


    public function create(){
        return view('admin.category.create');
    }

    public function store(Request $request){
        $validator = Validator::make($request->all(),[
            'name' => 'required',
            'slug' => 'required|unique:categories'
        ]);
        if($validator->passes()){
            $category = new Category();
            $category->name = $request->name;
            $category->slug = $request->slug;
            $category->status = $request->status;
            $category->save();

        
            return redirect()->route('categories.index')->with('message','Category added successfully');
            // $request->session()->flash('success', 'Category added successfully');

            // return to_route('categories.index')->with('status', 'Category added successfully');
            return response()->json([
                'status' => true,
                'message' => 'Category added successfully'
            ]);
     

        } else{
            return response()->json([
                'status' => false,
                'errors' => $validator->errors()
            ]);
        }
    }
}

web.php

Route::group(['prefix'=>'admin'], function(){
Route::group(['middleware' => 'admin.guest'], function(){
    Route::get('/login', [AdminLoginController::class,'index'])->name('admin.login');
    Route::post('/authenticate', [AdminLoginController::class,'authenticate'])->name('admin.authenticate');
});
Route::group(['middleware' => 'admin.auth'], function(){
    Route::get('/dashboard', [HomeController::class,'index'])->name('admin.dashboard');
    Route::get('/logout', [HomeController::class,'logout'])->name('admin.logout');

    //Category Routes
    Route::get('/categories', [CategoryController::class,'index'])->name('categories.index');
    // Route::get('/categories', [CategoryController::class,'search'])->name('categories.search');
    Route::get('/categories/create', [CategoryController::class,'create'])->name('categories.create');
    Route::post('/categories', [CategoryController::class,'store'])->name('categories.store');

    //temp-images.create
    Route::post('/upload-temp-image', [TempImagesController::class, 'create'])->name('temp-images.create');

    Route::get('/getSlug', function(Request $request){
        $slug = '';
        if(!empty($request->title)){
            $slug = Str::slug($request->title);
        }
        return response()->json([
            'status'=>true,
            'slug'=>$slug
        ]);
    })->name('getSlug');
});
});

Kernel.php

protected $middlewareAliases = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'admin.auth' => AppHttpMiddlewareAdminAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'admin.guest' => AppHttpMiddlewareAdminRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'precognitive' => IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,
        'signed' => AppHttpMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
    ];

MiddlewareAdminAuthenticate.php

class AdminAuthenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('admin.login');
    }

    protected function authenticate($request, array $guards)
    {
        if($this->auth->guard('admin')->check()){
            return $this->auth->shouldUse('admin');
        }
        
        $this->unauthenticated($request, ['admin']);
    }
}

create.blade.php

 <form action='' method="POST" id="categoryForm" name="categoryForm">
                <div class="card">
                    <div class="card-body">                             
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="name">Name</label>
                                    <input type="text" name="name" id="name" class="form-control" placeholder="Name">   
                                    <p></p>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="slug">Slug</label>
                                    <input type="text" readonly name="slug" id="slug" class="form-control" placeholder="Slug">  
                                    <p></p>
                                </div>
                            </div>  
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <input type="hidden" id="image_id" name="image_id" 
value="">
                                    <label for="image">Image</label>
                                    <div id="image" class="dropzone dz-clickable">
                                        <div class="dz-message needsclick">
                                            <br>Drop files here or click to upload.<br> 
<br>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="status">Status</label>
                                    <select name="status" id="status" class="form-control">
                                        <option value="1">Active</option>
                                        <option value="0">Block</option>
                                    </select>
                                </div>
                            </div>  


                        </div>
                    </div>                          
                </div>
                <div class="pb-5 pt-3">
                    <input type="submit" value="Create" class="btn btn-primary">
                    <a href="" class="btn btn-outline-dark ml-3">Cancel</a>
                </div>
            </form>
<script>
    $('#categoryForm').submit(function(event){
        event.preventDefault();
        var element = $(this)
        $("button[type=submit]").prop('disabled',true)
        $.ajax({
            url:'{{ route("categories.store") }}',
            type: 'post',
            data: element.serializeArray(),
            dataType: 'json',
            success: function(response){
                $("button[type=submit]").prop('disabled',false)
                if(response['status'] == true){
                    $("#name").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("")
                    $("#slug").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("")
                } else{
                    var errors = response['errors']

                    if(errors['name']){
                        $("#name").addClass('is-invalid').siblings('p').addClass('invalid-feedback').html(errors['name'])
                    } else{
                        $("#name").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("")
                    }

                    if(errors['slug']){
                        $("#slug").addClass('is-invalid').siblings('p').addClass('invalid-feedback').html(errors['slug'])
                    } else{
                        $("#slug").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("")
                    }
                }
            },
            error: function(jqXHR, exception){
                console.log("Something went wrong")
            }
        })
    })

For the create.blade.php, when I try to submit the new form data using POST action and in the CategoryController, I would like to redirect back to the route categories.index and I tried return redirect()->route('categories.index')->with('message','Category added successfully'); but the page still not redirect after I submitted even I checked clearly the route path exists. When I check the network the route path exists but the page still remains stuck. Can any people help figure out what’s the problem?

2

Answers


  1. Instead of redirecting in the controller, you should handle the redirect or page update on the client side after the successful AJAX request.

    return response()->json([
        'status' => true,
        'message' => 'Category added successfully'
    ]);
    

    Modify your JavaScript code to handle the redirection or page update:

    $('#categoryForm').submit(function(event){
        event.preventDefault();
        var element = $(this);
        $("button[type=submit]").prop('disabled', true);
        $.ajax({
            url: '{{ route("categories.store") }}',
            type: 'post',
            data: element.serializeArray(),
            dataType: 'json',
            success: function(response){
                $("button[type=submit]").prop('disabled', false);
                if (response['status'] == true){
                    // Clear any error messages if present
                    $("#name").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("");
                    $("#slug").removeClass('is-invalid').siblings('p').removeClass('invalid-feedback').html("");
                    
                    // Perform your desired action here
                    // For example, you can show a success message and then redirect or update the page
                    alert(response['message']); // Display success message
                    window.location.href = '{{ route("categories.index") }}'; // Redirect to index page
                } else {
                    // Handle errors
                }
            },
            error: function(jqXHR, exception){
                console.log("Something went wrong");
            }
        });
    });
    
    Login or Signup to reply.
  2. If you’re using AJAX to submit the form, the traditional redirect will not work.

    Changes

    1. Remove multiple return statements from your code. Note that the code below return will not execute
    2. If you need to pass a redirect URL, then pass that alongside the response.

    Controller, in success if condition add this

    return response()->json([
        'status' => true,
        'message' => 'Category added successfully',
        'redirect' => route('categories.index')
    ]);
    

    In your AJAX

    success: function(response){
        if(response['status'] == true){
            if (response.redirect) {
                window.location.href = response.redirect;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search