somenet77

somenet77

Member Since 5 Years Ago

Experience Points
3,620
Total
Experience

1,380 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
22
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
3,620 XP
May
22
1 week ago
Activity icon

Started a new Conversation Parent Child Order Is Mismatch After Array Convert To Json?

I have a categories table with parent id and I have generated the parent-child select dropdown. But array return after database query is not ordered as array after convert to JSON.

array:5 [▼
  1 => "Deondre Little"
  2 => "-Prof. Hope Hettinger"
  4 => "-Axel Kirlin II"
  5 => "-Dr. Otha Schumm Sr."
  3 => "Roberto Kilback"
]

When a response to JSON is an output like below

{
    "1": "Deondre Little",
    "2": "-Prof. Hope Hettinger",
    "3": "Roberto Kilback",
    "4": "-Axel Kirlin II",
    "5": "-Dr. Otha Schumm Sr."
  }

I need JSON key-value pair like an array key value.

However, I fix this issue on my way like this

public function listCategories()
    {
        $newCategoriesList = [];

        $categories = $this->categoryContract->listCategories();

        foreach($categories as $key => $value) {
            $newCategoriesList[] = [
                'id' => $key,
                'name' => $value
            ]; 
        }

        return $newCategoriesList;
    }

Is a better way than i used ?

May
20
1 week ago
Activity icon

Started a new Conversation How To Generate Nestable Menu ?

I have a category table like this.

id      name      parent_id   
1       Test         0
2       Test1       1
3       Test2       2
4       Test3       2
5       Test4       0

Now i want to generate dropdown select box like this using vuejs

<select v-model="selected">
<option value="1">Test</option>
<option value="2">-Test1</option>
<option value="3">--Test2</option>
<option value="4">--Test3</option>
<option value="5>Test5</option>

i have already made the API for the category which return data like this

[
    {
      "id": 1,
      "name": "Benny Turner",
      "parent_id": 0,
    },
    {
      "id": 2,
      "name": "Carol Bergstrom",
      "parent_id": 1
    },
    {
      "id": 3,
      "name": "Hassie Rice",
      "parent_id": 1
    },
    {
      "id": 4,
      "name": "Skye Quitzon",
      "parent_id": 3
    },
    {
      "id": 5,
      "name": "Stephan Beier",
      "parent_id": 4
    },
   {
      "id": 6,
      "name": "Stephan Joe",
      "parent_id": 6
    }
]
Apr
14
1 month ago
Activity icon

Replied to Api Route Not Working With Multiple Guard Session Login.

So what is the solution if I login through admin guard.

Apr
13
1 month ago
Activity icon

Started a new Conversation Api Route Not Working With Multiple Guard Session Login.

I am developing an eCommerce system with multiple authentication frontend and admin, for frontend I used the default web guard and for admin I used the admin guard. And also developing an API for the frontend. My problem is for frontend the default API routes are worked but for admin guard, its doesn't work I used different table for each guard users(web) and admin(admins). When I try any below routes through admin guard with Axios it occur "unauthenticated"

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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::post('v1/register', 'Auth\[email protected]');
Route::post('/login', 'Auth\[email protected]');

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

Route::middleware('json', 'auth:api')
    ->namespace('Api\V1')
    ->prefix('v1')
    ->name('api.')
    ->group(function () {
    		Route::get('brands/datatable', 'Brand\[email protected]')->name('brands.datatable');
            Route::apiResource('brands', 'Brand\BrandController');
            Route::apiResource('categories', 'Category\CategoryController');
            Route::apiResource('products', 'Product\ProductController');
            Route::apiResource('attributes', 'Attribute\AttributeController');
});

Mar
11
2 months ago
Activity icon

Started a new Conversation What Is The Best Solution For Multiple Authentication In Laravel ?

  1. Using multiple table with guard eg default users table for frontend users and admins table for backend users (Note: in backend there is users with role.)

  2. Adding is_admin field in default users table. And add the middleware for admin or user.

Mar
10
2 months ago
Activity icon

Replied to What Is The Best Solution For Multiple Authentication ?

I want best solution to manage multiple user type.

Activity icon

Replied to What Is The Best Solution For Multiple Authentication ?

My question is i want to implement the multiple authentication using spatie role and permissions whether I used default user table for both frontend and backend or used multiple table user for frontnd and admin for backend.

Activity icon

Started a new Conversation What Is The Best Solution For Multiple Authentication ?

