gzai

Member Since 1 Year Ago

Experience Points
12,890
Total
Experience

2,110 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
102
Lessons
Completed
Best Reply Awards
2
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.

  • Community Pillar

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

Level 3
12,890 XP
Jan
13
2 weeks ago
Activity icon

Started a new Conversation Laravel Middleware Throttle Is Not Working

Hi,

I have laravel 7, kernel throttle:60,1, and specific route have middleware throttle:120,1.

hit php artisan cache:clear and php artisan config:clear

when I tried on postman specific route, why X-RateLimit-Limit is 60 instead of 120?

Activity icon

Replied to Serverless Laravel On AWS With Bref Deployment Error

@agoi yes. bref has the latest version 1.0.

Oct
11
3 months ago
Activity icon

Started a new Conversation Laravel Where Parameter Grouping For Having Is Not Right

Hi,

I have query to check distance for google coordinate.

When I set havingRaw for check distance this is working well.

->when( $request->has('distance') && $request->get('distance') != '', function($query) use ($request) {
    return $query->havingRaw('distance <= ?', [ $request->get('distance') ]);
})

But when I set havingRaw with parameter grouping this is not working well.

->when( $request->has('distance') && $request->get('distance') != '', function($query) use ($request) {
    return $query->where(function($subQuery) use ($request) {
        return $subQuery->havingRaw('distance <= ?', [ $request->get('distance') ]);
    });
})

I want to add other parameter for orHavingRaw

...
->when( $request->has('distance') && $request->get('distance') != '', function($query) use ($request) {
    return $query->where(function($subQuery) use ($request) {
        return $subQuery->havingRaw('distance <= ?', [ $request->get('distance') ]);
    	    ->orHavingRaw('distance == ?', [ '0.0' ]);
    });
})

Update :

Solved. I was wrong thinking using having in where.

->when( $request->has('distance') && $request->get('distance') != '', function($query) use ($request) {
    return $query->havingRaw('distance <= ? OR distance = ?', [ $request->get('distance'), 0 ]);
})
Sep
17
4 months ago
Activity icon

Replied to Update Field Unique

public function update(CategoryUpdateRequest $request, $id)
{
    $category = Category::findOrFail($id);
    $category->name_category = $request->name_category;
    $category->description = $request->description;

    if ($category->isDirty()) {
        $message = 'edited category';
    } else {
        $message = 'there are no changes';
    }

    $category->save();

    return response()->json([
        'message' => $message
    ]);
}
Sep
13
4 months ago
Activity icon

Replied to Update Field Unique

missing comma after table field

    return [
        'name_category' => "required|unique:categories,name_category," . $this->id,
        'description' => 'required'
    ];
Activity icon

Started a new Conversation Laravel API Event Logout For Data User Is Empty

Hi,

Laravel 7 API event when logout, result for user is empty, how to get data user before event logout execute ?

'Illuminate\Auth\Events\Logout' => [
	'App\Listeners\LogSuccessfulLogout',
],

Listener for event logout :

class LogSuccessfulLogout
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        if ( $event ) {
		// $event->user is empty for API, but for web return user data
        }
    }
}
Activity icon

Started a new Conversation Laravel 7 Create Custom Auth Guard API For Login

Hi,

I have custom Auth guard API but when I want to login from API, Illuminate\Auth\RequestGuard::login does not exist

auth.php

'guards' => [
        'api' => [
            'driver' => 'cognito',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

AuthServiceProvider.php

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        Auth::viaRequest('cognito', function ($request) {
            $token = $request->bearerToken();

            if ($token) {
            	$client = new CognitoClient;
            	
                return $client->verifyToken($token);
            }
            
            return null;
        });
    }
}

ApiController.php

    public function login(Request $request)
    {
    	...
    	if (! $result = $this->client->login($request->username, $request->password) ) 
    	{
    		$errors = Session::get('errors')->getMessageBag();
    		return response()->json($errors, 422);
    	}

        if (! $user = User::firstWhere('cognito_id', $this->client->getUserID($result['AccessToken'])) ) 
    	{
    		return response()->json([ 'login' => ['Unauthorized'] ], 401);
    	}

    	if ( isset($result['AccessToken']) ) {

		$remember = (isset($request->remember)&&$request->remember) ? true : false;

		auth('api')->login($user, $remember); // error
			
		return $result;

	    } else {

	    	return response()->json([ 'login' => ['Unauthorized'] ], 401);

	    }
    }

How to create custom login for custom Auth guard API ?

Sep
09
4 months ago
Activity icon

Replied to Laravel XSRF-TOKEN Missing

Create on VPC

this is my .env

APP_NAME="My CMS"
APP_ENV=production
APP_KEY=base64:LQO+ILW6BO6veWXkYBsIqcQSoqWSHsacYFrypweVavg=
APP_DEBUG=true
APP_URL=http://localhost/my_cms/public
APP_VERSION=0.1.1

LOG_CHANNEL=stderr
FILESYSTEM_DRIVER=s3
VIEW_COMPILED_PATH=/tmp/storage/framework/views

