0

I installed Laravel UI using this tutorial https://www.itsolutionstuff.com/post/laravel-9-authentication-using-breeze-tutorialexample.html

The login and register forms are there http://localhost:8000/login but after login if I go to my route (http://localhost:8000/api/categories) inside the middleware I am redirected to the home page. If I have the route outside the middleware it works but without requiring a login.

** Works ** (at least the 'Category' view shows)

    Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
        Route::get('categories', 'index')->name('categories.index')
    });

** Does Not work ** (redirects to home view)

Route::group(['middleware' => 'auth:api'], function(){
    Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
        Route::get('categories', 'index')->name('categories.index')
    });
});

** CategoryController**

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cat = $this->getCategories();
        return response()->json($cat);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cat = $this->getCategories();
        return view('create-category',compact('cat'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return Auth::user();
        $category = Category::firstOrCreate(
            ['name' => $role_name],
            ['guard_name' => 'api']
        );
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $cat = $this->getCategories($id);
//        $cat = Category::where('id', $id)->get()->keyBy('id');
        return response()->json($cat);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function getParentCategory($id) {
        $cat = Category::where('id', $id)->get()->keyBy('id');
        return $cat;
    }

    public function getChildCategory($id, $keyBy = null) {
//        return $keyBy;
        $cat = Category::where('parent_id', $id)->get()->keyBy('id');
        return $cat;
    }

    private function setKeyBy($collection, $name) {
        $collection = $collection->keyBy($name);
        return $collection;
    }

    public function getCategories($category_id = null) {
        $cat = Category::where('id', '>', 0);
        if(!is_null($category_id)) {
            $cat = $cat->where('id', $category_id)->get()->keyBy('id');
        } else {
            $cat = $cat->whereNull('parent_id')->get()->keyBy('id');

            foreach($cat as $catID=>$catArray) {
                $subCat = $this->getChildCategory($catID, 'id');
//                $subCat = $subCat->keyBy('id');
                if ($subCat->first()) {
                    $cat[$catID]['subcat'] = $subCat;
                }
            }
        }
        return $cat;
    }

    public function createCategoryForm() {
        $cat = $this->getCategories();
        return view('create-category',compact('cat'));
    }

    public function categoryDropown($child_id = null) {
        $cat = $this->getCategories();
    }

    public function categoryChildDropown($child_id) {
        $cat = Category::where('parent_id', $child_id)->get();
        return $cat;
    }
}

I have used Laravel for a while now but this is the first time creating an app from scratch with Auth. I do not know what I am missing. TIA

mathius1
  • 1,381
  • 11
  • 17
  • I do not want it to go to the dashboard. I want it to go to /api/categories where it will display a list of categories. Sorry if the question is confusing. – mathius1 Nov 16 '22 at 22:20
  • the `api` guard for auth is expecting you to pass a token with the request as it is "stateless" authentication (no sessions which is what the `web` guard would use) ... also you didn't install Laravel UI, you installed Laravel Breeze which is a different package – lagbox Nov 16 '22 at 22:21
  • I used composer require laravel/ui – mathius1 Nov 17 '22 at 19:26

2 Answers2

0

You can try this:

$router->group(['middleware' => 'auth'], function() use ($router) {
    Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
        Route::get('categories', 'index')->name('categories.index')
    });
});
DreamBold
  • 2,727
  • 1
  • 9
  • 24
  • I am getting a $router undefined in PHPStorm. – mathius1 Nov 17 '22 at 01:30
  • `php artisan route:clear` `php artisan view:clear` `php artisan cache:clear` Can you run these? – DreamBold Nov 17 '22 at 05:55
  • I ran those and after login it redirects me to http://localhost:8000/home – mathius1 Nov 17 '22 at 19:34
  • Do you mean it's the same as before? – DreamBold Nov 17 '22 at 19:36
  • Redirecting to `home` you can see in the ` app/Http/Middleware/RedirectIfAuthenticated.php` file. Redirecting to `home` after login/register you can set in `app/Http/Controllers/Auth/LoginController.php` and `app/Http/Controllers/Auth/RegisterController.php`. It looks like `protected $redirectTo = '/home';` – DreamBold Nov 17 '22 at 19:42
  • I appreciate your help. After login it still redirects to /home I have even commented out $redirectTo but still goes to home after login. – mathius1 Nov 17 '22 at 23:45
  • Can you add me to your repo? dreambold – DreamBold Nov 18 '22 at 00:10
0

Thanks to Dream Bold for pointing me in the right direction. I should have posted the web.php and api.php files. I found the answer here https://stackoverflow.com/a/35162656/1198563
I had the route in the api.php Once I moved it into web.php, into the web middleware group and in the api middleware group it works.

Route::group(['middleware' => 'web'], function () {
Route::auth();
// Moving here will ensure that sessions, csrf, etc. is included in all these routes
Route::group(['prefix' => 'api', 'middleware' => 'auth'], function () {
    Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function () {
            Route::get('categories', 'index')->name('categories.index');//->middleware('auth');
        });
    });
});
mathius1
  • 1,381
  • 11
  • 17