I am building an eCommerce system with API for my business but I have a little bit confused for multiple authentication whether I use the same users model for both admin and front login or make admins table with the new authentication system. I have a role-based user system for admin panel and simple user for the frontend (without role). Which is the best solution for this system?

Mar
05
2 months ago
Activity icon

Started a new Conversation Which Is Better Airlock Or Passport ?

In laravel 7 new package AirLock is introduced but I am a little bit confused about which package should use while API authentication Airlock or passport. I have also read Mohamed Said article https://divinglaravel.com/authentication-and-laravel-airlock at the end of the article

Passport
You can use Airlock instead of passport if your application doesn't need the Client Credential grant to allow machine-to-machine communication or the Authorization Code grant. These types of communication require more advanced authentication techniques that Airlock is not built to handle.

In all other scenarios, Airlock is a really good option for authenticating your users without having to setup an entire OAuth2 server implementation.

I am confused in this paragraph

Client Credential grant to allow machine-to-machine communication or the Authorization Code grant
Mar
04
2 months ago
Activity icon

Started a new Conversation Please Well Documented The Config Files Changes

I have a question about how we can update the new configuration setting insides the config directory files. Recently I have updated laravel 6 to 7 following the steps documented in the upgrade guide in laravel docs https://laravel.com/docs/7.x/upgrade but when I compared the file inside https://github.com/laravel/laravel/tree/master/config and my config files there are changes in the new version file. My question is if a new configuration is added or changed in the configuration, please mention in the upgrade guide so that the upgraded version is an exact match with the latest version.

Feb
26
3 months ago
Activity icon

Awarded Best Reply on How To Display Exception Error Msg ?

I have fix my error in this way a new exception will thrown in the repository.

In Repository

public function find($id)
    {
        try {
            return $this->category->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);
            
            throw new ModelNotFoundException($e);
        }
    }

in Exception/Handler.php

if ($exception instanceof Exception) {
            return response()->json([
                'message' => $exception->getMessage(),
                'code'=> $exception->getCode()
            ]);
        }

        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'message' => 'No query result is found with given id',
                'code' => $exception->getCode()
            ]);
        }

So my controller is as it is

public function show($id)
    {
        $category = $this->category->show($id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }
Activity icon

Replied to How To Display Exception Error Msg ?

I have fix my error in this way a new exception will thrown in the repository.

In Repository

public function find($id)
    {
        try {
            return $this->category->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);
            
            throw new ModelNotFoundException($e);
        }
    }

in Exception/Handler.php

if ($exception instanceof Exception) {
            return response()->json([
                'message' => $exception->getMessage(),
                'code'=> $exception->getCode()
            ]);
        }

        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'message' => 'No query result is found with given id',
                'code' => $exception->getCode()
            ]);
        }

So my controller is as it is

