Home > Enterprise >  Problem with Route::apiResource() Laravel Framework 8.64.0
Problem with Route::apiResource() Laravel Framework 8.64.0

Time:10-14

I'm using laravel 8 (Laravel Framework 8.64.0) to create an API. But when make a call to an endpoint, which i define with Route::apiResource it doesn't return the result from a query, returns nothing.

routes\api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\TodoController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

//Route::get('/todos', [TodoController::class, 'index']);

Route::apiResources([
    'todos' => TodoController::class,
]);

Models\Todo.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'is_done',
        'due_at',
        'completed_at',
    ];
}

Controllers\TodoController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Todo;

class TodoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Todo::all();
    }

If I add another route:

Route::get('/todos', [TodoController::class, 'index']);

and I call it, it works. What could possible be the problem?

CodePudding user response:

You may want to try create TodoResource class extend JsonResource by running

php artisan make:resource TodoResource

then inside Todo Controller index function, replace return Todo::all(); with

return TodoResource::collection(Todo::all());

CodePudding user response:

Solution why not work, remove line from

routes\api.php:

use App\Http\Controllers\Api\TodoController;
  • Related