zakhttp

zakhttp

Member Since 3 Years Ago

Dubai

Experience Points 3,260
Experience Level 1

1,740 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 28
Lessons
Completed
Best Reply Awards 1
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

16 Nov
2 years ago
28 Jun
3 years ago
02 Apr
3 years ago

zakhttp left a reply on Installing MongoDb On Laravel Homestead And Php7

Hello @computecoholic, already merged, thanks for your contribution!

17 Mar
3 years ago

zakhttp started a new conversation Installing MongoDb On Laravel Homestead And Php7

Hello Guys, i created a script to help install mongoDB on homestead with php7, Since it was a 3days hassle for me to figure out the problem, so decided to automate the process, Here is the repo: https://github.com/zakhttp/Mongostead7.git Please make sure to change permission of the file to be able to execute it using the command: sudo chmod +x mongoHomestead7.sh

zakhttp left a reply on Installing The PHP 7 MongoDB Client/Driver

Hello @logikinc, i faced the same issue but i managed to install it, i created a git repo containing a bash script to automate the process, https://github.com/zakhttp/Mongostead7.git Please make sure to change permission of the file to be able to execute it using the command: sudo chmod +x mongoHomestead7.sh Cheers!

16 Mar
3 years ago

zakhttp started a new conversation Laravel Api JWT Implementation Using Fractal And Mongodb

Hello LaraFolks (BTW it's a nice name for a Laravel community project lol) I would like to share with you my experience after just a couple of months of Laravel apprenticeship. Iam working on a project That matches Clients with Service providers where i am having a lot of inconsistent Schema data. I started by using Mysql with Laravel Eloquent then i got stuck at the middle for the following reasons:

  1. I had 2 types of users Clients and Providers and each has got different fields to be filled for registration (I know you will tell me use Polymorphic relationships ... consider it done for the mean time)
  2. things started to get tough when users will start creating job requests to Providers (Services are also different in matters of the Schema)

So at the end i decided to take a deep breath and dive into MongoDB implementation (This was my first time to deal with the so called NoSQL Kind of things ...)

After that i tried to clean up my Api Authentication Controller as well as my Api Controller, i also created a Validation trait to extract validation rules and request fields.

Please check the code below and dont hesitate to post your comment how to improve it further!

ApiController

/** * */ const CODE_WRONG_ARGS = 'GEN-FUBARGS'; const CODE_NOT_FOUND = 'GEN-LIKETHEWIND'; const CODE_INTERNAL_ERROR = 'GEN-AAAGGH'; const CODE_UNAUTHORIZED = 'GEN-MAYBGTFO'; const CODE_FORBIDDEN = 'GEN-GTFO';

/**
 * @var int
 */
protected $statusCode = 200;

/**
 * @var Request
 */
protected $request;
/**
 * @var Manager
 */
protected $fractal;




public function __construct(Request $request, Manager $fractal)
{
    $this->request = $request;
    $this->fractal = $fractal;
}

/**
 * @return int
 */
public function getStatusCode()
{
    return $this->statusCode;
}


/**
 * @param $statusCode
 * @return $this
 */
public function setStatusCode($statusCode)
{
    $this->statusCode = $statusCode;
    return $this;
}

/**
 * @param $item
 * @param $callback
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithItem($item, $callback)
{
    $resource = new Item($item, $callback);
    $rootScope = $this->fractal->createData($resource);
    return $this->respondWithArray($rootScope->toArray());


}


/**
 * @param $collection
 * @param $callback
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithCollection($collection, $callback)
{
    $resource = new Collection($collection, $callback);

    $rootScope = $this->fractal->createData($resource);
    return $this->respondWithArray($rootScope->toArray());
}

/**
 * @param array $array
 * @param array $headers
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithArray(array $array, array $headers = [])
{
     $response = response()->json($array, $this->statusCode, $headers);
     $response->header('Content-Type', 'application/json');
    return $response;
}


/**
 * @param string $message
 * @return \Illuminate\Http\JsonResponse
 */
public function respondNotFound($message = 'resource not found')
{
    return $this->setStatusCode(400)->respondWithError($message, $this->getStatusCode());
}

/**
 * @param $data
 * @param array $headers
 * @return \Illuminate\Http\JsonResponse
 */
public function respond($data, $headers = [])
{
    return response()->json([
        $data,
        $this->getStatusCode(),
        $headers]);
}


/**
 * @param $message
 * @param $errorCode
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithError($message, $errorCode)
{
    if ($this->statusCode === 200) {
        trigger_error(
            "You better have a really good reason for erroring on a 200...",
            E_USER_WARNING
        );
    }
    return $this->respondWithArray([
        'error' => [
            'code' => $errorCode,
            'http_code' => $this->statusCode,
            'message' => $message,
        ]
    ]);
}


public function errorForbidden($message = 'Forbidden')
{
    return $this->setStatusCode(403)
        ->respondWithError($message, self::CODE_FORBIDDEN);
}



public function errorInternalError($message = 'Internal Error')
{
    return $this->setStatusCode(500)
        ->respondWithError($message, self::CODE_INTERNAL_ERROR);
}

public function errorNotFound($message = 'Resource Not Found')
{
    return $this->setStatusCode(404)
        ->respondWithError($message, self::CODE_NOT_FOUND);
}

public function errorUnauthorized($message = 'Unauthorized')
{
    return $this->setStatusCode(401)
        ->respondWithError($message, self::CODE_UNAUTHORIZED);
}

/**
 * @param string $message
 * @return \Illuminate\Http\JsonResponse
 */
public function errorWrongArgs($message = 'Wrong Arguments')
{
    return $this->setStatusCode(400)
        ->respondWithError($message, self::CODE_WRONG_ARGS);
}

}