DB_CONNECTION=mysql
DB_HOST=mycms-dev-instance-1.xxx.ap-southeast-1.rds.amazonaws.com
DB_PORT=3306
DB_DATABASE=db_my_cms
DB_USERNAME=admin
DB_PASSWORD=admin123

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SESSION_LIFETIME=120

and this is my serverless.yml

service: my-cms

provider:
    name: aws
    # The AWS region in which to deploy (us-east-1 is the default)
    region: ap-southeast-1
    # The stage of the application, e.g. dev, production, staging… ('dev' is the default)
    stage: dev
    runtime: provided

package:
    # Directories to exclude from deployment
    exclude:
        - node_modules/**
        - public/storage
        - resources/assets/**
        - storage/**
        - tests/**

functions:
    # This function runs the Laravel website/API
    web:
        handler: public/index.php
        timeout: 28 # in seconds (API Gateway has a timeout of 29 seconds)
        layers:
            - ${bref:layer.php-74-fpm}
        events:
            -   http: 'ANY /'
            -   http: 'ANY /{proxy+}'
    # This function lets us run artisan commands in Lambda
    artisan:
        handler: artisan
        timeout: 120 # in seconds
        layers:
            - ${bref:layer.php-74} # PHP
            - ${bref:layer.console} # The "console" layer

resources:
    Resources:
        # CloudFront
        CloudFrontDistribution:
            Type: AWS::CloudFront::Distribution
            Properties:
                DistributionConfig:
                    Comment: My CloudFront Distribution
                    DefaultCacheBehavior:
                      TargetOriginId: MyFirstOrigin
                      ViewerProtocolPolicy: 'redirect-to-https'
                      DefaultTTL: 30
                      ForwardedValues:
                        QueryString: false
                    Enabled: true
                    Origins:
                      - Id: MyFirstOrigin
                        DomainName:
                          Fn::Join:
                            - "."
                            - - Ref: ApiGatewayRestApi
                              - execute-api.ap-southeast-1.amazonaws.com
                        OriginPath: /dev
                        CustomOriginConfig:
                          HTTPPort: 80
                          HTTPSPort: 443
                          OriginProtocolPolicy: https-only
        # The S3 bucket that stores the assets
        Assets:
            Type: AWS::S3::Bucket
            Properties:
                BucketName: 'bucket-cms'
        # The policy that makes the bucket publicly readable
        AssetsBucketPolicy:
            Type: AWS::S3::BucketPolicy
            Properties:
                Bucket: !Ref Assets # References the bucket we defined above
                PolicyDocument:
                    Statement:
                        -   Effect: Allow
                            Principal: '*' # everyone
                            Action: 's3:GetObject' # to read
                            Resource: !Join ['/', [!GetAtt Assets.Arn, '*']] # things in the bucket
                            # alternatively you can write out Resource: 'arn:aws:s3:::<bucket-name>/*'
        # CDN
        WebsiteCDN:
            Type: AWS::CloudFront::Distribution
            Properties:
                DistributionConfig:
                    Enabled: true
                    # Cheapest option by default (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DistributionConfig.html)
                    PriceClass: PriceClass_100
                    # Enable http2 transfer for better performances
                    HttpVersion: http2
                    # Origins are where CloudFront fetches content
                    Origins:
                        # The website (AWS Lambda)
                        -   Id: Website
                            DomainName: !Join ['.', [!Ref ApiGatewayRestApi, 'execute-api', !Ref AWS::Region, 'amazonaws.com']]
                            # This is the stage
                            OriginPath: "/${opt:stage, 'dev'}"
                            CustomOriginConfig:
                                OriginProtocolPolicy: 'https-only' # API Gateway only supports HTTPS
                        # The assets (S3)
                        -   Id: Assets
                            DomainName: !GetAtt Assets.RegionalDomainName
                            S3OriginConfig: {} # this key is required to tell CloudFront that this is an S3 origin, even though nothing is configured
                            # If you host a static website, like a SPA, use s3-website URLs instead of the config above
                            # See https://stackoverflow.com/questions/15309113/amazon-cloudfront-doesnt-respect-my-s3-website-buckets-index-html-rules#15528757
                            # DomainName: !Select [2, !Split ["/", !GetAtt Assets.WebsiteURL]]
                            # CustomOriginConfig:
                            #     OriginProtocolPolicy: 'http-only' # S3 websites only support HTTP
                            # You'll also need to enable website hosting on your s3 bucket by configuring the WebsiteConfiguration property
                            # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-websiteconfiguration
                    # The default behavior is to send everything to AWS Lambda
                    DefaultCacheBehavior:
                        AllowedMethods: [GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE]
                        TargetOriginId: Website # the PHP application
                        # Disable caching for the PHP application https://aws.amazon.com/premiumsupport/knowledge-center/prevent-cloudfront-from-caching-files/
                        DefaultTTL: 0
                        MinTTL: 0
                        MaxTTL: 0
                        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-forwardedvalues.html
                        ForwardedValues:
                            QueryString: true
                            Cookies:
                                Forward: all # Forward cookies to use them in PHP
                            # We must *not* forward the `Host` header else it messes up API Gateway
                            Headers:
                                - 'Accept'
                                - 'Accept-Language'
                                - 'Origin'
                                - 'Referer'
                        ViewerProtocolPolicy: redirect-to-https
                    CacheBehaviors:
                        # Assets will be served under the `/assets/` prefix
                        -   PathPattern: 'assets/*'
                            TargetOriginId: Assets # the static files on S3
                            AllowedMethods: [GET, HEAD]
                            ForwardedValues:
                                # No need for all that with assets
                                QueryString: 'false'
                                Cookies:
                                    Forward: none
                            ViewerProtocolPolicy: redirect-to-https
                            Compress: true # Serve files with gzip for browsers that support it (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html)
                    CustomErrorResponses:
                        # Do not cache HTTP errors
                        -   ErrorCode: 500
                            ErrorCachingMinTTL: 0
                        -   ErrorCode: 504
                            ErrorCachingMinTTL: 0

plugins:
    # We need to include the Bref plugin
    - ./vendor/bref/bref
Activity icon

Replied to Laravel XSRF-TOKEN Missing

Yes, I followed everything on that link, set up everything correctly.

and I followed this link bref.sh.

I don't know what setting is missing. CSRF like rejected, and I have login API with JWT, success return token, when I use that token to other API link, token not same.

Activity icon

Replied to Laravel XSRF-TOKEN Missing

@bobbybouwmann thanks for reply.

this is my first time trying deploy on aws serverless lambda. I haven't tried adding a whitelist header.

Activity icon

Started a new Conversation Laravel XSRF-TOKEN Missing

Hi,

I have laravel 7 and in all form have @csrf, after submit return request and running well in local. but after deploy to aws serverless, after submit all form return 419 page expired. after check in aws serverless, set-cookie: XSRF-TOKEN is missing in inspect network.

What is wrong? any idea?

Sep
02
4 months ago
Activity icon

Started a new Conversation Serverless Laravel On AWS With Bref Deployment Error

I want to deploy laravel with bref to aws serverless but stuck with this error

'There is no Bref layer named "php-74-fpm" in region "us-southeast-1"'

I check runtime bref for php-74-fpm in region us-southeast-1 exist.

What am I doing wrong here?

This is my serverless.yml :

service: laravel

provider:
    name: aws
    # The AWS region in which to deploy (us-east-1 is the default)
    region: us-southeast-1
    # The stage of the application, e.g. dev, production, staging… ('dev' is the default)
    stage: dev
    runtime: provided

package:
    # Directories to exclude from deployment
    exclude:
        - node_modules/**
        - public/storage
        - resources/assets/**
        - storage/**
        - tests/**

functions:
    # This function runs the Laravel website/API
    web:
        handler: public/index.php
        timeout: 28 # in seconds (API Gateway has a timeout of 29 seconds)
        layers:
            - ${bref:layer.php-74-fpm}
        events:
            -   http: 'ANY /'
            -   http: 'ANY /{proxy+}'
    # This function lets us run artisan commands in Lambda
    artisan:
        handler: artisan
        timeout: 120 # in seconds
        layers:
            - ${bref:layer.php-74} # PHP
            - ${bref:layer.console} # The "console" layer

plugins:
    # We need to include the Bref plugin
    - ./vendor/bref/bref
Aug
20
5 months ago
Activity icon

Replied to Show MessageBag In Json

Sorry for making the question.

Have found the solution, for users who need a solution :

api controller :

	public function sendData(Request $request)
	{
	    // validation
	    ...

	    if (! $result = $this->dataService->processData($data) ) 
	    {
    		$errors = Session::get('errors')->getMessageBag();
    		return response()->json($errors, 422);
	    }

	    ...
	}
Activity icon

Started a new Conversation Show MessageBag In Json

Hi, I have a service and can add messagebag error from function add_error, messagebag error can show in web controller, but how to show messagebag error in api controller ?

service :

	public function processData($data)
	{
	    try {
	        $response = // processing data
	    } catch (DataException $exception) {
	        if ($exception->errorCode() === self::NOT_FOUND) {
	            $this->add_error('The data is not found!', 'data');
	            return false;
	        }

	        throw $exception;
	    }

	    return $response;
	}

	protected function add_error($error_msg, $key = 'default') 
	{
	    $errors = Session::get('errors', new ViewErrorBag);

	    if (! $errors instanceof ViewErrorBag) {
	        $errors = new ViewErrorBag;
	    }

	    $bag = $errors->getBags()['default'] ?? new MessageBag;
	    $bag->add($key, $error_msg);

	    Session::flash(
	        'errors', $errors->put('default', $bag)
	    );
	}

web controller (success show error from process data service) :

	public function sendData(Request $request)
	{
	    // validation
	    ...

	    if (! $result = $this->dataService->processData($data) ) 
	    {
	        return redirect()->back()->withInput();
	    }

	    ...
	}

api controller (cannot show error from process data service) :

	public function sendData(Request $request)
	{
	    // validation
	    ...

	    if (! $result = $this->dataService->processData($data) ) 
	    {
	        return response()->json($validator->errors(), 422);
	    }

	    ...
	}