PetroGromovo

PetroGromovo

Member Since 1 Year Ago

Experience Points
4,210
Total
Experience

790 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,210 XP
Mar
27
1 day 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 days 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
3 days 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 weeks 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
2 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
2 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
2 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
2 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
2 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
2 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
2 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
2 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]6.1 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
3 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
3 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
3 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
3 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
3 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
3 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
3 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 ?

Dec
19
3 months ago
Activity icon

Started a new Conversation 401 Error Accessing Admin's Controller Under /admin/ Directory

Hello, In Laravel 5.8 app using tymon/jwt-auth 1.0.0 I make backend rest api and I want to move all admin's controls directory, so I created Controller with command

php artisan make:controller API/Admin/SkillController --resource

which has :

<?php

namespace App\Http\Controllers\API\Admin;

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

use App\library\CheckValueType;
use App\Settings;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Skill;
use App\Http\Resources\Admin\Skill as SkillResource;
use App\Http\Traits\funcsTrait;


class SkillController extends Controller
{
    use funcsTrait;

    private $requestData;


    public function __construct()
    {
        $this->middleware('jwt.auth', ['except' => []]);
        $request           = request();
        $this->requestData = $request->all();
    }
    ...
In routes/api.php :
Route::group(['middleware' => 'jwt.auth',  'prefix' => 'admin', 'as' => 'admin.'], function ($router) {
    Route::get('skills', 'API\Admin\[email protected]');
    ...
    
}); // Route::group(['middleware' => 'jwt.auth',  'prefix' => 'admin', 'as' => 'admin.'], function ($router) {


Route::group(['middleware' => 'jwt.auth',  'prefix' => 'manager', 'as' => 'manager.'], function ($router) {
    Route::get('users_assigned_to_task/{task_id}', 'API\[email protected]_assigned_to_task');
    ...    

Also I have very similar app/Http/Controllers/API/ManagerController.php file( with routes defined above ) :

<?php

namespace App\Http\Controllers\API;

use Auth;
use DB;
use Validator;

use App\ActivityLog;
//use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Task;
use App\UserSkill;
use App\UsersGroups;
use App\Event;
use App\EventUser;
use App\TaskAssignedToUser;
use App\Http\Traits\funcsTrait;

class ManagerController extends Controller
{
    use funcsTrait;
    private $requestData;
, 
    public function __construct()
    {
        $this->middleware('jwt.auth', ['except' => []]);
        $request           = request();
        $this->requestData = $request->all();
    }
    ...

which works ok for me.

The only difference is that SkillController is under /admin/ subdirectory, but I set it with namespace...

But seting all parameters in axios GET request I see 401 error : https://imgur.com/a/xFgRK17 What is wrong ?

Thanks!

Dec
16
3 months ago
Activity icon

Replied to Additive Checks With Jwt-auth In Users_groups Table

Have anybody make such additive checks? No ideas ?

Dec
15
3 months ago
Activity icon

Started a new Conversation Additive Checks With Jwt-auth In Users_groups Table

Hello, In Laravel 5.8 app using tymon/jwt-auth 1.0.0 I have users_groups table and I need for logged user for some controller to make check if inside of some group. For this in routes/api.php I have :

Route::group(['middleware' => 'jwt.auth',  'prefix' => 'manager', 'as' => 'manager.'], function ($router) {
    Route::get('users_of_event_selection/{event_id}', 'API\[email protected]_of_event_selection');
    Route::post('add_user_to_event', 'API\[email protected]_user_to_event');
...

I app/Http/Controllers/API/ManagerController.php I added checks:

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

        $loggedUser= Auth::guard('api')->user();
        $userGroupsCount = UsersGroups
            ::getByUserId($loggedUser->id)
            ->getByGroupId([ACCESS_ROLE_ADMIN,ACCESS_ROLE_MANAGER])
            ->count();
        if($userGroupsCount == 0) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

    }

But if

$userGroupsCount == 0 

the code above does not work as I expected and my control's method returns valid data. I suppose I can make small function and to call it in top on any control's method, but if that ig good way? If jwt-auth has any way to extend additive checks ?

Thanks!

Dec
14
3 months ago
Activity icon

Replied to How To Export Lines Db Table To Csv File With Phpspreadsheet

I found how to write to csv file, next I need to write csv file and download in browsers download function using method :

\Response::download(

I try to upload it to tmp directory and checking value I see

        $sys_get_temp_dir= sys_get_temp_dir();

line above has /tmp value

Next I save it as :

        $dest_csv_file= $sys_get_temp_dir . '/box_rooms_'.time().'.csv';
        $header = ["Id",... ];

        $fp = fopen($dest_csv_file, "w");

        fputcsv($fp, $header);

        foreach ($storageSpacesCollection as $line) {
            fputcsv($fp, $line);
        }

        fclose($fp);

But searching on my local ubuntu 18(on server I also have ubuntu) I found generated file as

/tmp/systemd-private-6a9ea6844b9c4c94883d23e4fb3e2215-apache2.service-shqCeo/tmp/box_rooms_1576324869.csv

That was very strange, as I do not know how read it from tmp path. Can it be done?

Activity icon

Replied to How To Export Lines Db Table To Csv File With Phpspreadsheet

Thanks! Looks like fputcsv works good. Could you please also give a hint how to download the generated csv file in browser (saving it in temp dir I suppose ) ?

Dec
13
3 months ago
Activity icon

Started a new Conversation How To Export Lines Db Table To Csv File With Phpspreadsheet

In laravel 5.7 with "phpoffice/phpspreadsheet": "^1.6" app I need to export lines db table to csv file, like :


$dataLines= [ 
    ['field1'=>'000000000', 'field2'=>1111111111111],
    ['field1'=>'11000000000', 'field2'=>221111111111111],
    ['field1'=>'31000000000', 'field2'=>321111111111111],
];


$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);

$writer->save('/path/12345.csv');

But with code above I have empty file and I did find not way to write content of $dataLines array. Also as I need to write 1 row as fields name and next rows from db, have I to prepare 1st row with fields name and rest rows (only values without fields name) manually ? Are there some mothods to make it automatically ?

Dec
03
3 months ago
Activity icon

Started a new Conversation Strange Output Of Laravel Version

Hello, I created a new laravel app a bit more month ago. But just checked it's version and was very surprised, as i see

$ php artisan --version
Laravel Framework 6.6.0

In composer.json I found laravel/framework": "^6.2 :

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2",
        "barryvdh/laravel-cors": "^0.11.4",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "^6.2",
        "laravel/passport": "^8.0",
        "laravel/tinker": "^1.0",
        "spatie/laravel-activitylog": "^3.9",
        "wboyz/laravel-enum": "^0.2.1"
    },
    "require-dev": {
        "facade/ignition": "^1.4",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^8.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

But Here : https://laravel-news.com/laravel-release-process I see only 6.0 (LTS) mentioned. What raised this version in command output? Can it be issue in some cases, as many packages are related to some version of Laravel Framework ?

Thanks!

Nov
25
4 months ago
Activity icon

Replied to How From Vue/cli App Get Access To Laravel's Auth Routes?

Do you mean tymon/jwt-auth ? Must it be installed in Larasel Backend App? Could you please provide some example / link how it can be implemented ?

Activity icon

Started a new Conversation How From Vue/cli App Get Access To Laravel's Auth Routes?

Hello, I make @vue/cli 4.0.5 / vuex 3 app with data reading from Laravel 6 Backend REST API and for this in routes of the last I wrote :

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

Route::post('login', 'API\[email protected]');
Route::post('register', 'API\[email protected]');

Route::get('tasks_paged/{page}', 'TasksController');
Route::resource('tasks', 'TasksController', ['except' => []]);

Route::group(['middleware' => 'auth:api',  'prefix' => 'personal', 'as' => 'personal.'], function ($router) {
    Route::get('task_assigned_to_users/{user_id}', 'API\[email protected]_assigned_to_users');
    Route::post('task_assigned_to_user_store', 'API\[email protected]_assigned_to_user_store');
}); 

Route::get('get_task_by_slug/{task_slug}', '[email protected]_task_by_slug');

In the client app I made register/login pages for routes above and saved user's token in vuex store. I read data from tasks_paged and get_task_by_slug as they are always accessible.

But reading data which are inside personal rules with url

http://local-ctasks-api.com/api/personal/task_assigned_to_users/1
I got error 401 Unauthorized.

Which steps have I to take access to personal rules with checking logged user and his token?

Thanks!

Nov
01
4 months ago
Activity icon

Started a new Conversation In Docker Composer Container Raise Error : Carbon 1 Is Deprecated

Hello, I tried to run under docker my laravel 5.5 / postgres 9 app and in composer container I got error :

Carbon 1 is deprecated, see how to migrate to Carbon 2.
https://carbon.nesbot.com/docs/#api-carbon-2
    You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.

My composer.json:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "barryvdh/laravel-debugbar": "^2.3",
        "graham-campbell/markdown": "^8.0",
        "intervention/image": "^2.3",
        "khill/lavacharts": "3.0.*",
        "laravel/framework": "5.5.*",
        "laravel/socialite": "^3.0",
        "laravel/tinker": "~1.0",
        "laravelcollective/html": "^5.4.0",
        "nwidart/laravel-modules": "^2.2",
        "doctrine/dbal": "~2.5",
        "wboyz/laravel-enum": "^0.2.1"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0",
        "stolz/laravel-html-tidy": "^0.1.1",
        "xethron/migrations-generator": "^2.0",
        "filp/whoops" : "~2.0" 
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\": "app/",
            "Modules\": "Modules/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\Foundation\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\Foundation\ComposerScripts::postUpdate",
            "php artisan optimize"
        ],

        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]

    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

docker-compose.yml :

version: '3'

services:

    web:
        build:
            context: ./web           # directory of web/Dockerfile.yml
            dockerfile: Dockerfile.yml
        
        environment:
            - APACHE_RUN_USER=#1000

        container_name: lprods_web

        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        ports:
            - 8086:80
        working_dir: ${APP_PTH_CONTAINER}
        
        

    db:
        image: postgres:9.6.10-alpine
        container_name: lprods_db
        ports:
            - '5433:5432'
        restart: always
        environment: 
            POSTGRES_USER: 'postgres'
            POSTGRES_PASSWORD: '1'
            POSTGRES_DB: 'wprods'
        volumes:
            - ./init:/docker-entrypoint-initdb.d/


    adminer:
        image: adminer
        container_name: lprods_adminer
        restart: always
        ports:
            - 8087:80
        links:
            - db
            
    composer:
        image: composer:1.6
        container_name: lprods_composer
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: composer install  --ignore-platform-reqs

and web/Dockerfile.yml :

  FROM php:7.1-apache

    RUN apt-get update && \
    apt-get install -y \
    python \
    libfreetype6-dev \
    libwebp-dev \
    libjpeg62-turbo-dev \
    libpng-dev \
    libzip-dev \
    nano \
    git-core \
    curl \
    build-essential \
    openssl \
    libssl-dev \
    libgmp-dev \
    libldap2-dev \
    libpq-dev \
    netcat \
    sqlite3 \
    libsqlite3-dev \
    && git clone https://github.com/nodejs/node.git \
    && cd node \
    && git checkout v12.0.0 \
    && ./configure \
    && make \
    && make install

    RUN npm install cross-env

    RUN  docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-webp-dir=/usr/include/  --with-jpeg-dir=/usr/include/


    RUN  docker-php-ext-install gd pgsql pdo_pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
    && a2enmod rewrite

    COPY virtualhost.conf /etc/apache2/sites-enabled/000-default.conf

I am not sure which steps have I to take? To add command

RUN ./vendor/bin/upgrade-carbon

In the end of web/Dockerfile.yml file ?

Entering the docker bash I tried to run proposed command, but got error :

$ docker-compose exec web bash
[email protected]:/var/www/lprods_docker_root# php -v
PHP 7.1.33 (cli) (built: Oct 25 2019 06:33:10) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
[email protected]:/var/www/lprods_docker_root# ./vendor/bin/upgrade-carbon
sh: 1: composer: not found

Fatal error: Uncaught Error: Class 'Composer\Composer' not found in /var/www/lprods_docker_root/vendor/nesbot/carbon/src/Carbon/Upgrade.php:131
Stack trace:
#0 /var/www/lprods_docker_root/vendor/nesbot/carbon/bin/upgrade-carbon(28): Carbon\Upgrade::upgrade()
#1 {main}
  thrown in /var/www/lprods_docker_root/vendor/nesbot/carbon/src/Carbon/Upgrade.php on line 131
?

I tried to add proposed upgrade-carbon command into web/Dockerfile.yml file :

    RUN  docker-php-ext-install gd pgsql pdo_pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
    && a2enmod rewrite

    RUN ./vendor/bin/upgrade-carbon

    COPY virtualhost.conf /etc/apache2/sites-enabled/000-default.conf

But I got error :

Step 5/7 : RUN  docker-php-ext-install gd pgsql pdo_pgsql zip gmp bcmath pcntl ldap sysvmsg exif     && a2enmod rewrite
 ---> Using cache
 ---> 60c29909c34a
Step 6/7 : RUN ./vendor/bin/upgrade-carbon
 ---> Running in 4fb9274ac5cb
/bin/sh: 1: ./vendor/bin/upgrade-carbon: not found
ERROR: Service 'web' failed to build: The command '/bin/sh -c ./vendor/bin/upgrade-carbon' returned a non-zero code: 127

I suppose I need to run upgrade-carbon command AFTER command in composer file:

command: composer install  --ignore-platform-reqs

Can I do this in docker and how?

Thanks!

Oct
20
5 months ago
Activity icon

Replied to Vue-breadcrumbs Component Opened Wrong Page

Ho ideas? Have anybody used this plugin ? Or can you advice similar plugin for breadcrumbs making with templates ?

Oct
17
5 months ago
Activity icon

Started a new Conversation Vue-breadcrumbs Component Opened Wrong Page

Hello, In my Laravel 5.8 / vuejs 2.6 app I need to use breadcrumbs and I installed https://github.com/samturrell/vue-breadcrumbs pligin

and from its example description I see that I must to adjust all routes in resources/js/routes.js which I want to use in breadcrumbs, so I wrote :

import Home from './components/BS4/Home.vue';
import ForumsList from './components/BS4/forum/ForumsList.vue';
...
export const routes = [

    // FRONTEND PAGES BLOCK START

    {
        path: '/',
        component: Home,
        meta: {
            breadcrumb: 'Home Page',
            requiresAuth: false
        },
        name: 'HomePage',

        children: [
            {
                path: '/forums-list',
                component: ForumsList,
                meta: {
                    breadcrumb: 'Forums',
                    requiresAuth: false
                },
                name: 'ForumsList',
                children: [
                    {
                        path: '/forum/:slug',
                        component: ForumView,
                        meta: {
                            breadcrumb: 'Forum View',
                            requiresAuth: false
                        },
                        name: 'ForumView',
                        children: [
                            {
                                path: '/forum-thread/:slug',
                                component: ForumThreadView,
                                meta: {
                                    breadcrumb: 'Forum Thread',
                                    requiresAuth: false
                                },
                                name: 'ForumThreadView'
                            },

                        ]
                    },
                ]
            },

        ],


    },

    // FRONTEND PAGES BLOCK END


// BACKEND CRUD PAGES BLOCK START
    {
        path: '/admin/dashboard',
        component: DashboardContainer,
        meta: {
            requiresAuth: true,
            authGroupsAccess: ['Admin', 'Manager'],
        },
        name: 'DashboardIndex'
    },

But it does not work as I expect: clicking on "/forums-list" link with browser url changed I see content in breadcrumbs is changed to Home Page"/"Forums but in beowser home page is opened. Has my routes systax error?

Oct
02
5 months ago
Activity icon

Started a new Conversation How Correctly Convert Date Time To Moment Format?

Hello, Using vuejs 2.6 I have a function to which I sent datetime in string format like : 2019-06-03 16:53:29 , convert it to moment format and next I converto to other string format, like:

        momentDatetime(datetime, datetime_format, default_val) {

            let dt= datetime
            if (typeof datetime == "string") {
                if (datetime_format == "") return '';

                dt = Vue.moment(String(datetime));

            } // if (typeof datetime == "string") {

That works if datetime is string, now I want to send (current) datetime, like :

            item.created_at= this.momentDatetime( moment( new Date() ), this.settings_js_moment_datetime_format )

I failed with line above. How correctly convert date time to moment format ?