Search code examples
laravelvuejs3laravel-8nuxt3.jspinia

How to solve can't getById?


i'm trying to write a test to test that the method that gets categoryById returns the correct data but i'm getting Null. please does anyone have an idea how to fix this issue? thanks

My CategoryController

public function show($id)
    {
        try {
            $category = Category::find($id);
            return response()->json([
                'success' => 'OK',
                "categories" => $category,
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

My vue store

        async getCategoriesById(id) {
            let res = await $axios.get(`/api/categories/${id}`)

            // this.$state.id = res.data[0].id   <-- this is also not working
            
            console.log(res)
        },
    },

My Categories Component

onMounted(async () => {
  getCategoriesById()
})

const getCategoriesById = async () => {
  try {
    await $forumStore.getCategoriesById(route.params.id)
  } catch (error) {
    console.log(error)

  }
}

My route

Route::get('/categories/{id}', [CategoryController::class, 'show']);

My issue

enter image description here


Solution

  • If the id is passed to the controller correctly make sure you actually have a category with the given id sitting in your database. Category::find($id) just returns null if there is no category with the matching id in the database. So, the result is correct as you're returning a successful response without handling a null result. Use Category::findOrFail($id) instead if you want to trigger an error when no category is found.