PetroGromovo

PetroGromovo

Member Since 1 Year Ago

Experience Points
4,710
Total
Experience

290 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
1
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
4,710 XP
May
26
5 days ago
Activity icon

Started a new Conversation Mapping With Elasticquent Got Root Mapping Definition Has Unsupported Parameters Error

Hello, In Laravel 7.12.0 app I added "elasticquent/elasticquent": "dev-master" plugin and I try to implement sample data example from https://www.elastic.co/blog/a-practical-introduction-to-elasticsearch

with shakespeare.json file

But making mapping I got error :

Elasticsearch\Common\Exceptions\BadRequest400Exception
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [shakespeares : {_source={enabled=true}, properties={play_name={analyzer=standard, type=string}, speech_number={analyzer=standard, type=number}, line_number={analyzer=standard, type=string}, text_entry={analyzer=standard, type=text}, speaker={analyzer=standard, type=string}, line_id={analyzer=standard, type=integer}}}]"}],"type":"mapper_parsing_exception","reason":"Failed to parse mapping [_doc]: Root mapping definition has unsupported parameters: [shakespeares : {_source={enabled=true}, properties={play_name={analyzer=standard, type=string}, speech_number={analyzer=standard, type=number}, line_number={analyzer=standard, type=string}, text_entry={analyzer=standard, type=text}, speaker={analyzer=standard, type=string}, line_id={analyzer=standard, type=integer}}}]","caused_by":{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [shakespeares : {_source={enabled=true}, properties={play_name={analyzer=standard, type=string}, speech_number={analyzer=standard, type=number}, line_number={analyzer=standard, type=string}, text_entry={analyzer=standard, type=text}, speaker={analyzer=standard, type=string}, line_id={analyzer=standard, type=integer}}}]"}},"status":400}

I created model /app/Shakespeare.php :

<?php

namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use App\library\MyFuncsClass;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Elasticquent\ElasticquentTrait;

class Shakespeare extends Model
{
    use ElasticquentTrait;
    protected $table = 'shakespeares';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $mappingProperties = array(
/*        'title' => array(
            'type' => 'string',
            'analyzer' => 'standard'
        )*/
        'line_id' => [
            'type' => 'integer',
            'analyzer' => 'standard'
        ],

        'play_name' => [
            'type' => 'string',
            'analyzer' => 'standard' // not_analyzed
        ],

        'speech_number' => [
            'type' => 'number',
            'analyzer' => 'standard'
        ],


        'line_number' => [
            'type' => 'string', // line_number??
            'analyzer' => 'standard'
        ],

        'speaker' => [
            'type' => 'string',
            'analyzer' => 'standard' // not_analyzed
        ],


        'text_entry' => [
            'type' => 'text',
            'analyzer' => 'standard'
        ],

    );



    protected $fillable = [
        'id', 'line_id', 'play_name', 'speech_number', 'line_number', 'speaker', 'text_entry', 'created_at', 'updated_at'
    ];

    function getIndexName()
    {
        return 'shakespeares_root';
    }