ApiAuthController

use AuthValidationTrait;

/**
 * Login the user by checking his credentials and return a JWT
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try
    {
        if( !$token = JWTAuth::attempt($credentials)){

            return $this->setStatusCode(401)->respondWithError('invalid_credentials', $this->getStatusCode());

        }
    } catch (JWTException $e) {

        return $this->setStatusCode(500)->respondWithError('could_not_create_token', $this->getStatusCode());

    }

    return $this->respond(compact('token'));
}


/**
 * Get the authenticated user via the provided token
 * @return \Illuminate\Http\JsonResponse
 */
public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());


    } catch (TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());
        
    }

    return $this->respondWithItem($user, new UserTransformer);
}


/**
 * Perform validation checks and create the user
 * @param $userType
 * @return \Illuminate\Http\JsonResponse
 */
public function register($userType)
{
    $validator = Validator::make($this->request->all(), $this->rules($userType));

    if($validator->fails())
    {

        return $this->setStatusCode(422)->respondWithError($validator->errors()->getMessages(), $this->getStatusCode());

    }

    return $this->createUser($userType);
}


/**
 * Create the user and merge the user type with the request data
 * @param $userType
 * @return \Illuminate\Http\JsonResponse
 */
public function createUser($userType)
{
    $data = array_merge(['type'=>$userType], $this->request->only($this->fields($userType)));

    $user = User::create($data);

    return $this->respondWithItem($user, new UserTransformer);

}

}

AuthValidationTrait

protected $validationRules = [ 'client'=>[ 'name' => 'required|max:100', 'mobile' => 'required|numeric', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6', ], 'provider'=>[ 'company_name' => 'required|max:100', 'address' => 'required', 'phone' => 'required|numeric', 'contact_person' => 'required|max:100', 'mobile' => 'required|numeric', 'description' => 'required|min:15|max:250', 'website' => 'required|max:255', 'logo' => '|min:6required', //TODO plan logo upload 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6', ] ];

/**
 * returns the validation array key/value
 * @param $userType
 * @return mixed
 */
public function rules($userType)
{
    return  $this->validationRules[$userType];
}

/**
 * get the request fields using the validation array keys
 * @param $userType
 * @return array
 */
public function fields($userType)
{
    return array_keys($this->rules($userType));
}

Thanks in advance LaraFolks!!

06 Mar
3 years ago

zakhttp left a reply on Multi User Sign Up In Laravel 5.1 Using JWT

Here is my ApiAuthController Code, i am wondering how can i imporve it or refacor it:

class ApiAuthController extends ApiController {

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try
    {
        if( !$token = JWTAuth::attempt($credentials)){
            return response()->json(['error'=>'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error'=>'could_not_create_token'], 500);

    }

    return response()->json(compact('token'));
}

/**
 * @return \Illuminate\Http\JsonResponse
 */
public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    return response()->json(compact('user'));
}



/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerClient(Request $request)
{

    $validationRules=[
        'name' => 'required|max:100',
        'mobile' => 'required|numeric',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
    ];
    $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $client = Client::create($request->only('name', 'mobile'));
    $user = new User($request->only('email','password'));
    $user['password'] = Hash::make($request->password);
    return $client->user()->save($user);
}


/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerProvider(Request $request)
{
    $validationRules = [
        'company_name' => 'required|max:100',
        'address' => 'required',
        'phone' => 'required|numeric',
        'contact_person' => 'required|max:100',
        'mobile' => 'required|numeric',
        'description' => 'required|min:15|max:250',
        'website' => 'required|max:255',
        'logo' => '|min:6required', //TODO plan logo upload
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
        ];
    $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $provider = Provider::create($request->except('email', 'password'));
    $user = new User($request->only('email', 'password'));
    $user['password'] = Hash::make($request->password);
    return $provider->user()->save($user);
}

}