public function show($id)
    {
        $category = $this->category->show($id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }
Feb
25
3 months ago
Activity icon

Replied to How To Display Exception Error Msg ?

I have already catch exception in categoryrepository file please check the file. Which I bind with categorycontract file.My question is how to solve this issue give me some idea.

Activity icon

Started a new Conversation How To Display Exception Error Msg ?

I have issue while displaying the exception in json format.

My problem is if i hit url with record exist (http://127.0.0.1:8000/api/v1/categories/1) it response perfect json

{
    "data": {
        "name": "Linda Bechtelar",
        "slug": "linda-bechtelar",
        "description": "Placeat totam et vero officiis itaque laborum. Aperiam voluptate placeat molestiae doloremque suscipit sapiente excepturi. Ex consequatur a quia.",
        "parent_id": 1,
        "featured": false,
        "media": {
            "name": "kitten",
            "url": "http://localhost/storage/1/kitten.jpeg"
        }
    }
}

But if i hit url record with not exist like eg (http://127.0.0.1:8000/api/v1/categories/1000)

{
    "message": "Method Illuminate\Http\JsonResponse::getMedia does not exist.",
    "exception": "BadMethodCallException",

I want to exception response like this

{
    "message": "No query result is found with id 10",
    "code": 0
}

i have a controller with show method like this

<?php

namespace App\Http\Controllers\Api\V1\Product;

use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use App\Lakhure\Admin\Traits\Authorizable;
use App\Http\Requests\Product\CategoryRequest;
use App\Http\Resources\Product\CategoryCollection;
use App\Lakhure\Admin\Services\Product\CategoryService;
use App\Http\Resources\Product\Category as CategoryResource;

class CategoryController extends Controller
{
    use Authorizable;

    private $abilities = [
        //'index' => 'list',
        'add' => 'create',
        'show' => 'view',
        'edit' => 'update',
        'destroy' => 'delete',
    ];

    /**
     * @var $category
     */
    protected $category;

    /**
     * CategoryController constructer
     *
     * @param CategoryService $category
     */
    public function __construct(CategoryService $category)
    {
        $this->category = $category;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = $this->category->all();

        return (new CategoryCollection($categories))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  App\Http\Requests\Product\CategoryRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CategoryRequest $request)
    {
        $category = $this->category->create($request);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $category = $this->category->show($id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  App\Http\Requests\Product\CategoryRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(CategoryRequest $request, $id)
    {
        $category = $this->category->update($request, $id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_ACCEPTED);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $category = $this->category->delete($id);

        return response($category)
            ->setStatusCode(Response::HTTP_NO_CONTENT);
    }
}

And my CategoryRepository is like this.

<?php

namespace App\Lakhure\Admin\Repositories\Product;

use Exception;
use App\Models\Category;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Lakhure\Admin\Contracts\Product\CategoryContract;

class CategoryRepository implements CategoryContract
{
    /**
     * @var $category
     */
    protected $category;

    /**
     * @var $db
     */
    protected $db;

    /**
     * CategoryRepository constructor.
     * @param Category $model
     * @param DatabaseManager $db
     */
    public function __construct(Category $category, DatabaseManager $db)
    {
        $this->category = $category;

        $this->db = $db;
    }

    /**
     * @param array $columns
     * @param string $orderBy
     * @param string $sortBy
     * @param int $limit
     */
    public function all($columns = ['*'], $orderBy = 'id', $sortBy = 'desc', $limit = 10)
    {
        try {
            return $this->category->select($columns)->orderBy($orderBy, $sortBy)->paginate($limit);
        } catch (Exception $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);
        }
    }

    /**
     * @param array $request
     * @return Category|mixed
     */
    public function create($request)
    {
        $this->db->beginTransaction();

        try {
            $category = $this->category->create($request);
            $this->db->commit();

            Log::info('Category created', ['_trace' => $category]);
            return $category;
        } catch (Exception $e) {
            $this->db->rollback();
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode()
            ]);
        }
    }

    /**
     * @param int $id
     * @return mixed
     * @throws ModelNotFoundException
     */
    public function find($id)
    {
        try {
            return $this->category->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => sprintf('No query result is found with id %d', $id),
                'code' => $e->getCode()
            ]);
        }
    }

    /**
     * @param array $request
     * @param int $id
     * @return Category
     */
    public function update($request, $id)
    {
        $this->db->beginTransaction();

        try {
            $category = $this->category->findOrFail($id);
            //$category->fill($request);
            $category = tap($category)->update($request);
            $this->db->commit();
            Log::info('Category Updated', ['_trace' => $category]);

            return $category;
        } catch (Exception $e) {
            $this->db->rollback();

            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => sprintf('No query result is found with id %d', $id),
                'code' => $e->getCode()
            ]);
        } 
    }

    /**
     * @param int $id
     * @return void
     */
    public function delete($id)
    {
        $this->db->beginTransaction();

        try {
            $this->category->destroy($id);
            $this->db->commit();
            Log::info('Category deleted', ['_trace' => 'id: ' . $id]);

            return $this->category;
        } catch (Exception $e) {
            $this->db->rollback();
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode()
            ]);
        }
    }
}

And finally my service file is like this.

<?php

namespace App\Lakhure\Admin\Services\Product;

use App\Lakhure\Admin\Contracts\Product\CategoryContract;

class CategoryService
{
    /**
     * @var $categoryContract
     */
    public $categoryContract;

    /**
     * Cateogry Service Constructor
     * @param CategoryContract $categoryContract
     */
    public function __construct(CategoryContract $categoryContract)
    {
        $this->categoryContract = $categoryContract;
    }

    /**
     * Get all categories
     * @return mixed
     */
    public function all(array $columns = ['*'], string $orderBy = 'id', string $sortBy = 'desc', int $limit = 10)
    {
        return $this->categoryContract->all($columns, $orderBy, $sortBy, $limit);
    }

