gzai

gzai

Member Since 9 Months Ago

Experience Points
12,830
Total
Experience

2,170 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.

Level 3
12,830 XP
Oct
11
1 week 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
1 month 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
1 month 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
1 month 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
1 month 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
2 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);
	    }

	    ...
	}
May
31
4 months ago
Activity icon

Commented on Eventing Pros And Cons

How can we set the listener's order as we want? laravel set order listener based on the order of naming? or we can set the listener's order as we want? in video :

'check for new archivements'
'do other thing'
'send shareable coupon'

how to change order like this :

'check for new archivements'
'send shareable coupon'
'do other thing'
May
09
5 months ago
Activity icon

Replied to Auth::user() Is Not Right

I know what happen, after looking for some possibilities.

I have api_token in every user to access API Routes, and when I create User ID 530, I copy api_token from User ID 529 to user ID 530 ( because I just want to hurry up ).

Call Auth::user() on Web Route is correct, and call Auth::user() or Auth::guard('api')->user() on Api Routes is not correct. Because it has same api_token, the first user has same api_token will be called first.

https://laravel.com/docs/5.8/api-authentication

Schema::table('users', function ($table) {
    $table->string('api_token', 80)->after('password')
                        ->unique()
                        ->nullable()
                        ->default(null);
});

Update api_token with unique str random for User ID 530, and now calling Auth::user() or Auth::guard('api')->user() for User ID 530 will be correct.

Update note :

So If I have access to someone website database, and copy superadmin's api_token to my user api_token, I will have superadmin's auth data to access API Route. very scary!!!

May
08
5 months ago
Activity icon

Replied to Display Bulk Data Using Ajax From DB In Laravel

you can use jquery autocomplete

Activity icon

Replied to Auth::user() Is Not Right

@nakov try Auth::guard('api')->user();, the result is still wrong.

ApiController

print_r( Auth::guard('api')->user() );