zakhttp left a reply on Multi User Sign Up In Laravel 5.1 Using JWT

Below is mu ApiAuthController code, i am still wondering how can i refactor it to make it better:

namespace App\Http\Controllers\Auth;

use App\Client; use App\Http\Controllers\ApiController; use App\Provider; use App\User; use Illuminate\Http\Request;

use App\Http\Requests; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Tymon\JWTAuth\Facades\JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException;

class ApiAuthController extends ApiController {

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try
    {
        if( !$token = JWTAuth::attempt($credentials)){
            return response()->json(['error'=>'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error'=>'could_not_create_token'], 500);

    }

    return response()->json(compact('token'));
}

/**
 * @return \Illuminate\Http\JsonResponse
 */
public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    return response()->json(compact('user'));
}


/**
 * register a user
 * @param Request $request
 * @return static
 */


/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerClient(Request $request)
{

    $validationRules=[
        'name' => 'required|max:100',
        'mobile' => 'required|numeric',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
    ];
    $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $client = Client::create($request->only('name', 'mobile'));
    $user = new User($request->only('email','password'));
    $user['password'] = Hash::make($request->password);
    return $client->user()->save($user);
}


/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerProvider(Request $request)
{
    $validationRules = [
        'company_name' => 'required|max:100',
        'address' => 'required',
        'phone' => 'required|numeric',
        'contact_person' => 'required|max:100',
        'mobile' => 'required|numeric',
        'description' => 'required|min:15|max:250',
        'website' => 'required|max:255',
        'logo' => '|min:6required', //TODO plan logo upload
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
        ];
    $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $provider = Provider::create($request->except('email', 'password'));
    $user = new User($request->only('email', 'password'));
    $user['password'] = Hash::make($request->password);
    return $provider->user()->save($user);
}

}

zakhttp left a reply on Multi User Sign Up In Laravel 5.1 Using JWT

Here is mi ApiAuthController code: class ApiAuthController extends ApiController {

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try
    {
        if( !$token = JWTAuth::attempt($credentials)){
            return response()->json(['error'=>'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error'=>'could_not_create_token'], 500);

    }

    return response()->json(compact('token'));
}

/**
 * @return \Illuminate\Http\JsonResponse
 */
public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

// $userable = $user->userable->toArray(); return response()->json(compact('user')); }

/**
 * register a user
 * @param Request $request
 * @return static
 */


/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerClient(Request $request)
{

    $validationRules=[
        'name' => 'required|max:100',
        'mobile' => 'required|numeric',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
    ];
    $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $client = Client::create($request->only('name', 'mobile'));
    $user = new User($request->only('email','password'));
    $user['password'] = Hash::make($request->password);
    return $client->user()->save($user);
}


/**
 * @param Request $request
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\JsonResponse
 */
public function registerProvider(Request $request)
{
    $validationRules = [
        'company_name' => 'required|max:100',
        'address' => 'required',
        'phone' => 'required|numeric',
        'contact_person' => 'required|max:100',
        'mobile' => 'required|numeric',
        'description' => 'required|min:15|max:250',
        'website' => 'required|max:255',

// 'logo' => '|min:6required', //TODO plan logo upload 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6', ]; $validator = Validator::make($request->all(), $validationRules);

    if ($validator->fails()) {
        return response()->json([
            'error' => $validator->errors()
        ]);
    }

    $provider = Provider::create($request->except('email', 'password'));
    $user = new User($request->only('email', 'password'));
    $user['password'] = Hash::make($request->password);
    return $provider->user()->save($user);
}

}

zakhttp left a reply on Multi User Sign Up In Laravel 5.1 Using JWT

Thanks Hero21, i am actually not looking for the roles definition yet, i am still stuck with touting signup requests because clients and providers have different sign up fields.

zakhttp started a new conversation Multi User Sign Up In Laravel 5.1 Using JWT

Hello Guys, i am working on a personal project for a backend api using Laravel 5.1 I basically have two types of users : Clients and Vendors. both of them sharing a user model using polymorphic relationships.

Users Table id Email Password userable_id Userable_type

Clients Table id name mobile

Vendors id Company name Website

What's the best way to write a sign up function using jwt and how can i route thr requests respectfully to rest principles,

Thanks a lot,

17 Feb
3 years ago

zakhttp left a reply on Use Of Undefined Constant MCRYPT_RIJNDAEL_128 - Assumed 'MCRYPT_RIJNDAEL_128'

@psybaron thanks it worked for me on laravel 5.0 and php 7