    /**
     * Create the category
     * @param  CategoryRequest
     * @return Category
     */
    public function create($request)
    {
        $params = $request->except('file');

        $category = $this->categoryContract->create($params);

        if ($request->hasFile('file')) {
            $category->addMedia($request->file)->sanitizingFileName(function ($fileName) {
                return strtolower(str_replace(['#', '/', '\', ' '], '-', $fileName));
            })->toMediaCollection('categories');
        }

        return $category;
    }

    /**
     * Show category by id
     * @param Category ID
     * @return Category
     */
    public function show($id)
    {
        return $this->categoryContract->find($id);
    }

    /**
     * Update the category
     * @param  CategoryRequest
     * @param  Category ID
     * @return Category
     */
    public function update($request, $id)
    {
        $params = $request->except('file');

        $category = $this->categoryContract->update($params, $id);

        if ($request->hasFile('file')) {
            $category->clearMediaCollection('categories');
            $category->addMedia($request->file)->sanitizingFileName(function ($fileName) {
                return strtolower(str_replace(['#', '/', '\', ' '], '-', $fileName));
            })->toMediaCollection('categories');
        }

        return $category;
    }

    /**
     * Delete the category
     * @param  Category ID
     * @return Category
     */
    public function delete($id)
    {
        $category = $this->categoryContract->find($id);

        $this->categoryContract->delete($id);

        return $category;
    }
}

and my resource file i like this

<?php

namespace App\Http\Resources\Product;

use Illuminate\Http\Resources\Json\JsonResource;

class Category extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $media = $this->getMedia('categories');

        return [
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
            'parent_id' => $this->parent_id,
            'featured' => $this->featured,
            'media' => [
                'name' => isset($media[0]) ? $media[0]->name : null,
                'url' => isset($media[0]) ? $media[0]->getUrl() : null
            ] 
        ];
    }
}

Activity icon

Started a new Conversation How To Handle Exception In Eloquent Api Resources

I have issue while displaying the exception in json format.

My problem is if i hit url with record exist (http://127.0.0.1:8000/api/v1/categories/1) it response perfect json

{
    "data": {
        "name": "Linda Bechtelar",
        "slug": "linda-bechtelar",
        "description": "Placeat totam et vero officiis itaque laborum. Aperiam voluptate placeat molestiae doloremque suscipit sapiente excepturi. Ex consequatur a quia.",
        "parent_id": 1,
        "featured": false,
        "media": {
            "name": "kitten",
            "url": "http://localhost/storage/1/kitten.jpeg"
        }
    }
}

But if i hit url record with not exist like eg (http://127.0.0.1:8000/api/v1/categories/1000)

{
    "message": "Method Illuminate\Http\JsonResponse::getMedia does not exist.",
    "exception": "BadMethodCallException",

I want to exception response like this

{
    "message": "No query result is found with id 10",
    "code": 0
}

i have a controller with show method like this

<?php

namespace App\Http\Controllers\Api\V1\Product;

use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use App\Lakhure\Admin\Traits\Authorizable;
use App\Http\Requests\Product\CategoryRequest;
use App\Http\Resources\Product\CategoryCollection;
use App\Lakhure\Admin\Services\Product\CategoryService;
use App\Http\Resources\Product\Category as CategoryResource;

class CategoryController extends Controller
{
    use Authorizable;

    private $abilities = [
        //'index' => 'list',
        'add' => 'create',
        'show' => 'view',
        'edit' => 'update',
        'destroy' => 'delete',
    ];

    /**
     * @var $category
     */
    protected $category;

    /**
     * CategoryController constructer
     *
     * @param CategoryService $category
     */
    public function __construct(CategoryService $category)
    {
        $this->category = $category;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = $this->category->all();

        return (new CategoryCollection($categories))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  App\Http\Requests\Product\CategoryRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CategoryRequest $request)
    {
        $category = $this->category->create($request);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $category = $this->category->show($id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  App\Http\Requests\Product\CategoryRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(CategoryRequest $request, $id)
    {
        $category = $this->category->update($request, $id);

        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_ACCEPTED);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $category = $this->category->delete($id);

        return response($category)
            ->setStatusCode(Response::HTTP_NO_CONTENT);
    }
}

And my CategoryRepository is like this.

<?php

namespace App\Lakhure\Admin\Repositories\Product;

use Exception;
use App\Models\Category;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Lakhure\Admin\Contracts\Product\CategoryContract;

class CategoryRepository implements CategoryContract
{
    /**
     * @var $category
     */
    protected $category;

    /**
     * @var $db
     */
    protected $db;

    /**
     * CategoryRepository constructor.
     * @param Category $model
     * @param DatabaseManager $db
     */
    public function __construct(Category $category, DatabaseManager $db)
    {
        $this->category = $category;

        $this->db = $db;
    }

    /**
     * @param array $columns
     * @param string $orderBy
     * @param string $sortBy
     * @param int $limit
     */
    public function all($columns = ['*'], $orderBy = 'id', $sortBy = 'desc', $limit = 10)
    {
        try {
            return $this->category->select($columns)->orderBy($orderBy, $sortBy)->paginate($limit);
        } catch (Exception $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);
        }
    }

    /**
     * @param array $request
     * @return Category|mixed
     */
    public function create($request)
    {
        $this->db->beginTransaction();

        try {
            $category = $this->category->create($request);
            $this->db->commit();

            Log::info('Category created', ['_trace' => $category]);
            return $category;
        } catch (Exception $e) {
            $this->db->rollback();
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode()
            ]);
        }
    }

    /**
     * @param int $id
     * @return mixed
     * @throws ModelNotFoundException
     */
    public function find($id)
    {
        try {
            return $this->category->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => sprintf('No query result is found with id %d', $id),
                'code' => $e->getCode()
            ]);
        }
    }

    /**
     * @param array $request
     * @param int $id
     * @return Category
     */
    public function update($request, $id)
    {
        $this->db->beginTransaction();

        try {
            $category = $this->category->findOrFail($id);
            //$category->fill($request);
            $category = tap($category)->update($request);
            $this->db->commit();
            Log::info('Category Updated', ['_trace' => $category]);

            return $category;
        } catch (Exception $e) {
            $this->db->rollback();

            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => sprintf('No query result is found with id %d', $id),
                'code' => $e->getCode()
            ]);
        } 
    }

    /**
     * @param int $id
     * @return void
     */
    public function delete($id)
    {
        $this->db->beginTransaction();

        try {
            $this->category->destroy($id);
            $this->db->commit();
            Log::info('Category deleted', ['_trace' => 'id: ' . $id]);

            return $this->category;
        } catch (Exception $e) {
            $this->db->rollback();
            Log::error($e->getMessage(), ['_trace' => $e->getTraceAsString()]);

            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode()
            ]);
        }
    }
}