// result
App\User Object
(
    [fillable:protected] => Array
        (
            [0] => username
            [1] => email
            [2] => password
            [3] => api_token
        )

    [hidden:protected] => Array
        (
            [0] => password
            [1] => remember_token
            [2] => api_token
        )

    [casts:protected] => Array
        (
            [email_verified_at] => datetime
        )

    [connection:protected] => mysql
    [table:protected] => users
    [primaryKey:protected] => id
    [keyType:protected] => int
    [incrementing] => 1
    [with:protected] => Array
        (
        )

    [withCount:protected] => Array
        (
        )

    [perPage:protected] => 15
    [exists] => 1
    [wasRecentlyCreated] => 
    [attributes:protected] => Array
        (
            [id] => 529 // not correct
	...
Activity icon

Started a new Conversation Auth::user() Is Not Right

Hi,

After login I check data Auth::user() is correct.

PanelController

print_r( Auth::user() );

// result
App\User Object
(
    [fillable:protected] => Array
        (
            [0] => username
            [1] => email
            [2] => password
            [3] => api_token
        )

    [hidden:protected] => Array
        (
            [0] => password
            [1] => remember_token
            [2] => api_token
        )

    [casts:protected] => Array
        (
            [email_verified_at] => datetime
        )

    [connection:protected] => mysql
    [table:protected] => users
    [primaryKey:protected] => id
    [keyType:protected] => int
    [incrementing] => 1
    [with:protected] => Array
        (
        )

    [withCount:protected] => Array
        (
        )

    [perPage:protected] => 15
    [exists] => 1
    [wasRecentlyCreated] => 
    [attributes:protected] => Array
        (
            [id] => 530 // correct
	...

but after I check data Auth::user() in api controller, data from Auth::user() is not correct.

ApiController

print_r( Auth::user() );

// result
App\User Object
(
    [fillable:protected] => Array
        (
            [0] => username
            [1] => email
            [2] => password
            [3] => api_token
        )

    [hidden:protected] => Array
        (
            [0] => password
            [1] => remember_token
            [2] => api_token
        )

    [casts:protected] => Array
        (
            [email_verified_at] => datetime
        )

    [connection:protected] => mysql
    [table:protected] => users
    [primaryKey:protected] => id
    [keyType:protected] => int
    [incrementing] => 1
    [with:protected] => Array
        (
        )

    [withCount:protected] => Array
        (
        )

    [perPage:protected] => 15
    [exists] => 1
    [wasRecentlyCreated] => 
    [attributes:protected] => Array
        (
            [id] => 529 // not correct
	...

need help

May
07
5 months ago
Activity icon

Replied to How To Run 2 Service Supervisors With 2 Separate Logs

Found the solution

I think I can only make one laravel-worker.conf file, but it can create many files with different names.

Problem solved

Activity icon

Started a new Conversation How To Run 2 Service Supervisors With 2 Separate Logs

Hi,

I have 1 server with 2 websites ( Laravel 5.3 & Laravel 6.15 ), and have a supervisor only run 1 service ( Laravel 5.3 ), if I want to set run 2 service in supervisor ( Laravel 5.3 & Laravel 6.15 ), How to separate the logs?

May
02
5 months ago
Activity icon

Replied to How Come Package Migrations Runs Before Project's Main Migrations ?

migration will process based on the past date until the most recent date from the naming of the migration file

Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

It's okay @rodrigo.pedra. I am very grateful because you replied in your busy schedule.

We can set unique request too :

protected function prepareForValidation()
{
    if (!request()->has('enable')) return; // do nothing

    // process as above
}

I thought there is a method to enable or disable the custom request for prepareForValidation that we are calling.

ex:

public function store(TasksRequest(false) $request) // disable prepareForValidation

public function quick_add(TasksRequest(true) $request) // enable prepareForValidation
Apr
30
5 months ago
Activity icon

Replied to 419 CSRF Token Unknow Status Handle

Status Code: 419 unknown status, permission on the storage folder? maybe can't write session.

Activity icon

Replied to 419 CSRF Token Unknow Status Handle

add this to your App\Exceptions\Handler.php

    public function render($request, Exception $exception)
    {

        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            return redirect('/login');
        }

        return parent::render($request, $exception);
    }
Activity icon

Replied to How To Retrieve Random Slug From Database

better use HashID or UUID

HashID create a unique random str based on your ID, and you don't need to save it in database. https://github.com/vinkla/laravel-hashids or https://github.com/mtvs/eloquent-hashids

Activity icon

Replied to Create Link With Id Passed To It

you have set /animals/{{ $animal->id }}, then /animalphotos/create/{{ $animal->id }}

Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

@rodrigo.pedra how I can use prepareForValidation only for public function quick_add and disable prepareForValidation for public function store(TasksRequest $request) ?

Apr
29
5 months ago
Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

I have store process just like that, and this process is correct.

use App\Requests\TasksRequest;

class TasksController extends Controller 
{

	public function store(TasksRequest $request) 
	{
		$result = $this->tasksRepository->create( $request->validated() );
		return $result;
	}

}

Then I have another function that require the TasksRequest

class TasksRepository 
{

	public function quick_add(Request $request)
	{

		$id = ( $request->has('id') ) ? $request->get('id') : 0 ;

		$suggest = TasksSuggests::find( $id );

		// here init data from suggest and merge to $request

		$request_tasks = app('App\Requests\TasksRequest');
        	$request_tasks->setValidator( Validator::make( $request->all(), $request_tasks->rules(), $request_tasks->messages() ) );

        	$result = $this->create( $request_tasks->validated() );

		return $result;

	}

	public function create($input)
	{
		return Tasks::create( $input ); 
	}

}

I can't do it like a store process for public function quick_add(TasksRequest $request), because before the validation process in function quick_add, I have to init the merge data with the request.

Apr
27
5 months ago
Activity icon

Started a new Conversation Calling Validation FormRequest From Controller Is Sometimes Incorrect

Hello,

I have FormRequest, and I want to call FormRequest in other api controller

controller :


$request_tasks = app('App\Requests\TasksRequest');
$request_tasks->setValidator( Validator::make( $request->all(), $request_tasks->rules(), $request_tasks->messages() ) );

$result = $this->create( $request_tasks->validated() );

The process validation is correct, but sometime validation incorrect for some rule. does anyone know the issue?

Apr
24
5 months ago