    public static function setESMapping()
    {
//        if (   Shakespeare::mappingExists() ) {
//        Shakespeare::deleteMapping();
//        }


        // Error pointing to line below !
        $ret= Shakespeare::createIndex(/*$shards = null, $replicas = null*/);
        \Log::info( '-1 setESMapping $ret ::' . print_r(  $ret, true  ) );

        $ret= Shakespeare::putMapping( true/*$ignoreConflicts = true*/);
        \Log::info( '-2 setESMapping $ret ::' . print_r(  $ret, true  ) );

        $ret= Shakespeare::addAllToIndex();
        \Log::info( '-3 setESMapping $ret ::' . print_r(  $ret, true  ) );

my config/elasticquent.php :

<?php

return array(
    'config' => [
        'hosts'     => ['localhost:9200'],
        'retries'   => 1,
    ],

    'default_index' => 'my_custom_index_name',

);

elasticsearch is running at the moment and I have in console :

 curl localhost:9200
{
  "name" : "athoe",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "e53SDZ6PTMyXhbeJ0Zx7TQ",
  "version" : {
    "number" : "7.7.0",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "81a1e9eda8e6183f5237786246f6dced26a10eaf",
    "build_date" : "2020-05-12T02:01:37.602180Z",
    "build_snapshot" : false,
    "lucene_version" : "8.5.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

I tried to hide columns in $mappingProperties , leaving only sample

'title' => array(
            'type' => 'string',
            'analyzer' => 'standard'
        )

But I have the same error. How to fix it ?

elasticsearch : Version: 7.7.0

Thanks!

May
22
1 week ago
Activity icon

Started a new Conversation How To Use Mixing In Cypress Of Vue/cli 4 App?

Hello, In vue/cli 4 app using cypress for testing I want to use my mixing and for this in my tests/e2e/specs/fileupload_tests.js I added declaration:

import faker from 'faker'
import 'cypress-file-upload'
import appMixin from '../../../src/appMixin'        // Full path is src/appMixin.js

describe('Admin category fileupload functionality', () => {
    it('category fileupload', () => {
        ...

But I see error in my browser :

/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/node_modules/@babel/runtime/helpers/esm/typeof.js:1
export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

That is not error of invalid mixing path - in this case I got different error.

Which way is valid ?

    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "cypress-file-upload": "^3.5.3",
    "vue": "^2.6.10",

Thanks!

May
11
2 weeks ago
Activity icon

Replied to Installed Mewebstudio/captcha Always Returned Invalid Capture

Thanks! It asks for INVISIBLE_RECAPTCHA_SECRETKEY. I have to get it on some external resource ?

Activity icon

Started a new Conversation Installed Mewebstudio/captcha Always Returned Invalid Capture

Hello! I installed mewebstudio/captcha in my Laravel 7.6 app but it always returned Invalid capture, even I enter valid value I enter in text inpur. Ex: entering https://prnt.sc/s8g03j and submitting form : I got

Invalid capture.

error. I try to debug info and see output from request validation in app/Http/Requests/ContactUsRequest.php with code :

    public function rules()
    {
        $request     = request();
        $requestData = $request->all();
        \Log::info( '-1 ContactUsRequest $requestData ::' . print_r(  json_encode($requestData), true  ) );

        \Log::info( '-2 contacts_us_post $request->session()->all(); ::' . print_r(  $request->session()->all(), true  ) );


        $a= ContactUs::getValidationRulesArray( [ 'skip_acceptor_id', 'skip_accepted'] );
        \Log::info( '-2 ContactUsRequest $a ::' . print_r(  $a, true  ) );
        return $a;
    }

When rules are defined in model :

    public static function getValidationRulesArray($options): array
    {
        $validationRulesArray = [
            'author_name'  => 'required|string|max:255',
            'author_email' => 'required|email|max:255',
            'message'      => 'required',
            'acceptor_id'  => 'required|integer|exists:' . (with(new User)->getTable()) . ',id',
            'accepted'     => 'required|in:' . with(new ContactUs)->getValueLabelKeys(ContactUs::getContactUsAcceptedValueArray(false)),
            'captcha'      => 'required|captcha'
        ];
        if (in_array('skip_acceptor_id', $options)) {
            unset($validationRulesArray['acceptor_id']);
        }
        if (in_array('skip_accepted', $options)) {
            unset($validationRulesArray['accepted']);
        }

        return $validationRulesArray;
    }

Checking logs I see :

[2020-04-30 10:29:12] local.INFO: -1 ContactUsRequest $requestData ::{"_token":"n8rVAUJhjg42hupGUntJZWwbOwzIcUmFYWna2e64","author_name":"[email protected]","author_email":"[email protected]","message":"text from [email protected] lorem\r\nipsum","captcha":"qtee7n"}  
[2020-04-30 10:29:12] local.INFO: -2 contacts_us_post $request->session()->all(); ::Array
(
    [_token] => n8rVAUJhjg42hupGUntJZWwbOwzIcUmFYWna2e64
    [_previous] => Array
        (
            [url] => http://local-votes.com/show_banner_image/1/PHP+site/php-logo.png/PHP+is+a+popular+scripting+language/2?dt=1588231599
        )

    [_flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [captcha] => Array
        (
            [sensitive] => 
            [key] => yt2.cC8CAPOd8JS8ZfcnUOeZr0RzD2eIDylRYurg41or1TpiEn7oS
        )

    [votes_register] => Array
        (
            [username] => JackParrot
            [email] => [email protected]
            [password] => 111111
            [first_name] => Jack
            [last_name] => Parrot
            [phone] => 098-765-4321
            [website] => jackparrot.vote_site.com
            [notes] => 
            [sex] => M
            [selectedSubscriptions] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => 
                            [1] => 1
                            [2] => 2
                        )

                )

        )

)
  
[2020-04-30 10:29:12] local.INFO: -2 ContactUsRequest $a ::Array
(
    [author_name] => required|string|max:255
    [author_email] => required|email|max:255
    [message] => required
    [captcha] => required|captcha
)

I see my entered data in request and captcha data insession with key and I do not see error in captcha code code. Did I miss some options ?

My composer.json:

{
	"name": "laravel/laravel",
	"description": "The Laravel Framework.",
	"keywords": [
		"framework",
		"laravel"
	],
	"license": "MIT",
	"type": "project",

	"require": {
		"php": "^7.2.5",
		"alaouy/youtube": "^2.2",
		"aloha/twilio": "^4.0",
		"arrilot/laravel-widgets": "^3.12",
		"cornford/googlmapper": "^3.2.1",
		"cviebrock/eloquent-sluggable": "^7.0",
		"davejamesmiller/laravel-breadcrumbs": "5.x",
		"doctrine/dbal": "^2.8",
		"facebook/graph-sdk": "^5.7",
		"fideloper/proxy": "^4.0",
		"google/apiclient": "^2.4.1",
		"guzzlehttp/guzzle": "6.5.x-dev",
		"intervention/image": "^2.4",
		"itsgoingd/clockwork": "^3.0",
		"jrean/laravel-user-verification": "dev-master",
		"laravel/cashier": "^10.3",
		"laravel/framework": "^7.0",
		"laravel/passport": "^8.4",
		"laravel/tinker": "^2.0",
		"laravel/ui": "^2.0",
		"laravelium/sitemap": "7.0.1",
		"maatwebsite/excel": "^3.1",
		"mews/captcha": "^3.1",
		"mews/purifier": "3.2.0",
		"paypal/rest-api-sdk-php": "*",
		"pelago/emogrifier": "3.1.0",
		"proengsoft/laravel-jsvalidation": ">2.2.0",
		"qlick/laravel-full-calendar": "~1.0",
		"s-ichikawa/laravel-sendgrid-driver": "~2.0",
		"snowfire/beautymail": "dev-master",
		"spatie/browsershot": "^3.27",
		"spatie/db-dumper": "^2.14",
		"spatie/laravel-activitylog": "^3.1",
		"spatie/laravel-backup": "^6.1",
		"spatie/laravel-feed": "^2.1",
		"spatie/laravel-image-optimizer": "^1.4",
		"spatie/laravel-newsletter": "^4.2",
		"spatie/laravel-sitemap": "^5.3",
		"spatie/laravel-tags": "^2.1",
		"spipu/html2pdf": "^5.2",
		"stripe/stripe-php": "^7.2",
		"symfony/psr-http-message-bridge": "^1.2",
		"themsaid/laravel-mail-preview": "dev-master",
		"unisharp/laravel-filemanager": "^1.9",
		"wboyz/laravel-enum": "^0.2.1",
		"willvincent/feeds": "dev-master",
		"yajra/laravel-datatables-oracle": "^9.0.0",
		"zendframework/zend-diactoros": "^2.1"
	},

	"require-dev": {
		"barryvdh/laravel-debugbar": "^3.1",
		"filp/whoops": "^2.0",
		"fzaninotto/faker": "^1.4",
		"mockery/mockery": "^1.0",
		"nunomaduro/collision": "4.1",
		"orangehill/iseed": "^2.6",
		"phpunit/phpunit": "^8.5"
	},

	"repositories": [
		{
			"type": "vcs",
			"url": "https://github.com/jeremykenedy/Generators-1.git"
		}
	],

	"autoload": {
		"files": [
			"app/helper.php"
		],
		"classmap": [
			"database/seeds",
			"database/factories"
		],
		"psr-4": {
			"App\": "app/"
		}
	},
	"autoload-dev": {
		"psr-4": {
			"Tests\": "tests/"
		}
	},
	"extra": {
		"laravel": {
			"dont-discover": [
			]
		}
	},
	"scripts": {
		"post-root-package-install": [
			"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
		],
		"post-create-project-cmd": [
			"@php artisan key:generate"
		],
		"post-autoload-dump": [
			"Illuminate\Foundation\ComposerScripts::postAutoloadDump",
			"@php artisan package:discover"
		],
		"post-update-cmd": [
			"php artisan vendor:publish --provider=\"Proengsoft\JsValidation\JsValidationServiceProvider\" --tag=public --force"
		]
	},
	"config": {
		"preferred-install": "dist",
		"sort-packages": true,
		"optimize-autoloader": true
	},
	"minimum-stability": "dev",
	"prefer-stable": true
}

How to fix it ?

Thanks!

Apr
27
1 month ago
Activity icon

Replied to If Output Of \Log::info Depens On Some Options?

Reading the doc by link I do not see that 'daily' means and to which value have I to change level ? Could, you please, explain?

Activity icon

Started a new Conversation If Output Of \Log::info Depens On Some Options?

Hello,

If output of

 \Log::info('text');

function is dependable on some options ?

in .env I have :

APP_DEBUG=false

and in config/app.php

    'debug' => env('APP_DEBUG', false),

Also in config/logging.php I have options(seems default):

<?php

use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [


    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => 'critical',
        ],

        'papertrail' => [
            'driver' => 'monolog',
            'level' => 'debug',
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
        ],

        'stderr' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

The quesion is that with my options on live server I expected

 \Log::info('text');

would not log lines, but it writes lines anyway.

I read here https://laravel.com/docs/5.7/logging do not see any dependencies.

I mean I need to have log messages only if APP_DEBUG=true. I suppose that must be default ? Laravel 5.7

Thanks!

Apr
24
1 month ago
Activity icon

Started a new Conversation Error In Vue-simple-suggest When Item Is Selected

Hello,

In my vue/cli 4 / Bootstrap 4.3 app I make suggestion component(using vue-simple-suggest) with some additive parameters and returning data I need to get slug field of selected row and to redirect to other page based on this slug. Search works ok for me, but when Item in selection list is selected I see in browsers console one more request to database with whole selected item object and that raise error. I make:

                            <vue-simple-suggest
                                    id="search_string"
                                    v-model="search_string"
                                    display-attribute="name"
                                    value-attribute="slug"
                                    :list="simpleSuggestionList"
                                    autocomplete=off
                                    mode="select"
                                    @select="taskSuggestionSelected()"
                            ></vue-simple-suggest>

and js code:

            simpleSuggestionList() {
                let filters={
                    search_string : this.search_string, // search
                    only_free : ( this.cbx_only_free ? 1 : 0), // additive parameters
                    price_min : this.tasksPriceRange[0],
                    price_max : this.tasksPriceRange[1],
                    selectedCategories : this.getSelectedCategories
                }
                console.log('filters::')
                console.log(filters)
                return axios.post(this.apiUrl + '/tasks-search', filters, this.credentialsConfig)
                    .then(({data}) => {
                        return data.tasks
                    })
                    .catch(error => {
                        console.error(error)
                        this.showPopupMessage('Tasks search', error.response.data.message, 'warn')
                    })

                // return this.retArray
            },


            taskSuggestionSelected() {
                console.log('\'taskSuggestionSelected par1 ::\'+par1 +"  search_string::"+this.search_string::')
                return false
            }
  1. Why error and how not to trigger request to server when item is selected and
  2. how can I save/ pass slug of selected item into taskSuggestionSelected method as I need to make redirection?
    "vue": "^2.6.10",
    "vue-simple-suggest": "^1.10.1",

Thanks!

Apr
22
1 month ago
Activity icon

Started a new Conversation Format For Resources Wrapper For Dates Returned From Settings Table

Hello, In laravel 6 app I make resources wrapper for dates returned from Settings table( pairs of name => value ), but I got returned data in invalid format, not pairs of name => value. I have in controller:

        $settingsArray= [];
        $settingValues              = Settings::getSettingsList();
        foreach( $settingValues as $nextSettingValue ) {
            $settingsArray[$nextSettingValue->name] = $nextSettingValue->value;
        }

        \Log::info('$settingsArray ::');
        \Log::info(print_r(  $settingsArray, true  ));

        return (new SettingsCollection($settingsArray));

Output of logging above is :

[2020-04-21 07:47:07] local.INFO: $settingsArray ::  
[2020-04-21 07:47:07] local.INFO: Array
(
    [site_name] => VTasks
    [copyright_text] => © 2019 - 2020 All rights reserved
    [site_heading] => Task 'em all
    [backend_items_per_page] => 2
    [tasks_per_page] => 4
    [events_per_page] => 5
    [events_demo_month] => 2018-02-01
)

and in app/Http/Controllers/API/Admin/SettingsController.php :

class SettingsCollection extends ResourceCollection
{

    public static $wrap = 'settings';

    public function toArray($request)
    {

          \Log::info('SettingsCollection $request::');
            \Log::info(print_r(  json_encode($request), true  ));

          \Log::info('+++ SettingsCollection $this::');
            \Log::info(print_r(  json_encode($this), true  ));


        return $this->collection->transform(function($settings, $key){
            \Log::info('+++ $settings:');
            \Log::info(print_r(  json_encode($settings), true  ));

            \Log::info('+++ $key:');
            \Log::info(print_r(  json_encode($key), true  ));

            return [
                $key => $settings,
            ];
        });

    }

I see in log output :

[2020-04-21 07:47:07] local.INFO: "tasks_per_page"  
[2020-04-21 07:47:07] local.INFO: +++ $settings:  
[2020-04-21 07:47:07] local.INFO: "5"  
[2020-04-21 07:47:07] local.INFO: +++ $key:  
[2020-04-21 07:47:07] local.INFO: "events_per_page"  
[2020-04-21 07:47:07] local.INFO: +++ $settings:  
[2020-04-21 07:47:07] local.INFO: "2018-02-01"  
[2020-04-21 07:47:07] local.INFO: +++ $key:  
[2020-04-21 07:47:07] local.INFO: "events_demo_month"  
[2020-04-21 07:47:07] local.INFO: {"site_name":{"site_name":"VTasks"},"copyright_text":{"copyright_text":"\u00a9 2019 - 2020 All rights reserved"},"site_heading":{"site_heading":"Task 'em all"},"backend_items_per_page":{"backend_items_per_page":"2"},"tasks_per_page":{"tasks_per_page":"4"},"events_per_page":{"events_per_page":"5"},"events_demo_month":{"events_demo_month":"2018-02-01"}}  

and returned data has wrong structure : https://imgur.com/a/CvIAAQO

Which is the valid way ?

Thanks!

Apr
13
1 month ago
Activity icon

Replied to Updating Profile In Swagger How Set Array Of Data

In app/Http/Controllers/API/PersonalController.php conrtoller of my backend app I added loging in update method:

    public function update(Request $request, $id)
    {
        $loggedUser = Auth::guard('api')->user();

        \Log::info('PersonalController update $this->requestData::');
        \Log::info(print_r(  $this->requestData, true  ));

        $loggedUser->first_name    = !empty($this->requestData['profile']['first_name']) ? $this->requestData['profile']['first_name'] : '';

and when update profile from my client @vue/cli 4.0.5 app I see logging like:

2020-04-13 03:28:10] local.INFO: PersonalController update $this->requestData:: [2020-04-13 03:28:10] local.INFO: Array ( [profile] => Array ( [first_name] => John [last_name] => Glads [phone] => 252-129-0916 [website] => [email protected] ) )

But when I make run update method from swagger I do not see any update logging string like above But I see 200 responce in swagger : https://prnt.sc/ry6con and in request : https://prnt.sc/ry6drl I suppose that I have invalid profile parameter, but I do not see why?

Activity icon

Started a new Conversation Updating Profile In Swagger How Set Array Of Data

Hello, In my @vue/cli 4.0.5 app I save my profile data as array of profile :

     axios.put(this.apiUrl + '/personal/profile/' + this.userProfileRow.id, {
         profile: {
             first_name: this.userProfileRow.first_name,
             last_name: this.userProfileRow.last_name,
             phone: this.userProfileRow.phone,
             website: this.userProfileRow.website
         },
     }, this.credentialsConfig).then((/*response*/) => {

and in console of browser I see PUT request with array

profile: {first_name: "a", last_name: "b", phone: "c", website: "d"}

Now I make description in swagger with api 3 version as :

  /personal/profile/{user_id}:
    put:
      tags:
        - profile
      summary: personal profile update editable fields

      responses:
        '200':
          description: Successful update
        '400':
          description: Invalid profile editable fields updating

      operationId: updateProfileEditableFieldsByBearerToken

      parameters:
        - name: user_id
          in: path
          description: The user_id update editable fields.
          required: true
          schema:
            type: integer
            default: 1
            example: 1

      requestBody:
        description: Editable fields
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              properties:
                profile:
                  type: array
                  items:
                    $ref: '#/components/schemas/ProfileEditableFields'
                  
              required:
                - profile

components:

  schemas:

    ProfileEditableFields:
      properties:
        first_name:
          type: string
        last_name:
          type: string
        phone:
          type: string
        website:
          type: string

But I can not fill ProfileEditableFields, in my console I have : https://prnt.sc/rugv28

  1. I do not know which is valid format for any parameter of ProfileEditableFields ? With fhe fileld data above next curl request was generated :
curl -X PUT "http://myserver.com/api/personal/profile/1" -H "accept: */*" -H "Authorization: Bearer TOKEN" -H "Content-Type: application/x-www-form-urlencoded" -d "profile=first_name%20%3A%20111%0A%2Clast_name%20%3A%20222%0A%2Cphone%3A%20333333%2Cwebsite%3A%204444444"

But with 200 code returned all fields first_name, last_name... were cleared at db, as if empty values were sent(API permits empty fields).

  1. How can I set some default data for any elements of ProfileEditableFields structure ?

Thanks!

Apr
09
1 month ago
Activity icon

Started a new Conversation How To Add Additive Authorization Parameter In Vue-tables-2 Component Request

Implementing in my @vue/cli 4.0.5 app vue-tables-2 component with server-table and looking at this https://matanya.gitbook.io/vue-tables-2/server-table/custom-request-function

I try to set additive Authorization parameter to request like:

    <div id="activity_logs_data_table">
        <v-server-table url="/adminarea/activity-logs-filter" :columns="columns" :options="tableOptions">
            <span slot="edit" slot-scope="{row}">
                <a v-on:click="viewActivityLog(row)" :class="'p-1 a_view_item_'+row.id">
                    <i :class="'i_link '+getHeaderIcon('view')" title="View activity log item"></i>
                </a>
                <a v-on:click="removeActivityLog(row.id, row.log_name)" :class="'p-1 a_delete_item_'+row.id">
                  <i :class="'i_link '+getHeaderIcon('remove')" title="Remove activity log item"></i>
                </a>
            </span>
    
            <span slot="created_at" slot-scope="{row}">
                {{ momentDatetime(row.created_at, jsMomentDatetimeFormat) }}
            </span>
        </v-server-table>
    </div>
    
    
    
    data() {
        return {
            activityLogs: [],
    
            el: "#activity_logs_data_table",
            columns: ['id', 'log_name', 'causer_id', 'causer_type', 'created_at', 'edit'],
    
            tableOptions: {
                requestFunction: (data) => {
                    console.log('requestFunction data::')
                    console.log(data)
    
                    this.is_page_loaded = false
                    this.credentialsConfig.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken;
                    console.log('requestFunction this.credentialsConfig::')
                    console.log(this.credentialsConfig)
    
                    return axios.get(this.url, {
                        params: data
                    }, this.credentialsConfig ).catch(function (error) {
                        console.log('requestFunction error::')
                        console.error(error)
                        // this.dispatch('error', error );
                    });
    
                } // requestFunction: (data) => {

But I see error in console :

    TypeError: Cannot read property 'indexOf' of undefined
        at buildURL (buildURL.js?30b5:62)
        at dispatchXhrRequest (xhr.js?b50d:30)
        at new Promise (<anonymous>)
        at xhrAdapter (xhr.js?b50d:12)
        at dispatchRequest (dispatchRequest.js?5270:52)

and printscreen of console with debugging : https://prnt.sc/rtak15 I see query parameter empty ... Could it be the issue? Are parameters in axios.get invalid ?

    "axios": "^0.19.0",
    "vue": "^2.6.10",
    "vue-tables-2": "^2.0.14" 

Thanks!

Apr
08
1 month ago
Activity icon

Started a new Conversation Search Laravel 6/7 Crud Generator With Blade, Jquery

Hello, Could you please advice some laravel 6/7 crud generator with blade, Jquery free and convinient in work? I found this https://github.com/appzcoder/crud-generator But I am not sure is it good for laravel 6/7 ?

Thank!

Mar
31
2 months ago
Activity icon

Replied to What Can Be Used For Vue/cli Frontend / Laravel 6 Backend REST API Testing

Thanks! Interesting. I started viewing it : looks like it more for laravel with blade. Are there some tutorial for @vue/cli 3 app / Laravel 6 Backend REST API ?

Mar
29
2 months ago
Activity icon

Replied to How To Keep Access_token Parameter From Login For Next Post Requests

Is it possible what I want ? If yes, how ?

Mar
27
2 months ago
Activity icon

Started a new Conversation What Can Be Used For Vue/cli Frontend / Laravel 6 Backend REST API Testing

I have expierence of using laravel dusk for testing laravel 5 app with using of vuejs 2 components Now I make @vue/cli 4.0.5 / vuex 3 app with data reading from Laravel 6 Backend REST API and wonder how both parts of the app can be tested?

Can laravel dusk be used for this or there are some better tools for this ?

Thanks!

Activity icon

Replied to Using WhenLoaded In Resource Collection I Got Error

Thanks for the feedback, Reading the docs I missed difference between "when"and "whenLoaded"?

Also if I want to use $user object in Closure in its second argument, can I do like :

                'user' => $this->when('user', function ($user) {
                    return $user->name;
                }),

?

Mar
26
2 months ago
Activity icon

Started a new Conversation How To Keep Access_token Parameter From Login For Next Post Requests

Hello, In swagger With api 3 version I have login described as :

  /login:
    post:
      tags:
        - user login
      summary: User login

      responses:
        '200':
          description: Successful login
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserLogin'
        '400':
          description: Invalid login

      operationId: postLogin
      requestBody:
        description: Login user fields
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              properties:
                email:
                  type: string
                  default: [email protected]
                password:
                  type: string
                  default: 111111
              required:
                - email
                - password

and if login is successfull amonth returned data I have access_token field.

With schema described as :

components:
  schemas:


    UserLogin:
      properties:
        access_token:
          type: string
        user:
          $ref: '#/components/schemas/UserLogin'
        token_type:
          type: string
        user_avatar_path:
          type: string
        usersGroups:
          type: array
        expires_in:
          type: integer

I need to use this access_token value for next post requests to get access to authorized pages.

How can I do this in swagger. Seems I can not copypaste access_token value from login requeest for my post requests, asthey do not access_token parameter ?

Thanks!

Mar
25
2 months ago
Activity icon

Started a new Conversation Using WhenLoaded In Resource Collection I Got Error

Hello, In laravel 6 app I have a Resource Collection, which works ok for me :

class UserSkillCollection extends ResourceCollection
{
    public static $wrap = 'user_skills';

    public function toArray($request)
    {

        return $this->collection->transform(function($userSkill){
            return [
                'id' => $userSkill->id,
                'user_id' => $userSkill->user_id,
                'user_name' => $userSkill->user_name,
                'skill_id' => $userSkill->skill_id,
                'skill_name' => $userSkill->skill_name,
                'rating' => $userSkill->rating,
                'created_at' => $userSkill->created_at,
            ];
        });

    }

except when some fields are defined, like user_name, I have keys with null values.

To get rid of them I tried to use whenLoaded, but with line :

                'user_id' => $this->whenLoaded('user_id'),

I got error :

"message": "Method Illuminate\Support\Collection::relationLoaded does not exist.",

Which way is valid ?

Thanks!

Mar
11
2 months ago
Activity icon

Started a new Conversation How In Swagger To Make Requests To Auth Protected Backend App

Hello, Making first steps in swagger I created with api 3 version several response to public routes of my laravel 6 backend api app.

Now I wander how can I make requests to part of my backend app which are auth protected like :

Route::group(['middleware' => 'auth:api', 'prefix' => 'personal', 'as' => 'personal.'], function ($router) {
    Route::resource('ad-saved-filters', 'Personal\AdSavedFiltersController');
    ...

Please, link, how can I do it

Thanks!

Feb
28
3 months ago
Activity icon

Replied to How Show Maintenance Page If Appache Of Backend Server Is Not Running?

Sorry, if I did not put my question clearly I know how to catch 503 error. I wonder how can I catch when appach of backend app is not running / backend server is not running

Activity icon

Started a new Conversation How Show Maintenance Page If Appache Of Backend Server Is Not Running?

Hello! In @vue/cli 4.1.1 app I found in cases if appache is not running on backend server I got errors in console, but I do not see any code and I wonder if there is a way to catch it, something like 503 error of maintenance stopped?

Also say if backend server is not running at this time...

Thanks!

Feb
27
3 months ago
Activity icon

Replied to Valid Format Of Ranges For Vue2-daterange-picker

Thanks, that was helpfull. Now I have prior/next month icons at the corners of the calendar. Are there prior/next year icons available ?

Activity icon

Started a new Conversation Valid Format Of Ranges For Vue2-daterange-picker

Using vue2-daterange-picker I search how to hide left selection items, as 'Today','Yesterday', 'This month', 'This year', but I did find valid format. The thing is that now date picker looks like : https://prnt.sc/r8bbjt and I dislike those items which I prerfer to remove.

In the docs I found :

default ranges object (set to false to hide ranges)
{
    'Today',
    'Yesterday',
    'This month',
    'This year',
    'Last week',
    'Last month',
}

making :

                            <date-range-picker
                                    :opens="date_range_picker_locale_opens"
                                    @update="updateValues"
                                    :singleDatePicker="true"
                                    :locale-data="dateRangePickerLocale"
                                    :autoApply="true"
                                    :ranges="defaultRanges"
                                    :show-dropdowns="false"
                                    :alwaysShowCalendars="false"
                                    v-model="ad_expire_date"
                                    class="form-control editable_field"
                            >
                                <div slot="input" slot-scope="picker">
                                    {{ picker.startDate | date }}
                                </div>
                            </date-range-picker>

but it did not help

...
                defaultRanges: {  // I got a eslint syntax errors
                    'Today',
                    'Yesterday',
                    'This month',
                    'This year',
                    'Last week',
                    'Last month',
                },

Which is valid format?

    "vue": "^2.6.11",
    "vue2-daterange-picker": "^0.4.4",

Thanks!

Feb
24
3 months ago
Activity icon

Replied to How In Bootstrap-vue Convert FileReader To Blob And Upload To Server?

I still search for decision. Have anybody such uploading ?

Feb
19
3 months ago
Activity icon

Replied to How In Bootstrap-vue Convert FileReader To Blob And Upload To Server?

Very strange post above/ Sorry, was my question unclear ? I need to convert uploading image to blob...

Activity icon

Started a new Conversation How In Bootstrap-vue Convert FileReader To Blob And Upload To Server?

Hello, In @vue/cli 4.1.1 app I use bootstrap-vue and b-form-file conponent for images uploading

https://bootstrap-vue.js.org/docs/components/form-file/#multiple-files

with definition :

                <b-form-file
                    id="upload_ad_image"
                    v-model="new_upload_ad_image"
                    :state="Boolean(new_upload_ad_image)"
                    placeholder="Choose a file or drop it here..."
                    drop-placeholder="Drop file here..."
                    accept="image/jpeg, image/png, image/gif"
                ></b-form-file>
                
                <div ref="uploaded_img_preview" id="uploaded_img_preview" class="m-2" >Uploaded image preview :</div>

I found snippet https://codepen.io/Tenderfeel/pen/rgqWXR and using it I show selected file on my form for preview. Next I need to upload it on the server. I have an expierence of uploading image as blog using code like :

                fetch(this.taskRow.imageFile.blob).then(function (response) {
                    if (response.ok) {
                        return response.blob().then(function (imageBlob) {
                            let imageUploadData = new FormData()
                            imageUploadData.append('id', self.taskRow.id)
                            imageUploadData.append('image', imageBlob)
                            imageUploadData.append('image_filename', self.taskRow.imageFile.name)

But I need to convert uploading image to blob. I use method when image is selected: But got error :

Error in callback for watcher "new_upload_ad_image": "InvalidStateError: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs               
        watch: {
            new_upload_ad_image(val) {
                if (!val) return;
                if (this.previewImg) {
                    this.previewImg.remove();
                }
                const img = document.createElement("img");
                img.classList.add("obj");
                img.file = this.new_upload_ad_image;
                console.log('img.file::')
                console.log(img.file)

                this.previewImg = img;
                console.log('this.$refs.uploaded_img_preview::')
                console.log(this.$refs.uploaded_img_preview)

                console.log('img::')
                console.log(img)

                this.$refs.uploaded_img_preview.appendChild(img);

                const fileReader = new FileReader();
                fileReader.onload = (e) => {
                    this.previewImg.src = e.target.result;
                };
                fileReader.readAsDataURL(this.new_upload_ad_image);
                console.log('fileReader::')
                console.log(fileReader)

                let blobObj= fileReader.readAsDataURL(img.file) // RAISE ERROR :

                console.log('blobObj::')
                console.log(blobObj)

            }
        },

What I see in the console : https://imgur.com/a/2EZxq9C

How to get blob and upload it on server?

    "bootstrap-vue": "^2.3.0",
    "vue": "^2.6.11",

Thanks!

Feb
15
3 months ago
Activity icon

Replied to Unexpected Response From Swagger

I found a hint that it could be cors related issue. I have installed :

        "barryvdh/laravel-cors": "^0.11.4",
        "laravel/framework": "^6.0",
With params in config/cors.php :
    'supportsCredentials' => true,
    'allowedOrigins' => [env('ALLOWED_ORIGINS')],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

and ref in ALLOWED_ORIGINS to my client vue/cli app. But how to make it permittable for swagger ?

Activity icon

Started a new Conversation Unexpected Response From Swagger

Hello, I make first steps in swagger and creating new app (api 3 version) I try to write requests to my laravel backend api and testing I do not see response I expect. I have definitions:

openapi: 3.0.0
info:
  description: A Simple IP Address API
  title: VTasks
  version: v1
servers:
# Added by API Auto Mocking Plugin
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/petrogromovo/Vtasks/1.0.0
  - description: SwaggerHub API Auto Mocking
    url: http://vtasks.my-demo-apps.tk
#  host: vtasks.my-demo-apps.tk
# schemes:
#  - http
# basePath: /


paths:
  /:
    get:
      summary: Get client IP
      responses:
        '200':
          description: Success response
          
  /public_profile:
    get:
      tags:
        - user
      summary: Get public user info by id
      operationId: public_profile
      parameters:
        - name: user_id
          in: path
          description: The user_id that needs to be fetched. Use 1 for testing.
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: successful operation
        '400':
          description: Invalid username supplied
        '404':
          description: User not found

It shows syntax ok but trying to test how it works I enter user_id parameter, valid value and unvalid value of not existing user with such user_id, like : https://prnt.sc/r2rxgr I expected something like in postman, when I see if some data were found be request. Swagger works differently ?

Thanks!

Feb
05
3 months ago
Activity icon

Replied to Formatted Date For Vue-date-pick Is 1 Day Bigger

Have anybody such a problem ? How did you salve it ?

Feb
04
3 months ago
Activity icon

Replied to Formatted Date For Vue-date-pick Is 1 Day Bigger

I removed moment.tz from my project. In /etc/php/7.2/apache2/php.ini I changed

Timezone ='Europe/Uzhgorod'  // That it near my place I live
date.timezone = "Europe/Uzhgorod" 

So my phpinfo has output :

"Olson" Timezone Database Version   0.system
Timezone Database   internal
Default timezone    Europe/Uzhgorod

I searched how to get a timezone from client browser and found this https://stackoverflow.com/questions/6939685/get-client-time-zone-from-browser branch

and checking :

            var timedifference = new Date().getTimezoneOffset();
            console.log('timedifference::')
            console.log(timedifference)

            var rightNow = new Date();
            var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
            var temp = jan1.toGMTString();
            var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
            var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
            console.log('std_time_offset::')
            console.log(std_time_offset)


            let jstz = require('jstimezonedetect')
            let timezone = jstz.determine()
            console.log('timezone::')
            console.log(timezone)

            console.log('===========================')

I have next output : https://imgur.com/a/84RqqPJ

and again running code when I see date is changed +1 day :

                console.log('__')
                console.log('__')

                console.log('typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)

                if (typeof dateObj === 'string') {
                    dateObj = moment(dateObj, this.date_picker_format)
                }
                console.log('++typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj) // it has ‘2023-01-19’ value


                console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
                console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

                return moment(dateObj).format(this.date_picker_format)

and What I see in console : https://imgur.com/a/Y1aSBez That is strange that .d has 20 day. What is it? Some day zero based option? How can it be salved?

Feb
03
3 months ago
Activity icon

Replied to Formatted Date For Vue-date-pick Is 1 Day Bigger

I reoved moment-timezone but still have same problems Meanwhile I work locally at my local laptop with apache under Kubuntu18 In /etc/php/7.2/cli/php.ini I have

Timezone ='Europe/Kiev'
date.timezone = "UTC" 

and in phpinfo output I see :

"Olson" Timezone Database Version   0.system
Timezone Database   internal
Default timezone    UTC

Can that be the issue? Also How can I check timezone params of vuejs app?

Feb
02
3 months ago
Activity icon

Started a new Conversation Formatted Date For Vue-date-pick Is 1 Day Bigger

Hello, In my vue/cli 4/vuex / bootstrap-vue project app I install date picker with custom format, like here https://dbrekalo.github.io/vue-date-pick/examples.html#custom-date-parser

I use moment/moment-timezone in my project, so I do not want to use fecha as in example I have to convert date value from mysql to datepicker format and I have a problem that my converted date for datepicker is 1 day bigger...

I have in my component:

                        <date-pick
                                v-model="editableAd.expire_date_formatted"
                                :format="date_picker_format"
                                :parseDate="parseDate"
                                :formatDate="formatDate"
                                :inputAttributes="{size: 32}"
                        ></date-pick>

...
    import moment from 'moment-timezone'

    console.log('settingsTimeZone::')
    console.log(settingsTimeZone) // it shows Europe/Kiev

    moment.tz.setDefault(settingsTimeZone)

...
    date_picker_format: 'Do MMMM, YYYY',

...
    // setting formated date for dapicker
    this.editableAd.expire_date_formatted = this.formatDate(this.editableAd.expire_date, this.date_picker_format)
...

            formatDate(dateObj) {

                console.log('typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)  // it has ‘2023-01-19’ value

                if (typeof dateObj === 'string') {
                    dateObj = moment(dateObj, this.date_picker_format)
                }
                console.log('++typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)

                console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
                console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

                return moment(dateObj).format(this.date_picker_format) // returns invalid ‘20th January, 2023’ value 

which I see in datepicker

What I see in console for dateObj var : https://imgur.com/a/KZLtXiL

"bootstrap-vue": "^2.1.0",
  "font-awesome": "^4.7.0",
  "moment": "^2.24.0",
  "moment-timezone": "^0.5.27",
  "vue": "^2.6.10",
  "vue-date-pick": "^1.2.1",

Why error and how it can be fixed?

Thanks!

Jan
27
4 months ago
Activity icon

Replied to Can I Make With Spatie/laravel-permission Limit Access In Constructor For All Actions?

Thank you for hint! I remade it with nested groups:

Route::group(['middleware' => 'auth:api', 'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {

    Route::get('dashboard', 'API\Admin\[email protected]');

    Route::group(['middleware' => ['permission:' . PERMISSION_APP_ADMIN]], function () {
        Route::post('users-filter', 'Admin\[email protected]');
        Route::resource('users', 'Admin\UserController');
        Route::group(['prefix' => 'users'], function ($router) {
            Route::resource('/{user_id}/model_has_permissions', 'API\Admin\ModelHasPermissionsController');
        });
    });

It looks complicated, but works for me : PERMISSION_APP_ADMIN - defined const which I used for permission creation.

Jan
26
4 months ago
Activity icon

Started a new Conversation Can I Make With Spatie/laravel-permission Limit Access In Constructor For All Actions?

Hello, In Laravel 6 I use spatie/laravel-permission and it works if I make checks in control's action like :

        $loggedUser      = Auth::guard('api')->user();
        if ( !$loggedUser->can(PERMISSION_APP_ADMIN) ) {
            return response()->json(['error' => 'Unauthorized'], \App\MyApp::HTTP_RESPONSE_NOT_UNAUTHORIZED);
        }

But as all control's actions have the same rules I tried to move this code under constructor, like:

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;


class UserController extends Controller
{
    private $requestData;

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => []]);
        $request           = request();
        if ( !$loggedUser->can(PERMISSION_APP_ADMIN) ) {
            return response()->json(['error' => 'Unauthorized'], HTTP_RESPONSE_NOT_UNAUTHORIZED);
        }
    }

But Unauthorized error is not triggered and page is accessible. Which is right way ?

     "php": "^7.2",
       "laravel/framework": "^6.2",
       "laravel/passport": "^8.1",
       "spatie/laravel-permission": "^3.5",

Thanks!

Activity icon

Replied to How To Increase Session Vue/cli 4.0.5 / Vuex 3 / Laravel 6 Backend REST API App?

I want to clarify what I want: I use some banks accounts with personal area. If I inactive with 15-20 minutes I lose my session and have to login again. That is what I want.

Some more details: I have in backend app:

        "php": "^7.2",
        "barryvdh/laravel-cors": "^0.11.4",
        "laravel/framework": "^6.2",
        "laravel/passport": "^8.1",

And on Vue/Cli part :

    "store": "^2.0.12",
    "vue": "^2.6.10",
    "vue-js-modal": "^1.3.31",
    "vue-resource": "^1.5.1",
    "vue-router": "^3.1.3",
    "vuex": "^3.1.2"

Actualy I want in backend app in config/app.php to set some parameter like

    'personal_access_tokens_expire_in_hours' => 24, // Actually I think about value = 1

and to user it in 2 places : in app/Providers/AuthServiceProvider.php :

    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
        $personal_access_tokens_expire_in_hours   = config('app.personal_access_tokens_expire_in_hours',24);
        Passport::personalAccessTokensExpireIn(Carbon::now()->addHours($personal_access_tokens_expire_in_hours));
    }

and in app/Http/Controllers/AuthController.php :

    public function login(Request $request)
    {
        $credentials = request(['email', 'password']);
        $request->validate([
            'email'       => 'required|string|email',
            'password'    => 'required|string',
            'remember_me' => 'boolean'
        ]);

        if ( ! Auth::attempt($credentials)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        $user = $request->user();
        $user->last_logged= Carbon::now(config('app.timezone'));
        $user->save();
        $tokenResult = $user->createToken('Access Token');
        $token       = $tokenResult->token;

        if ($request->remember_me) {
            $personal_access_tokens_expire_in_hours   = config('app.personal_access_tokens_expire_in_hours',24);
            $token->expires_at = Carbon::now()->addHours($personal_access_tokens_expire_in_hours);
        } // Though Ronak Dhoot wrote that $token->expires_at does not infleunce anything.

I added last_logged field to users and fill it on any login.

With default personalAccessTokensExpireIn value in 1 day I login in the system in the middle of my working day. I turn off computer in the end of the day and opening it next morning I can enter my app with login I made yesterday(24 hours has not passed yet). That seems not safe for me.

I would prefer personalAccessTokensExpireIn = 1 hour and refresh it ANY authorized request from my vue/cli app. In which way that could be done? Working on vue/cli apps with baxkend api which way do you use?

I have some prior work with auth/jwt and in app/Http/Controllers/API/AuthController.php I found methods :

    public function refresh() // THIS METHOD IS NOT CALLED ANYWHERE
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    protected function respondWithToken($token)
    {
        $loggedUser= $this->guard()->user();

        $user_avatar_path= User::getUserAvatarPath($loggedUser->id, $loggedUser->avatar);
        $filenameData                     = User::setUserAvatarProps($loggedUser->id, $loggedUser->avatar, true);

        $usersGroups=  User::getUsersGroupsByUserId($loggedUser->id, false);
        return response()->json([
            'access_token' => $token,
            'user'         => $loggedUser,
            'token_type'   => 'bearer',
            'user_avatar_path'   => $user_avatar_path,
            'filenameData' => $filenameData,
            'usersGroups'  => $usersGroups,
            'expires_in'   => $this->guard('api')->factory()->getTTL() * 9360 // TOFIX
        ]);
    }

Can refresh() be used in my passport issue somehow?

Jan
22
4 months ago
Activity icon

Replied to How To Increase Session Vue/cli 4.0.5 / Vuex 3 / Laravel 6 Backend REST API App?

Have anybody encountered such issue? How it can be salved ?

Jan
21
4 months ago
Activity icon

Started a new Conversation How To Increase Session Vue/cli 4.0.5 / Vuex 3 / Laravel 6 Backend REST API App?

Hello, I make @vue/cli 4.0.5 / vuex 3 app with data reading from Laravel 6 Backend REST API app with passport as auth and I want to set bigger time of logged session during development and for this in my app/Http/Controllers/AuthController.php I changed time and session

    protected function respondWithToken($token)
    {
        $loggedUser = $this->guard()->user();

        $user_avatar_path = User::getUserAvatarPath($loggedUser->id, $loggedUser->avatar);
        $filenameData     = User::setUserAvatarProps($loggedUser->id, $loggedUser->avatar, true);

        return response()->json([
            'access_token'     => $token,
            'user'             => $loggedUser,
            'token_type'       => 'bearer',
            'user_avatar_path' => $user_avatar_path,
            'filenameData'     => $filenameData,
            'expires_in'       => $this->guard('api')->factory()->getTTL() * 660
        ]);
    }

But seems this chages does not influence my app. Did I miss some options? Also as I can see parameter expires_in starts its time from login time and that seems to me not what I want, as I want this parameter works as time from last work in the app. In other way any request to backend part I have to refresh this this parameter...

Thanks!

Jan
09
4 months ago
Activity icon

Replied to Runing Vue/cli App Under Docker Simple Index.html Is Opened

Who has installed vue/cli app under docker please share your expierence...

Jan
05
4 months ago
Activity icon

Replied to Register/login Flow With Passport In REST API

@prasadchinwal5, I have already run

php artisan passport:install

command creating 2 rows in oauth_clients table. And that is really what confuse me. I suppose that for any registered user in users table must be relative row in oauth_clients table related by user_id field. is it so ?

I looked several step by step manualls on youtube with passpord oauth2 authorization and in any command

php artisan passport:install

was run in console and token retrieved in Postman. That is ok for demo, but if many users would be resitered at site? I suppose any of them has 1 row in users table and relative row in oauth_clients table related by user_id field with unique secret key. is it so ?

Jan
04
4 months ago
Activity icon

Started a new Conversation Register/login Flow With Passport In REST API

Hello, I make @vue/cli/axios 4.0.5 app with data reading from Laravel 6 Backend REST API with passport auth driver. I want to clarify register/login flow, as except this I will need also to use passport client toaken for oauth2 connection.

When in register method I create new user, like :

            DB::beginTransaction();

            $requestData= $request->all();
            $newUser = new User();
            $newUser->name= $requestData['name'];
            $newUser->password= Hash::make($requestData['password']);
            $newUser->status= 'A';
            $newUser->email= $requestData['email'];
            $newUser->save();

Have I also to create oauth_clients row with user_id created at rows above? like:

const data = {
    name: 'Client Name',
    ‘user_id’ : $newUser.id, // CONNECT USER USER CREATED ABOVE
    redirect: 'http://example.com/callback'
};

axios.post('/oauth/clients', data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // List errors on response...
    });

As I do not create new client in command line

For login I have to use this docs https://laravel.com/docs/6.x/passport#requesting-password-grant-tokens :

Requesting Tokens
Once you have created a password grant client, you may request an access token by issuing a POST request to the /oauth/token route with the user's email address and password. Remember, this route is already registered by the Passport::routes method so there is no need to define it manually. If the request is successful, you will receive an access_token and refresh_token in the JSON response from the server:

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'username' => '[email protected]',
        'password' => 'my-password',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

That is clear with username and password parameters, but what are client_id, client_secret parameters? have I before running

$response = $http->post('http://your-app.com/oauth/token'

to get oauth_clients(I need to create model for this table ) rows by user_id ?

"laravel/framework": "^6.2",
"laravel/passport": "^8.1",

Thanks!

Dec
30
5 months ago
Activity icon

Replied to Runing Vue/cli App Under Docker Simple Index.html Is Opened

I returned to 1st way with https://github.com/ebiven/docker-vue-cli and looking at demo at https://github.com/ebiven/docker-vue-cli I see that ebiven/docker-vue-cli is used as web container, so removing node_modules directory and I remade my _Docker/docker-compose.yml :

version: '3.5'

services:

    web:
        container_name: vtasks_web

        image: ebiven/vue-cli

        command: npm install
#        command: npm install ; npm run serve  // I GOT ERROR HERE
#        command: npm run serve

        build:
            context: ./web
            dockerfile: Dockerfile.yml

        environment:
            - APACHE_RUN_USER=www-data

        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        ports:
            - "8088:80"

        working_dir: ${APP_PTH_CONTAINER}


    db:
        container_name: vtasks_db
        image: mysql:5.7.28
        restart: always
        environment:
            - MYSQL_DATABASE=DockerVTasks
            - MYSQL_USER=docker_user
            - MYSQL_PASSWORD=4321
            - MYSQL_ALLOW_EMPTY_PASSWORD=false
            - MYSQL_ROOT_PASSWORD=321
            - TZ=Europe/Kiev

        volumes:
            - ${DB_PATH_HOST}:/var/lib/mysql


    adminer:
      container_name: vtasks_adminer
      image: adminer
      restart: always
      ports:
        - 8089:8080
      links:
        - db

as result I see :

$ docker-compose up -d --build     
Building web
Step 1/6 : FROM php:7.3-apache
 ---> 5af347316d4b
Step 2/6 : RUN apt-get update &&     apt-get install -y     python     libfreetype6-dev     libwebp-dev     libjpeg62-turbo-dev     libpng-dev     libzip-dev     nano     mc     git-core     curl     build-essential     openssl     libssl-dev     libgmp-dev     libldap2-dev     netcat     locate     && git clone https://github.com/nodejs/node.git     && cd node     && git checkout v12.0.0     && ./configure      && make      && make install
 ---> Using cache
 ---> b56b2543f6bd
Step 3/6 : RUN npm install cross-env
 ---> Using cache
 ---> f8abda742c47
Step 4/6 : RUN  docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-webp-dir=/usr/include/  --with-jpeg-dir=/usr/include/
 ---> Using cache
 ---> df0636ba5b86
Step 5/6 : RUN  docker-php-ext-install gd pdo pdo_mysql zip gmp bcmath pcntl ldap sysvmsg exif && a2enmod rewrite
 ---> Using cache
 ---> 307c9f243f02
Step 6/6 : COPY virtualhost.conf /etc/apache2/sites-enabled/000-default.conf
 ---> Using cache
 ---> 3c733883faaa

Successfully built 3c733883faaa
Successfully tagged ebiven/vue-cli:latest
Recreating vtasks_web ... 
vtasks_db is up-to-date
Recreating vtasks_web
Recreating vtasks_web ... done
[email protected]:/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/_Docker$ docker logs --tail=40  vtasks_web

> [email protected] install /var/www/vtasks_docker_root/node_modules/node-sass
> node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.13.0/linux-x64-72_binding.node
Download complete
Binary saved to /var/www/vtasks_docker_root/node_modules/node-sass/vendor/linux-x64-72/binding.node
Caching binary to /root/.npm/node-sass/4.13.0/linux-x64-72_binding.node

> [email protected] postinstall /var/www/vtasks_docker_root/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)


> [email protected] postinstall /var/www/vtasks_docker_root/node_modules/ejs
> node ./postinstall.js

Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/)


> [email protected] postinstall /var/www/vtasks_docker_root/node_modules/node-sass
> node scripts/build.js

Binary found at /var/www/vtasks_docker_root/node_modules/node-sass/vendor/linux-x64-72/binding.node
Testing binary
Binary is fine
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1239 packages from 876 contributors and audited 19413 packages in 26.747s
found 0 vulnerabilities

I see node_modules directory is generated, but also I need to run

npm run serve

after

npm install

But which syntax have I to use?

Dec
28
5 months ago
Activity icon

Replied to Runing Vue/cli App Under Docker Simple Index.html Is Opened

Thank you for the provided link . I modified the command line : modified node source from 11-alpine and renamed project name and installed the project, but running command

yarn serve

I got error that serve was not found :

[email protected]:/mnt/_work_sdb8/wwwroot/lar/VApps/DOCKER_TEST$ mkdir vtaskproject && cd "$_" && docker run --rm -v "${PWD}:/$(basename `pwd`)" -w "/$(basename `pwd`)" -it node:11-alpine sh -c "yarn global add @vue/cli && vue create ."
Unable to find image 'node:11-alpine' locally
11-alpine: Pulling from library/node

e7c96db7181b: Already exists 
0119aca44649: Pull complete 
40df19605a18: Pull complete 
82194b8b4a64: Pull complete 
Digest: sha256:8bb56bab197299c8ff820f1a55462890caf08f57ffe3b91f5fa6945a4d505932
Status: Downloaded newer image for node:11-alpine

yarn global v1.15.2
[1/4] Resolving packages...
warning @vue/cli > @vue/cli-ui > vue-cli-plugin-apollo > apollo > git-parse > babel-polyfill > [email protected]: [email protected]<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of [email protected]
warning @vue/cli > @vue/cli-ui > vue-cli-plugin-apollo > apollo > git-parse > babel-polyfill > babel-runtime > [email protected]: [email protected]<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of [email protected]
[2/4] Fetching packages...
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
warning Your current version of Yarn is out of date. The latest version is "1.21.1", while you're on "1.15.2".
info To upgrade, run the following command:
$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
success Installed "@vue/[email protected]" with binaries:
      - vue
Done in 32.17s.
?  Your connection to the default yarn registry seems to be slow.
   Use https://registry.npm.taobao.org for faster installation? Yes


Vue CLI v4.1.1
? Generate project in current directory? Yes


Vue CLI v4.1.1
? Please pick a preset: default (babel, eslint)
? Pick the package manager to use when installing dependencies: Yarn


Vue CLI v4.1.1
���  Creating project in /vtaskproject.
���  Installing CLI plugins. This might take a while...

yarn install v1.15.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.


success Saved lockfile.
Done in 77.43s.
����  Invoking generators...
����  Installing additional dependencies...

yarn install v1.15.2
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Saved lockfile.
Done in 24.82s.
���  Running completion hooks...

����  Generating README.md...

����  Successfully created project vtaskproject.
����  Get started with the following commands:

 $ yarn serve

[email protected]:/mnt/_work_sdb8/wwwroot/lar/VApps/DOCKER_TEST/vtaskproject$ yarn serve
00h00m00s 0/0: : ERROR: [Errno 2] No such file or directory: 'serve'
[email protected]:/mnt/_work_sdb8/wwwroot/lar/VApps/DOCKER_TEST/vtaskproject$ yarn --version
0.32

I see that on successfull installation newly created project dir was selected.

Also in the provided article next was :

Dockerfile
The Dockerfile is identical to the given example in the documentation. Only the build-stage is split up into an install-stage and a build-stage, since we don’t need to build when we are developing!
$ lsb_release -d; uname -r; uname -i
Description:    Ubuntu 18.04.3 LTS
4.15.0-72-generic
x86_64
$ docker --version 
Docker version 19.03.5, build 633a0ea838

But the thin is I do not see any Dockerfile file in the created project : https://imgur.com/a/mKrdFgi as I expected. Had Dockerfile be there and how move next ?

Dec
26
5 months ago
Activity icon

Started a new Conversation Runing Vue/cli App Under Docker Simple Index.html Is Opened

Hello, I want to install my @vue/cli 4.0.5 app under docker and I found this package https://hub.docker.com/r/ebiven/vue-cli Supposing that is what I need (?) I modified _Docker/docker-compose.yml with

    web:
        container_name: vtasks_web

        build:
            context: ./web
            dockerfile: Dockerfile.yml

        environment:
            - APACHE_RUN_USER=www-data
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        ports:
            - 8088:80
        working_dir: ${APP_PTH_CONTAINER}

    ...
    
    vue_cli:
        container_name: vtasks_vue_cli
        image: ebiven/vue-cli:latest
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: npm install

Building the app and next checking logs I do not have errors, also node_modules was created(I removed it priorly):

But entering the bush I run

npm run serve

command and it shows :

ONE  Compiled successfully in 10065ms                                                                                                                                                                                            4:21:52 PM


  App running at:
  - Local:   http://localhost:8080/ 

  It seems you are running Vue CLI inside a container.
  Access the dev server via http://localhost:<your container's external mapped port>/

  Note that the development build is not optimized.
  To create a production build, run npm run build.

So I run

http://localhost:8088/

as in container of web I have 8088:80 set But in browser I see that index.html is opened(by title and page content) but not js rendered?

What is valid way ?

Thanks!

Activity icon

Replied to How To Replace Data In Middleware On Data Submitting

Is it inside of model? You do not use any middleware ?

Dec
25
5 months ago
Activity icon

Replied to How To Replace Data In Middleware On Data Submitting

Who replaced submitted data in middleware, please give a hint which method did you use ?

Dec
24
5 months ago
Activity icon

Replied to How To Replace Data In Middleware On Data Submitting

Reading the article I suppose I have to use cleanData of my middleware, so O commented method I used before and added method :

    private function cleanData(array $data)
    {
        \Log::info('$data:: ::');
        \Log::info($data);
        return collect($data)->map(function ($value, $key) {
            \Log::info('$value:: ::');
            \Log::info($value);
            $value= 'Some text ';
               return $value;
        })->all();
    }

Just to check and replace any value

BuT i got error in log file:

[2019-12-24 12:40:48] local.ERROR: Function name must be a string {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Function name must be a string at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:164)
[stacktrace]
#0 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#1 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/tymon/jwt-auth/src/Http/Middleware/Authenticate.php(32): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#2 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(163): Tymon\JWTAuth\Http\Middleware\Authenticate->handle(Object(Illuminate\Http\Request), Object(Closure))
#3 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#4 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#5 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(163): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#6 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#7 /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(58): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
...

and no message I wrote in \Log::info... Which way is right ?

Activity icon

Started a new Conversation How To Replace Data In Middleware On Data Submitting

Hello, In Laravel 5.8 app submitting form with the data I need to clear data, like doubled spaces, so I created middleware with clearing code :

app/Http/Middleware/WorkTextString.php :
<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\Traits\funcsTrait;
use function PHPSTORM_META\type;

class WorkTextString
{

    use funcsTrait;
    public function handle($request, Closure $next, $strip_tags_excluding= false )
    {
        $inputDataArray = $request->all();

        \Log::info($request->all());


        $stripTagsExcludingArray= $this->pregSplit('/ /',$strip_tags_excluding);
        foreach( $inputDataArray as $next_field_name=>$next_field_value ) {
            if ( !empty($next_field_value) and is_string($next_field_value) ) {
                $skip_strip_tags= in_array($next_field_name,$stripTagsExcludingArray);
                $inputDataArray[$next_field_name] = $this->workTextString($next_field_value, $skip_strip_tags);
            }
        }

        \Log::info('$inputDataArray:: ::');  // I CHECK AND SEE CLEARED DATA!
        \Log::info($inputDataArray);

        $request->replace($inputDataArray); // THAT DOWS NOT WORK ?

        // $request->merge($inputDataArray); // ALSO I TRIED THIS WAY - does not work

        return $next($request);
    }

}

But I see that submitted data are not cleared. Lokks like $request->replace does not work for me...

in routes/api.php :

Route::resource('skills', 'API\Admin\SkillController')->middleware('WorkTextString'); 

How correctly ?

Dec
22
5 months ago
Activity icon

Replied to How Make Route::resource With Page And Filter Options?

After some search I found a decision in defining in routes one more post route:

Route::group(['middleware' => 'jwt.auth',  'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
    Route::post('skills-filter', 'API\Admin\[email protected]');
    Route::resource('skills', 'API\Admin\SkillController');
    ...

and in app/Http/Controllers/API/Admin/SkillController.php :

<?php

namespace App\Http\Controllers\API\Admin;

use Auth;
use DB;
use Validator;
use App\User;

use App\Http\Resources\Admin\Skill as SkillResource;


class SkillController extends Controller
{
    private $requestData;
    private $page;
    private $filter_name;
    private $order_by;
    private $order_direction;


    public function __construct()
    {
        $this->middleware('jwt.auth', ['except' => []]);
        $request           = request();
        $this->requestData = $request->all();
    }

    public function filter()
    {
        if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        $backend_items_per_page = Settings::getValue('backend_items_per_page');

        $this->page            = !empty($this->requestData['page']) ? $this->requestData['page'] : '';
        $this->filter_name     = !empty($this->requestData['filter_name']) ? $this->requestData['filter_name'] : '';
        $this->order_by        = !empty($this->requestData['order_by']) ? $this->requestData['order_by'] : 'name';
        $this->order_direction = !empty($this->requestData['order_direction']) ? $this->requestData['order_direction'] : 'asc';
        $this->index();
        $skills = Skill
            ::getByName($this->filter_name)
            ->orderBy($this->order_by, $this->order_direction)
            ->paginate($backend_items_per_page);

        return SkillResource::collection($skills);
    } // public function filter()


    public function index()
    {
        if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $backend_items_per_page = Settings::getValue('backend_items_per_page');
        $skills = Skill::paginate($backend_items_per_page);
        return SkillResource::collection($skills);
    }

As that is adminarea some filter actions can have more 1 filter...

Just interested to know which other decisions are possible here?

Dec
21
5 months ago
Activity icon

Replied to How Make Route::resource With Page And Filter Options?

Yes, they extra are parameters ... In which way can I do it ?

Dec
20
5 months ago
Activity icon

Started a new Conversation How Make Route::resource With Page And Filter Options?

Hello, In Laravel 5.8 making backend rest api app with resource defined in routes/api.php, as

Route::group(['middleware' => 'jwt.auth',  'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
    ...
    Route::resource('skills', 'API\Admin\SkillController');

now on clients part for listing of skills I need to add current_page and filter_name. Can it be done with Route::resource definitopn ?