laravel-api / app / Http / Controllers / CategoryController.php
CategoryController.php
Raw
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;

use Illuminate\Support\Facades\Validator;


class CategoryController extends Controller
{
    /**
     * Display  All categories.
     *
     * @return \Illuminate\Http\Response
     */
    public function getCategory()
    {
        return category::all();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function addCategory(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'title' => 'required']); 
    
            if ($validator->fails()) {
                return response()->json(['title is required'], 405);
            }
            else {
                return Category::create($request->all());
            } 
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($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)
    {
        //
    }

    /**
     * Display item by category .
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */    
    public function getItemByCategory($id){

        $category = Category::find($id);
        
        if($category == null){
            return response()->json(['category not found'], 404);
        }

        $items = Category::find($id)->items;
        return $items ;
    }


}