And finally my service file is like this.

<?php

namespace App\Lakhure\Admin\Services\Product;

use App\Lakhure\Admin\Contracts\Product\CategoryContract;

class CategoryService
{
    /**
     * @var $categoryContract
     */
    public $categoryContract;

    /**
     * Cateogry Service Constructor
     * @param CategoryContract $categoryContract
     */
    public function __construct(CategoryContract $categoryContract)
    {
        $this->categoryContract = $categoryContract;
    }

    /**
     * Get all categories
     * @return mixed
     */
    public function all(array $columns = ['*'], string $orderBy = 'id', string $sortBy = 'desc', int $limit = 10)
    {
        return $this->categoryContract->all($columns, $orderBy, $sortBy, $limit);
    }

    /**
     * Create the category
     * @param  CategoryRequest
     * @return Category
     */
    public function create($request)
    {
        $params = $request->except('file');

        $category = $this->categoryContract->create($params);

        if ($request->hasFile('file')) {
            $category->addMedia($request->file)->sanitizingFileName(function ($fileName) {
                return strtolower(str_replace(['#', '/', '\', ' '], '-', $fileName));
            })->toMediaCollection('categories');
        }

        return $category;
    }

    /**
     * Show category by id
     * @param Category ID
     * @return Category
     */
    public function show($id)
    {
        return $this->categoryContract->find($id);
    }

    /**
     * Update the category
     * @param  CategoryRequest
     * @param  Category ID
     * @return Category
     */
    public function update($request, $id)
    {
        $params = $request->except('file');

        $category = $this->categoryContract->update($params, $id);

        if ($request->hasFile('file')) {
            $category->clearMediaCollection('categories');
            $category->addMedia($request->file)->sanitizingFileName(function ($fileName) {
                return strtolower(str_replace(['#', '/', '\', ' '], '-', $fileName));
            })->toMediaCollection('categories');
        }

        return $category;
    }

    /**
     * Delete the category
     * @param  Category ID
     * @return Category
     */
    public function delete($id)
    {
        $category = $this->categoryContract->find($id);

        $this->categoryContract->delete($id);

        return $category;
    }
}

and my resource file i like this

<?php

namespace App\Http\Resources\Product;

use Illuminate\Http\Resources\Json\JsonResource;

class Category extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $media = $this->getMedia('categories');

        return [
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
            'parent_id' => $this->parent_id,
            'featured' => $this->featured,
            'media' => [
                'name' => isset($media[0]) ? $media[0]->name : null,
                'url' => isset($media[0]) ? $media[0]->getUrl() : null
            ] 
        ];
    }
}