mstdmstd

mstdmstd

Member Since 2 Years Ago

Experience Points
14,170
Total
Experience

830 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
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 3
14,170 XP
Feb
18
1 day ago
Activity icon

Replied to Are There Maintenance-mode For Vue/cli App?

But how to generate 503 code ?

Activity icon

Replied to Are There Maintenance-mode For Vue/cli App?

Have anybody any decision from prior expierence ?

Feb
12
1 week ago
Activity icon

Started a new Conversation Are There Maintenance-mode For Vue/cli App?

Hello! I wonder if for vue/cli / bootstrap-vue project/vue-router / "vue-resource" project with laravel 6 as backend api there are some goods decisions/plugins like maintenance-mode in laravel, with blocking all site with common message and posibility to leave access to some pages, like admin area ?

Thanks!

Feb
10
1 week ago
Activity icon

Replied to Reading Data From Comments Table WithCount Returns Array Of Data Too

Sorry, no ideas why I get more data I need and how to fix it?

Feb
08
1 week ago
Activity icon

Replied to Reading Data From Comments Table WithCount Returns Array Of Data Too

No , that is the only request in the control. Action in my control app/Http/Controllers/AdCommentController.php is :

    public function index($ad_id)
    {
        $adComments = AdComment
            ::getByAdId($ad_id)
            ->withCount('children')
            ->whereNull('parent_ad_comment_id')
            ->get();
        return (new AdCommentCollection($adComments));

app/Http/Resources/AdCommentCollection.php :

<?php

namespace App\Http\Resources;

use App\library\MyFuncsClass;
use Illuminate\Http\Resources\Json\ResourceCollection;

class AdCommentCollection extends ResourceCollection
{
    public static $wrap = 'ad_comments';

    public function toArray($request)
    {

        $this->collection->transform(function ($adComment) {
            return new AdCommentResource($adComment);
        });

        return parent::toArray($request);
    }

    public function with($request)
    {
        return [
            'meta' => [
                'version'=>MyFuncsClass::getAppVersion()
            ]
        ];
    }
}

app/Http/Resources/AdCommentResource.php :

<?php

namespace App\Http\Resources;

use App\library\MyFuncsClass;
use Illuminate\Http\Resources\Json\JsonResource;

class AdCommentResource extends JsonResource
{

    public static $wrap = 'ad_comments';

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'ad_id' => $this->ad_id,

            'parent_ad_comment_id' => $this->parent_ad_comment_id,
            'user_id' => $this->user_id,
            'approved' => $this->approved,
            'comment' => $this->comment,
            'text' => 'id:'.$this->id .', count : ' .($this->children_count).' ? '.MyFuncsClass::concatStr($this->comment,30),
            'rating' => $this->rating,
            'children_count' => $this->children_count ?? 0,
            'children' => $this->children ?? [],
            'created_at' => $this->created_at,
        ];

    }

}

and model app/AdComment.php:

<?php
namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\library\MyFuncsClass;
use App\User;
use App\Ad;

class AdComment extends Model
{
    protected $fillable = [ 'ad_id', 'parent_ad_comment_id', 'user_id', 'approved',' comment', 'rating'];
    protected $table = 'ad_comments';
    protected $primaryKey = 'id';
    public $timestamps = false;

//    protected $with = ['children'];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('id', 'desc');
        });
    }

    public function ad(){
        return $this->belongsTo('App\Ad', 'ad_id','id');
    }

    public function children()
    {
        return $this->hasMany('App\AdComment', 'parent_ad_comment_id', 'id');
    }



    public function scopeGetByAdId($query, $ad_id= null)
    {
        if (!empty($ad_id)) {
            if ( is_array($ad_id) ) {
                $query->whereIn(with(new AdComment)->getTable().'.ad_id', $ad_id);
            } else {
                $query->where(with(new AdComment)->getTable().'.ad_id', $ad_id);
            }
        }
        return $query;
    }


    public function scopeGetByUserId($query, $user_id= null)
    {
        if (!empty($user_id)) {
            if ( is_array($user_id) ) {
                $query->whereIn(with(new AdComment)->getTable().'.user_id', $user_id);
            } else {
                $query->where(with(new AdComment)->getTable().'.user_id', $user_id);
            }
        }
        return $query;
    }

    public function scopeGetByParentAdCommentId($query, $parent_ad_comment_id= null)
    {
        if (!empty($parent_ad_comment_id)) {
            if ( is_array($parent_ad_comment_id) ) {
                $query->whereIn(with(new AdComment)->getTable().'.parent_ad_comment_id', $parent_ad_comment_id);
            } else {
                $query->where(with(new AdComment)->getTable().'.parent_ad_comment_id', $parent_ad_comment_id);
            }
        }
        return $query;
    }

    public function scopeOnlyApproved($query) {
        return $query->where('approved', true);
    }

    public function scopeGetByApproved($query, $approved = null)
    {
        if (!isset($approved) or strlen($approved) == 0) {
            return $query;
        }
        return $query->where(with(new AdComment)->getTable().'.approved', $approved);
    }
}

...

Activity icon

Replied to Reading Data From Comments Table WithCount Returns Array Of Data Too

Thanks! I do not need really  Eager Loading By Default, so when I run:

        $adComments = AdComment
            ::getByAdId($ad_id)
            ->with('children')
            ->whereNull('parent_ad_comment_id')
            ->get();

I see 2 statements:

   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`ad_id` = '1'     AND `parent_ad_comment_id` is null 
    ORDER BY `id` desc 
  
   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`parent_ad_comment_id` in (1, 5, 8, 9) 
    ORDER BY `id` desc 

When I do not need to read children subsitems, but only counts, I try to use withCount :

        $adComments = AdComment
            ::getByAdId($ad_id)
            ->withCount('children')
            ->whereNull('parent_ad_comment_id')
            ->get();

I see traces:

   SELECT `sda_ad_comments`.*, (  SELECT count(*) 
    FROM `sda_ad_comments`     AS `sda_laravel_reserved_0` 
    WHERE `sda_ad_comments`.`id` = `sda_laravel_reserved_0`.`parent_ad_comment_id` 
    ORDER BY `id` desc)     AS `children_count` 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`ad_id` = '1'     AND `parent_ad_comment_id` is null 
    ORDER BY `id` desc 
  
... For any found row in the request above  
   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`parent_ad_comment_id` = '9'     AND `sda_ad_comments`.`parent_ad_comment_id` is not null 
    ORDER BY `id` desc 

... For any found row in the request above
   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`parent_ad_comment_id` = '8'     AND `sda_ad_comments`.`parent_ad_comment_id` is not null 
    ORDER BY `id` desc 
...

Actually I would like to get rid from next selects, as I do not it it this case... If there is a way ?

Activity icon

Started a new Conversation Reading Data From Comments Table WithCount Returns Array Of Data Too

Hello, In Laravel 6 I have comments table with parent_id field :

    id  bigint(20) unsigned 
    ad_id   bigint(20) unsigned 
    parent_ad_comment_id    bigint(20) unsigned NULL    
    user_id int(10) unsigned NULL   
    approved    tinyint(1) [0]  
    comment mediumtext  
    rating  tinyint(3) unsigned NULL    
    created_at  timestamp [CURRENT_TIMESTAMP]

And I want to get only root ite,s with number of children data:

    $adComments = AdComment
        ::getByAdId($ad_id)
        ->withCount('children')
        ->whereNull('parent_ad_comment_id')
        ->get();

with defined scope :

    public function scopeGetByAdId($query, $ad_id= null)
        {
            if (!empty($ad_id)) {
                if ( is_array($ad_id) ) {
                    $query->whereIn(with(new AdComment)->getTable().'.ad_id', $ad_id);
                } else {
                    $query->where(with(new AdComment)->getTable().'.ad_id', $ad_id);
                }
            }
            return $query;
        }

and relation:

    public function children()
    {
        return $this->hasMany('App\AdComment', 'parent_ad_comment_id', 'id');
    }

But looking at sql I see 1 request I expect and several more requests for any find row in first request:

    SELECT `sda_ad_comments`.*, (  SELECT count(*) 
        FROM `sda_ad_comments`     AS `sda_laravel_reserved_0` 
        WHERE `sda_ad_comments`.`id` = `sda_laravel_reserved_0`.`parent_ad_comment_id` 
        ORDER BY `id` desc)     AS `children_count` 
        FROM `sda_ad_comments` 
        WHERE `sda_ad_comments`.`ad_id` = '1'     AND `parent_ad_comment_id` is null 
        ORDER BY `id` desc 
    ...  
      
       SELECT * 
        FROM `sda_ad_comments` 
        WHERE `sda_ad_comments`.`parent_ad_comment_id` = '9'     AND `sda_ad_comments`.`parent_ad_comment_id` is not null 
        ORDER BY `id` desc 
      
      
       SELECT * 
        FROM `sda_ad_comments` 
        WHERE `sda_ad_comments`.`parent_ad_comment_id` = '8'     AND `sda_ad_comments`.`parent_ad_comment_id` is not null 
        ORDER BY `id` desc 

and I see children array, which I did not expect to see. I hoped to something like children_count field. Why I got details data I do not need and how to get rid of it?

Thanks!

Feb
07
1 week ago
Activity icon

Replied to How To Count Number Of Rows With Having Condition

Sorry if I did not put it clearly from the start : I have ads table

id  bigint(20) unsigned 
ad_token    char(36)    
title   varchar(255)    
slug    varchar(260)
and ad_images table
id  bigint(20) unsigned 
ad_id   bigint(20) unsigned  // link to ads table
image   varchar(100)

Any ads rows can have several (or none) related rows to ad_images I need get count of rows in ads having related rows in ad_images

Eloquent preferable.

Activity icon

Replied to How To Count Number Of Rows With Having Condition

I tried this way and failed. Could you please give more details how request must look like?

Activity icon

Started a new Conversation How To Count Number Of Rows With Having Condition

Hello, In Laravel 6 I need to get number of rows with having condition, like :

        $ads_total_count = Ad
            ::getByTitle($this->filter_title)
            ->getByStatus('A')
            ->getUserByStatus('A')
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->leftJoin('ad_images', 'ad_images.ad_id', '=', 'ads.id')

            ->addSelect(['ad_images_count' => AdImage
                ::selectRaw('count(*)')
                ->whereColumn('ad_images.ad_id', 'ads.id')
            ])
            ->havingRaw(' ( SELECT count(*) '.
                        ' FROM `'.$prefix.'ad_images'.'` '.
                        ' WHERE '.$prefix.'ad_images.ad_id = '.$prefix.'ads.id ) > ?', [4])
            ->count();

and I have an error :

Unknown column 'ads-backend-api.sda_ads.id' in 'where clause' (SQL: 
  select count(*) as aggregate from 
    `sda_ads` left join `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` left join 
    `sda_ad_images` on `sda_ad_images`.`ad_id` = `sda_ads`.`id` where 
   `sda_ads`.`status` = A and `sda_users`.`status` = A 
having  ( SELECT count(*)  FROM `sda_ad_images`  WHERE sda_ad_images.ad_id = sda_ads.id ) > 4

looks like sda_ads.id in HAVING condition is not used from main select ? and ad_images_count coulmn is not in sql request.

I abbed ads in having clause

  $ads_total_count = Ad
            ::getByTitle($this->filter_title)
            ->getByStatus('A')
            ->getUserByStatus('A')

            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->leftJoin('ad_images', 'ad_images.ad_id', '=', 'ads.id')

            ->addSelect(['ad_images_count' => AdImage
                ::selectRaw('count(*)')
                ->whereColumn('ad_images.ad_id', 'ads.id')
            ])
            ->havingRaw(' ( SELECT count(*) '.
                        ' FROM `'.$prefix.'ad_images'.'`, `'.$prefix.'ads'.'` '.
                        ' WHERE '.$prefix.'ad_images.ad_id = '.$prefix.'ads.id ) > ?', [4])
            ->count();

and I got working but invalid sql :

   SELECT count(*)     AS aggregate 
    FROM `sda_ads` 
    LEFT JOIN `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` 
    LEFT JOIN `sda_ad_images` on `sda_ad_images`.`ad_id` = `sda_ads`.`id` 
    WHERE `sda_ads`.`status` = 'A'     AND `sda_users`.`status` = 'A' 
  HAVING  (   SELECT count(*)  
    FROM `sda_ad_images`, `sda_ads`  
    WHERE sda_ad_images.ad_id = sda_ads.id ) > '4' 

when all rows were counted.

Which way is correct?

Thanks!

Feb
03
2 weeks ago
Activity icon

Replied to I Got Unknown Column Error On Having With Count

I try to use having :

        $prefix= DB::getTablePrefix();

        $ads = Ad
            ::getByTitle($this->filter_title)
            ->onlyNoneInfo()
            ->getByStatus('A')
            ->getUserByStatus('A')
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->orderBy($this->order_by, $this->order_direction)

            ->select(
                'ads.*',
                'users.name as creator_username',
                'users.email as creator_email',
                'users.phone as creator_phone'
            )
            ->addSelect(['ad_images_count' => AdImage
                ::selectRaw('count(*)')
                ->whereColumn('ad_images.ad_id', 'ads.id')
            ])

            ->offset($limit_start)
            ->take($ads_per_page)


            ->havingRaw(' ( SELECT count(*) '.
                ' FROM `'.$prefix.'ad_images'.'` '.
                ' WHERE '.$prefix.'ad_images.ad_id = `'.$prefix.'ads`.`id` ) > ?', [0])
            ->paginate($ads_per_page)

but I got error :

Unknown column 'ads-backend-api.sda_ads.id' in 'where clause' (SQL: 
select count(*) as aggregate from `sda_ads` left join `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` where `ad_type` <> I and `sda_ads`.`status` = A and `sda_users`.`status` = A having  ( SELECT count(*)  FROM `sda_ad_images`  WHERE sda_ad_images.ad_id = `sda_ads`.`id` ) > 0

Looks like sda_ads.id is invalid condition. Which kind of wrapping does it need ?

I also tried without “`” symbol wrapping as :

->havingRaw(' ( SELECT count(*) '.
    ' FROM `'.$prefix.'ad_images'.'` '.
    ' WHERE '.$prefix.'ad_images.ad_id = '.$prefix.'ads.id ) > ?', [0])

and got :

Unknown column 'ads-backend-api.sda_ads.id' in 'where clause' (SQL: select count(*) as aggregate from `sda_ads` left join `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` where `ad_type` <> I and `sda_ads`.`status` = A and `sda_users`.`status` = A having  ( SELECT count(*)  FROM `sda_ad_images`  WHERE sda_ad_images.ad_id = sda_ads.id ) > 0

In my database ads-backend-api I have sda_ads table with id field.

“sda_” is db prefix in database configuration.

Which way is right ?

Jan
31
2 weeks ago
Activity icon

Started a new Conversation I Got Unknown Column Error On Having With Count

Hello, In Laravel 6 I have an error in request of ads with having on images count. I need to get only ads with images.

If to comment imagesCount(defined below) with request

        $ads = Ad
            ::getByTitle($this->filter_title)
            ->onlyNoneInfo()
            ->getByStatus('A')
            ->getUserByStatus('A')
//            ->imagesCount(true)
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->orderBy($this->order_by, $this->order_direction)

            ->select(
                'ads.*',
                'users.name as creator_username',
                'users.email as creator_email',
                'users.phone as creator_phone'
            )
            ->addSelect(['ad_images_count' => AdImage
                ::selectRaw('count(*)')
                ->whereColumn('ad_images.ad_id', 'ads.id')
            ])

            ->offset($limit_start)
            ->take($ads_per_page)
            ->distinct()
            ->paginate($ads_per_page);

I see sql generated :

   SELECT distinct `sda_ads`.*, `sda_users`.`name`     AS `creator_username`, `sda_users`.`email`     AS `creator_email`, `sda_users`.`phone`     AS `creator_phone`, (  SELECT count(*) 
    FROM `sda_ad_images` 
    WHERE `sda_ad_images`.`ad_id` = `sda_ads`.`id`)     AS `ad_images_count` 
    FROM `sda_ads` 
    LEFT JOIN `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` 
    WHERE `ad_type` <> 'I'     AND `sda_ads`.`status` = 'A'     AND `sda_users`.`status` = 'A' 
    ORDER BY `price` asc limit 4 offset 0 

with ad_images_count field having valid value

If to uncomment imagesCount with scope:

    public function scopeImagesCount($query, bool $check_images_count)
    {
        \Log::info('scopeImagesCount $check_images_count ::');
        \Log::info($check_images_count);

        if ($check_images_count) {
            \Log::info('CHECKING  ::');
            return $query->select(['ad_images_count' => AdImage
//            return $query->addSelect(['ad_images_count' => AdImage
                ::selectRaw('count(*)')
                ->whereColumn('ad_images.ad_id', 'ads.id')
            ])->where('ad_images_count', '>', 0);
        }
        \Log::info('SKIPPED CHECKING  ::');
        return $query;
    }

I got error :

[2020-01-31 15:27:37] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ad_images_count' in 'where clause' (SQL: select count(*) as aggregate from `sda_ads` left join `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` where `ad_type` <> I and `sda_ads`.`status` = A and `sda_users`.`status` = A and `ad_images_count` > 0) {"exception":"[object] (Illuminate\Database\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ad_images_count' in 'where clause' (SQL: select count(*) as aggregate from `sda_ads` left join `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` where `ad_type` <> I and `sda_ads`.`status` = A and `sda_users`.`status` = A and `ad_images_count` > 0) at /mnt/_work_sdb8/wwwroot/lar/ads-backend-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669)

looks like in having must subquery repeated, but not column name.

I uncommented addSelect - the same error... How?

Jan
28
3 weeks ago
Activity icon

Replied to Laravel Resources Lost Meta When I Added Mapping

I made some search and found this branch: https://stackoverflow.com/questions/49477682/conditional-relationship-not-appearing-in-laravel-resource-api

It was implemented with related model methods :

$games = Game::with('availableInterests')->get();

But I have a bit different case as as I can not get main_image and main_image_info using “:with”(or can ?) . I think I can read related categories fields with double relationship(seems eloquent can do it...). Any ideas ?

Jan
27
3 weeks ago
Activity icon

Replied to Laravel Resources Lost Meta When I Added Mapping

Thank you for feedback! I try to make next : I remove mapping from request :

        $ads = Ad
            ::getByTitle($this->filter_title)
            ->getByStatus('A')
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->orderBy($order_by, $order_direction)

            ->select(
                'ads.*',
                'users.name as creator_username',
                'users.email as creator_email',
                'users.phone as creator_phone'
            )

            ->offset($limit_start)
            ->take($ads_per_page)
            ->distinct()
            ->paginate($ads_per_page)l

I remade app/Http/Resources/AdCollection.php :

<?php

namespace App\Http\Resources;

use App\library\MyFuncsClass;
use Illuminate\Http\Resources\Json\ResourceCollection;

class AdCollection extends ResourceCollection
{

    public static $wrap = 'ads';

    public function toArray($request)
    {
        $this->collection->transform(function ($ad) {
            return new AdResource($ad);
        });
        return parent::toArray($request);
    }

    public function with($request)
    {
        return [
            'meta' => [
                'version'=>MyFuncsClass::getAppVersion()
            ]
        ];
    }

}

I created app/Http/Resources/AdResource.php :

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class AdResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'phone_display' => $this->phone_display,
            'published' => $this->published,
            'price' => $this->price,
            'ad_type' => $this->ad_type,
            'top' => $this->top,
            'expire_date' => $this->expire_date,
            'description' => $this->description,
            'creator_id' => $this->creator_id,
            'creator_username' => !empty($this->creator_username) ? $this->creator_username : null,
            'creator_email' => !empty($this->creator_email) ? $this->creator_email : null,
            'creator_phone' => !empty($this->creator_phone) ? $this->creator_phone : null,
            'categories' => !empty($this->categories) ? $this->categories : [],
            'main_image' => $this->main_image,
            'main_image_info' => $this->main_image_info,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Now in results data I see all meta info, but I lost main_image, main_image_info and categories fields

I see how whenLoaded must be used inside of AdResource, but how have I to run requests to get values for main_image, main_image_info and categories fields? Just in resource like :

class AdResource extends JsonResource
{
    public function toArray($request)
    {
    
        $adImage= AdImage
           ::getByAdId($this->id)
           ->getByMain(true)
           ->first();

        return [
            'id' => $this->id,
            ...
            'adImage' => $adImage->image,

? That not seems as good way...

Jan
26
3 weeks ago
Activity icon

Started a new Conversation Laravel Resources Lost Meta When I Added Mapping

Hello, In Laravel 6 I make pagination listing like

        $ads = Ad
            ::getByTitle($this->filter_title)
            ->getByStatus('A')
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->orderBy($this->order_by, $this->order_direction)

            ->select(
                'ads.*',
                'users.name as creator_username',
                'users.email as creator_email',
                'users.phone as creator_phone'
            )
            ->offset($limit_start)
            ->take($ads_per_page)
            ->distinct()
            ->paginate($ads_per_page);
            return (new AdCollection($ads));

and it works ok for me and in meta of returned data I got additive params including total :

meta":{"current_page":1,"from":1,"last_page":2,..."to":4,"total":5,"version":"1.0.3"}}

But I got a problem I added map to this request like:

        $ads = Ad
            ::getByTitle($this->filter_title)
            ->getByStatus('A')
            ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
            ->orderBy($this->order_by, $this->order_direction)

            ->select(
                'ads.*',
                'users.name as creator_username',
                'users.email as creator_email',
                'users.phone as creator_phone'
            )

            ->offset($limit_start)
            ->take($ads_per_page)
            ->distinct()
            ->paginate($ads_per_page)
            ->map(function ($adItem) {
                $adImage= AdImage
                    ::getByAdId($adItem->id)
                    ->getByMain(true)
                    ->first();
                if ($adImage) {
                    $adItem->main_image= $adImage->image;
                    $adItem->main_image_info= $adImage->info;
                }

                $categories = AdCategory
                    ::getByAdId($adItem->id)
                    ->leftJoin('categories', 'categories.id', '=', 'ad_categories.category_id')
                    ->orderBy('category_name', 'desc')

                    ->select(
                        'ad_categories.category_id as category_id',
                        'categories.name as category_name',
                        'categories.slug as category_slug'
                    )
                    ->get()
                    ->toArray();
                $adItem->categories= $categories;

                return $adItem;
            })
            ->all();

as I lost all meta data. Why error and if there is a way to fix it?

In app/Http/Resources/AdCollection.php I have :

<?php

namespace App\Http\Resources;

use App\library\MyFuncsClass;
use Illuminate\Http\Resources\Json\ResourceCollection;

class AdCollection extends ResourceCollection
{

    public static $wrap = 'ads';

    public function toArray($request)
    {
        return $this->collection->transform(function($ad){
            return [
                'id' => $ad->id,
                'title' => $ad->title,
                'slug' => $ad->slug,
                'phone_display' => $ad->phone_display,
                'published' => $ad->published,
                'price' => $ad->price,
                'ad_type' => $ad->ad_type,
                'expire_date' => $ad->expire_date,
                'description' => $ad->description,
                'creator_id' => $ad->creator_id,
                'creator_username' => !empty($ad->creator_username) ? $ad->creator_username : null,
                'creator_email' => !empty($ad->creator_email) ? $ad->creator_email : null,
                'creator_phone' => !empty($ad->creator_phone) ? $ad->creator_phone : null,
                'categories' => !empty($ad->categories) ? $ad->categories : [],
                'main_image' => $ad->main_image,
                'main_image_info' => $ad->main_image_info,
                'created_at' => $ad->created_at,
                'updated_at' => $ad->updated_at,
            ];
        });
    }

    public function with($request)
    {
        return [
            'meta' => [
                'version'=>MyFuncsClass::getAppVersion()
            ]
        ];
    }

}

Thanks!

Jan
20
4 weeks ago
Activity icon

Started a new Conversation How To Stop Output Of Beyondcode/laravel-dump-server If Server Is Not Running

In Laravel 6 backend rest api app I installed beyondcode/laravel-dump-server with wrapper method for dump( and it works ok, when I run dump-server in console. But if I closed console and do not remove dump( from my code I got errors in my app, as data are still ouputted... If these a way to check if dump-server is not runnig? In this case I would be eble not to run dump( in my wrapper function ...

Or somother tools with similar functionality ?

Thanks!

Jan
15
1 month ago
Activity icon

Replied to How To Call Facades Method From Boot Method?

Sorry, that is not clear. Could you please provide more details?

Activity icon

Replied to How To Call Facades Method From Boot Method?

I try a way to rename my helper class to “MyFuncsClassContainer”, supposing that that having the same name for helper and facade could raise error:

<?php

namespace App;

use DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

use App\Facades\MyFuncsClass;
use App\Http\Helpers\MyFuncsClassContainer; // Alias for my helper class
use Illuminate\Database\Eloquent\Model;
use Barryvdh\Debugbar\Facade as Debugbar;

class Task extends Model
{
    use Sluggable;

    protected $table = 'tasks';
    protected $primaryKey = 'id';
    }

    protected static function boot() {
        parent::boot();

        static::deleting(function($task) {
            $hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);


            \Log::info( '-9 $hostel_image_image_path::' );
            \Log::info( print_r($hostel_image_image_path, true) );
            $myFuncsClassCore = factory(MyFuncsClassContainer::class)->create();
            $myFuncsClassCore->debToFile(' debToFile string REDSA');

Bur anywat I got error :

 Cannot declare class App\Helpers\MyFuncsClassContainer, because the name is already in use {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException

If there is a way to fix this error ?

Jan
13
1 month ago
Activity icon

Replied to How To Call Facades Method From Boot Method?

I try to follow this link with example as :

 <?php

namespace App;

use DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Cviebrock\EloquentSluggable\Sluggable;

use App\Facades\MyFuncsClass;
...
        parent::boot();

        static::deleting(function($task) {
            $hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);
            $myFuncsClassCore = factory(MyFuncsClass::class)->create();
            $myFuncsClassCore->debToFile(' debToFile string REDSA');

But I got error :

[2020-01-13 16:24:49] local.ERROR: Unable to locate factory with name [default] [App\Facades\MyFuncsClass]. {"userId":1,"exception":"[object] (InvalidArgumentException(code: 0): Unable to locate factory with name [default] [App\Facades\MyFuncsClass]. at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:269)
[stacktrace]

Looks like error was raised as MyFuncsClass in this case in facade, class, but not my helpers class? I tried :

  1. 2nd way
<?php

namespace App;

use DB;
use App\Facades\MyFuncsClass;
use App\Http\Helpers\MyFuncsClass as MyFuncsClassCore; // Alias for my helper class
...
        static::deleting(function($task) {
            $hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);
         $myFuncsClassCore = factory(MyFuncsClassCore::class)->create();
         $myFuncsClassCore->debToFile(' debToFile string REDSA');

I got error :

[2020-01-13 16:31:01] local.ERROR: Cannot declare class App\Helpers\MyFuncsClass, because the name is already in use {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 1): Cannot declare class App\Helpers\MyFuncsClass, because the name is already in use at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/app/Http/Helpers/MyFuncsClass.php:19)
[stacktrace]

Which way is correct?

As I want to keep both facade to my library and create real time facade in static functions, which raise errors I started. is it possible?

Activity icon

Started a new Conversation How To Call Facades Method From Boot Method?

Hello, In laravel 6 app I created facade app/Facades/MyFuncsClass.php :

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class MyFuncsClass extends Facade{
    protected static function getFacadeAccessor() { return 'MyFuncsClass'; }
}

I registered my facade in config/app.php, 'providers' block

But I got error :

    "message": "Non-static method App\Helpers\MyFuncsClass::debToFile() should not be called statically",

calling it from boot method:

    protected static function boot() {
        parent::boot();

        static::deleting(function($task) {
            $hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);
            MyFuncsClass::debToFile(print_r($hostel_image_image_path, true), '-9 $hostel_image_image_path::');
            ...

Is there is a way to escape this error and run MyFuncsClass::debToFile in boot method ? Actually I can call \MyFuncsClass::debToFile( ok from not static methods, like control actions, but I have the error calling from static boot method...

Thanks!

Activity icon

Replied to I Do Not Have Meta Data In Laravel's Resources

Yes, I saw that I have nested arrays, but with your last code example I ghot errors and do now how to handle it. I found decitions here https://stackoverflow.com/questions/46388205/laravel-5-5-api-resources-for-collections-standalone-data

In code code it was listing and when I need to get 1 row I have to writeL

            loadTaskDetails() {
                axios({url: this.apiUrl + '/get_task_by_slug/' + this.task_slug, data: {}, method: 'get'})
                    .then(response => {
                        this.taskRow = response.data.data[0][0]
                        this.task_assigned_to_users_count = response.data.meta.task_assigned_to_users_count

syntax looks terrible, but that works for me...

Jan
12
1 month ago
Activity icon

Replied to I Do Not Have Meta Data In Laravel's Resources

Yes, in my app/Providers/AppServiceProvider.php I have lines :

<?php

namespace App\Providers;

use Auth;
use Validator;
use Illuminate\Http\Resources\Json\Resource;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {

        Resource::withoutWrapping();

But if line above commented or not I have to use :

                        this.tasks = response.data.data[0]

in both cases?

Is withoutWrapping parameter applicable ResourceCollection data? Are there some otgher parameters involved ?

Activity icon

Replied to I Do Not Have Meta Data In Laravel's Resources

Thanks! One More question on client(vuejs.axios request) to read data I have to write:

                        this.tasks = response.data.data[0]
                        this.tasks_total_count = response.data.meta.tasks_total_count

If there is a way to get rid away of .data[0] ?

Activity icon

Replied to I Do Not Have Meta Data In Laravel's Resources

Thanks for your feedback! I made like :

<?php

namespace App\Http\Resources;
use App\Facades\MyFuncsClass;

use Illuminate\Http\Resources\Json\ResourceCollection;

class TaskCollection extends ResourceCollection
{
    public function toArray($task)
    {

        return [
            $this->collection->transform(function($task){
                return [
                    'id' => $task->id,
                    'name' => $task->name,
                    'slug' => $task->slug,
                    'price' => $task->price,
                    'description' => $task->description,
                    'creator_id' => $task->creator_id,
                    'leader_id' => $task->leader_id,
                    'category_id' => $task->category_id,
                    'priority' => $task->priority,
                    'status' => $task->status,

                    'date_start' => $task->date_start,
                    'date_start_formatted' => MyFuncsClass::mySqlToStringDate($task->date_start),

                    'date_end' => $task->date_end,
                    'date_end_formatted' => MyFuncsClass::mySqlToStringDate($task->date_end),

                    'needs_reports' => $task->needs_reports,
                    'image' => $task->image,
                    'leader_name' => $task->leader_name,
                    'category_name' => $task->category_name,
                    'category_slug' => $task->category_slug,
                    'filenameData' => $task->filenameData,
                    'taskRequireSkills' => !empty($task->taskRequireSkills) ? $task->taskRequireSkills : [],
                    'events' => !empty($task->events) ? $task->events : [],
                    'events_count' => !empty($task->events_count) ? $task->events_count : 0,
                    'created_at' => $task->created_at,
                    'updated_at' => $task->updated_at,
                ];
            }),
        ];

    }

    public function with($task)
    {
        return [
            'meta' => [
                'version'=>'1.0.2'
            ]
        ];
    }

}

and the only question I have is how to pass 1 more parameter tasks_total_count, which I need for pagination of my page? I can not put it in “with” method as it is changable value for any request. I can set this value in any $task row, but this way seems not good...

Jan
11
1 month ago
Activity icon

Started a new Conversation I Do Not Have Meta Data In Laravel's Resources

Hello, In my laravel 5 apps I returned json in request controls, like:

        $retArray['tasks']          = $taskList;
        $retArray['tasks_total_count'] = $tasks_total_count;
        return response()->json($retArray, 200);

including additive parameters like tasks_total_count, which was used for pagination.

In laravel 6 app I use resources, like:

<?php

namespace App\Http\Resources\Admin;

use App\Facades\MyFuncsClass;
use Illuminate\Http\Resources\Json\JsonResource;

class Task extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'price' => $this->price,
            ...
            'taskRequireSkills' => !empty($this->taskRequireSkills) ? $this->taskRequireSkills : [],
            'events' => !empty($this->events) ? $this->events : [],
            'events_count' => !empty($this->events_count) ? $this->events_count : 0,
            'created_at' => $this->created_at,
            ...
        ];
    }

    public function with($request)
    {
        return [
            'meta' => [
                'version'=>'1.0.2'
            ]
        ];
    }

}

I want to add some additive meta data, like version but in my browser I do not see this meta data, : https://prnt.sc/qm4t8y Also which is correct way to add tasks_total_count parameter to my Resource, which is diffrent for any request?

Thanks!

Jan
10
1 month ago
Activity icon

Started a new Conversation How In Laravel Connect To Phpbb With Oauth2

Hello, I learn oath2 in laravel 6 with passport and I want to add to my testing passport app several external apps. First I installed phpbb and found this https://area51.phpbb.com/docs/dev/3.2.x/extensions/tutorial_authentication.html tutorial. But I stuck on first steps, as I read :

An authentication provider that comes with phpBB requires a minimum of two files: a class and an entry in a config/auth.yml file. Authentication provider.

I did not find any config/auth.yml file, but I found file config/default/container/services_auth.yml with lines : ...

    auth.provider.oauth:
        class: phpbb\auth\provider\oauth\oauth
        arguments:
            - '@dbal.conn'
            - '@config'
            - '@passwords.manager'
            - '@request'
            - '@user'
            - '%tables.auth_provider_oauth_token_storage%'
            - '%tables.auth_provider_oauth_states%'
            - '%tables.auth_provider_oauth_account_assoc%'
            - '@auth.provider.oauth.service_collection'
            - '%tables.users%'
            - '@service_container'
            - '@dispatcher'
            - '%core.root_path%'
            - '%core.php_ext%'
        tags:
            - { name: auth.provider }

# ----- OAuth services providers -----
    auth.provider.oauth.service_collection:
        class: phpbb\di\service_collection
        arguments:
            - '@service_container'
        tags:
            - { name: service_collection, tag: auth.provider.oauth.service }
...
  1. Is it the same file and I have to modify it? If yes, which params have I to edit?
  2. Have I to create a new config/auth.yml file and edit it? If yes, which params have I to add?

Which steps have I to take to login to phpbb with my laravel passport account ?

Thanks!

Jan
07
1 month ago
Activity icon

Replied to Guzzle Post Request Returns 419 Unknown Status

Sorry, I did not point in my topic : I make @vue/cli/axios 4 app with requests to Laravel 6 Backend REST API with passport auth driver. So I have axios request to laravel's control in which I run code in my topic.

I know this decision

<meta name="csrf-token" content="{{ csrf_token() }}">

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

for laravel/blade apps with data submitted in blade form when ajax is set:

If there is some decision for Backend REST API control with axios request ?

Activity icon

Started a new Conversation Guzzle Post Request Returns 419 Unknown Status

Hello, I try to run passport '/oauth/clients' method to create new passport's client with guzzle and got 419 unknown status error I do :

            $app_root_url = config('app.url');
            \Log::info('-1 REGISTER $app_root_url::');
            \Log::info($app_root_url);

            $headers =  [
                'content-type' => 'application/json',
                'verify' => true,
                'X-CSRF-TOKEN' => csrf_token()
            ];

            $guzzleClient = new \GuzzleHttp\Client();
            $url = $app_root_url . '/oauth/clients';

            $requestBody['name'] = $newUser->name;
            $requestBody['redirect'] = $app_root_url . '/callback';
//            $requestBody['Accept'] = 'application/json';  // Do I need this parameter ?

            \Log::info('-2 REGISTER $requestBody::');
            \Log::info($requestBody);

            \Log::info('-3 REGISTER $headers::');
            \Log::info($headers);

            $request = $guzzleClient->post( $url,  [
                "headers" => $headers,             // Do I need these params ?
                'form_params' => $requestBody  //  ERROR REFERING THIS LINE
            ]);
            $response = $request->send();
            \Log::info('-5 REGISTER $response::');
            \Log::info($response);

Usually this error shows that CSRF is not set and in log file I see that in headers array X-CSRF-TOKEN is NULL :

[2020-01-07 04:47:02] local.INFO: -1 REGISTER $app_root_url::  
[2020-01-07 04:47:02] local.INFO: http://local-hostels3-backend-api.com  
[2020-01-07 04:47:02] local.INFO: -2 REGISTER $requestBody::  
[2020-01-07 04:47:02] local.INFO: array (
  'name' => 'admin',
  'redirect' => 'http://local-hostels3-backend-api.com/callback',
)  
[2020-01-07 04:47:02] local.INFO: -3 REGISTER $headers::  
[2020-01-07 04:47:02] local.INFO: array (
  'content-type' => 'application/json',
  'verify' => true,
  'X-CSRF-TOKEN' => NULL,
)  
[2020-01-07 04:47:03] local.ERROR: Client error: `POST http://local-hostels3-backend-api.com/oauth/clients` resulted in a `419 unknown status` response:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width= (truncated...)
 {"exception":"[object] (GuzzleHttp\Exception\ClientException(code: 419): Client error: `POST http://local-hostels3-backend-api.com/oauth/clients` resulted in a `419 unknown status` response:
<!DOCTYPE html>
<html lang=\"en\">
    <head>
        <meta charset=\"utf-8\">
        <meta name=\"viewport\" content=\"width= (truncated...)
 at /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113)
[stacktrace]
#0 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()
#4 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\Promise\TaskQueue->run(true)
#5 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(223): GuzzleHttp\Promise\Promise->invokeWaitFn()
#6 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\Promise\Promise->waitIfPending()
#7 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\Promise\Promise->invokeWaitList()
#8 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending()
#9 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/guzzle/src/Client.php(183): GuzzleHttp\Promise\Promise->wait()
#10 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/vendor/guzzlehttp/guzzle/src/Client.php(96): GuzzleHttp\Client->request('post', 'http://local-ho...', Array)
#11 /mnt/_work_sdb8/wwwroot/lar/hostels3-backend-api/app/Http/Controllers/AuthController.php(224): GuzzleHttp\Client->__call('post', Array)
#12 [internal function]: App\Http\Controllers\AuthController->register(Object(Illuminate\Http\Request))

I tried to comment in headers lines one by one :

                'verify' => true,
                'X-CSRF-TOKEN' => csrf_token()

But I still got the same error.

I commented VerifyCsrfToken in kernel :
    protected $middlewareGroups = [
        ...
//        \App\Http\Middleware\VerifyCsrfToken::class,

But got error :

://local-hostels3-backend-api.com/oauth/clients` resulted in a `500 Internal Server Error` response:\n<!doctype html>\n<html class=\"theme-light\">\n<!--\nSymfony\Component\Routing\Exception\RouteNotFoundException: Route [login (truncated...)\n",
    "exception": "GuzzleHttp\Exception\ServerException",

In routes/api.php I have :

Route::post('login', '[email protected]')->name('api.login');
Route::post('register', '[email protected]')->name('api.register');
Route::post('callback', '[email protected]')->name('api.callback');

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
How to fix this error ?

Thanks!

Dec
27
1 month ago
Activity icon

Replied to Changes I Make In @vue/cli App Are Not Applied With Local Server

I made some additive checks :

Editing vue files of the project in defautl kate editor I opened the project in Visual Studio Code I see that my changes are not applied, until I close console and run npm run serve again

So I suppose that it is not PhpStorm options issue?

Dec
26
1 month ago
Activity icon

Replied to Changes I Make In @vue/cli App Are Not Applied With Local Server

Actually that is not Laravel project, but @vue/cli 4.0.5 And in package.json I have :

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

No watch command as I have in Laravel... Also I had been working with this project for 2 monthes, but suffer it last several days...

Activity icon

Replied to Changes I Make In @vue/cli App Are Not Applied With Local Server

I got :

$ npm run watch
npm ERR! missing script: watch

Some option missing in app config ?

Activity icon

Started a new Conversation Changes I Make In @vue/cli App Are Not Applied With Local Server

Hello, working with @vue/cli 4.0.5 in dev mode I run server locally and very often I see changes I make in my PhpStorm 2019.2.3 are not applied to my running local server

I see output in the console :

$ npm run serve

> [email protected] serve /mnt/_work_sdb8/wwwroot/lar/VApps/vtasks
> vue-cli-service serve

 INFO  Starting development server...
98% after emitting CopyPlugin

 DONE  Compiled successfully in 8350ms                                                                                                                                                                                             6:18:04 PM


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

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


But to see my changes in Phpstorm applied I need to close console with local server...
Just thought is it safe to close console with running server ?

Also I seems to me this problem started after I begin working with Nuxt app with default localhost:3000 port. I mean I work in one Kubuntu session , switching from one app to other in console and closing console with running localhost and running commands npm run serve / npm run dev Can it be the issue and how it can be detected / salved ? –

uname -a
Linux athoe 4.15.0-72-generic #81-Ubuntu SMP Tue Nov 26 12:20:02 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

package.json :

{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "v-money": "^0.8.1",
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",
    "vue-focus": "^2.1.0",
    "vue-js-modal": "^1.3.31",
    "vue-nav-tabs": "^0.5.7",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vue-the-mask": "^0.11.1",
    "vue-wysiwyg": "^1.7.2",
    "vue2-datepicker": "^3.3.0",
    "vue2-filters": "^0.8.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  }
}

Thanlks!

Dec
13
2 months ago
Activity icon

Started a new Conversation Adding Second Form Action With Button It Does Not Work

Hello,

In laravel 5.7 with blade app I need to add button to form which has no <form tag, so I add

            <div class="form-row p-5">
                <div class="col-12 col-sm-6 mb-3 pr-2 pl-2">
                </div>
                <div class="col-12 col-sm-6 mb-3 mt-1 pl-2 pr-2">
                    <form id="storage_spaces_export_form" action="{{ route('admin.storage_spaces_export') }}" method="POST" >
                        @csrf
                        <button type="button" class="btn btn-primary float-right">
                            <span class="btn-label"><i class="fa fa-plus"></i></span>&nbsp;Export ALL box rooms to csv file
                        </button>&nbsp;&nbsp;
                    </form>
                </div>
            </div>

But nothing is triggered pushing this button, I open source of this page and see 2 forms defintions :

        </a>
            <form id="logout-form" action="http://local-boxbooking2.com/logout" method="POST" style="display: none;">
                <input type="hidden" name="_token" value="7ioKi3WR19G31mKpZSnKMpOzT9WND2wvEapJ5FPr">                </form>
                
                ...

         <div class="form-row p-5">
                <div class="col-12 col-sm-6 mb-3 pr-2 pl-2">
                </div>
                <div class="col-12 col-sm-6 mb-3 mt-1 pl-2 pr-2">
                    <form id="storage_spaces_export_form" action="http://local-boxbooking2.com/admin/storage_spaces_export" method="POST" >
                        <input type="hidden" name="_token" value="7ioKi3WR19G31mKpZSnKMpOzT9WND2wvEapJ5FPr">   
                                                 <button type="button" class="btn btn-primary float-right">
                            <span class="btn-label"><i class="fa fa-plus"></i></span>&nbsp;Export ALL box rooms to csv file
                        </button>&nbsp;&nbsp;
                    </form>
                </div>
            </div>
            

I do not see why the new button does not work and how to fix it ?

Thanks!

Dec
12
2 months ago
Activity icon

Started a new Conversation Opening Vue-js-modal Filtered Data Show Empty Array

Hello, In vue/cli 4 app I make events page with component for any event and by clicking on button admin can modify users of this event in modal dialog("vue-js-modal": "^1.3.31",). I read data from backend api app and I need to show filtered user list. I use computed filterEventUsers method, which now returns all data(later I will add some filters in it). The problem is that in my page I see valid rows of both users listings in eventUsers and filterEventUsers. I see it it vue debugging : https://imgur.com/a/WiGHvNF

But listing under modal is empty. I do not see why? all data in Modal has no any scope ? I supposed no ?

I do :

    <template>
        <article class="event_item_container">
    
    
            eventUsers::{{ eventUsers }}
            <br>filterEventUsers::{{ filterEventUsers }}
            <!-- THESE LISTINGS ARE EMPTY ON PAGE OPENED, BUT FILLED WHEN I CLICK BUTTON CALLING showMembersOfThisEvent method-->
    
    
            <ul class="column_content_left_aligned">
                ...my page
            </ul>
    
    
    
            <!-- MODAL PAGE DEFINITION START-->
            <modal :height="modalTaskEventDetailsHeight+100" :width="modalWidth" name="modal-members-of-this-event" transition="pop-out">
    
                <div class="modal-content p-3">
    
                    <div class="modal-body">
    
                        <div class="column_content_left_aligned">
                            <div class="row_content_left_aligned p-3" style="overflow-y: scroll; max-height: 800px; ">
                                <fieldset class="blocks">
                                    <legend class="blocks">{{ filterEventUsers.length }} assigned {{ filterEventUsers.length |
                                        pluralize(['user','users']) }}
                                    <!-- SHOW 0 -->
                                        
                                    </legend>
                                    <div class="table-responsive table-wrapper-for-data-listing ">
                                        ++===filterEventUsers::{{ filterEventUsers }}
                                        <!-- THIS SHOWS EMPTY LISTING so MY NEXT LISTING IS EMPTY-->
                                        ... my listing
                                    </div>
    
    
                                </fieldset>
    
                            </div> <!-- <div class="row_content_left_aligned p-3" style="overflow-y: scroll; max-height: 400px; "> -->
    
                        </div> <!-- <div class="column_content_left_aligned"> -->
    
                    </div> <!-- <div class="modal-body"> -->
    
                </div> <!-- <div class="modal-content"> -->
    
    
            </modal> <!-- modal-members-of-this-event  -->
    
            <!-- MODAL PAGE DEFINITION END-->
    
    
        </article>
    </template>
    
    <script>
        import {bus} from '../../main'
        import axios from 'axios'
    
        import Vue from 'vue'
    
        import appMixin from '@/appMixin'
        import {settingsEventAccessLabels, settingsEventsPerPage, settingsJsMomentDatetimeFormat} from './../../app.settings.js'
        import {settingCredentialsConfig} from '@/app.settings.js'
    
        export default {
            name: 'eventsTimelineItem',
    
            data: function () {
                return {
                    innerWidth,
                    innerHeight,
                    credentialsConfig: settingCredentialsConfig,
                    eventUsers : [], // DATA
                    eventsPerPage: settingsEventsPerPage,
                    eventAccessLabels: settingsEventAccessLabels,
                    jsMomentDatetimeFormat: settingsJsMomentDatetimeFormat,
                    apiUrl: process.env.VUE_APP_API_URL
    
                }
            }, // data: function () {
    
    
            computed: {
    
                filterEventUsers() {
                    return this.eventUsers.filter(state => { // FILTER METHOD WHICH NOW RETURNS ALL DATA
                        // if (state.published && state.is_homepage) {
                        return true;
                        // }
                        // return false;
                    });
                },
    
                modalTaskEventDetailsHeight() {
                    return this.innerHeight - 200
                },
    
                modalWidth() {
                    return this.innerWidth - 100
                },
    
                loggedUserIsManager: function () {
                    return this.$store.getters.is_manager
                },
    
                loggedUserIsAdmin: function () {
                    return this.$store.getters.is_admin
                },
    
                currentLoggedUserToken() {
                    return this.$store.getters.token
                },
    
            }, //computed: {
    
            methods: {
    
                // MEMBERS OF THIS TASK MODAL START
                showMembersOfThisEvent() {
                    if (this.currentLoggedUser == null || typeof this.currentLoggedUser.id === 'undefined') {
                        this.showPopupMessage('Modification of members of the event', 'You need to login !', 'warn')
                        return
                    }
    
                    if (!this.loggedUserIsManager && !this.loggedUserIsAdmin) {
                        this.showPopupMessage('Modification of members of the event', 'You have no access to this functionality !', 'warn')
                        return
                    }
    
    
                    this.credentialsConfig.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken
                    console.log('users_of_event_selection this.credentialsConfig::')
                    console.log(this.credentialsConfig)
    
                    axios.get(this.apiUrl + '/manager/users_of_event_selection/' + this.nextEvent.id, this.credentialsConfig)
                        .then((response) => {
                            console.log('users_of_event_selection response::')
                            console.log(response)
                            this.eventUsers = response.data.eventUsers // I READ DATA FROM SERVER BY CLICKING ON BUTTON
    
                            this.$modal.show('modal-members-of-this-event', {
                                title: 'Members of event'
                            })
                        })
                        .catch(error => {
                            console.error(error)
                            this.showPopupMessage('Members of the event', error.response.data.message, 'warn')
                        })
    
                }, // showMembersOfThisEvent() {
    
                cancelMembersOfThisEvent() {
                    this.$modal.hide('modal-members-of-this-event')
                }, // cancelMembersOfThisEvent() {
    
    
            }, // methods: {
    
            mixins: [appMixin]
    
        }
    </script>

why filterEventUsers is empty in my modal and how to fix it?

Thanks!

Dec
02
2 months ago
Activity icon

Started a new Conversation Installin Jwt-auth In Laravel 5.8 Got Error JWTAuthServiceProvider' Not Found

Hello, I try to install jwt-auth to my laravel 5.8 ass as written here https://github.com/tymondesigns/jwt-auth/wiki/Installation

But I encountered versions compatibility error and after search I found this

https://stackoverflow.com/questions/55824542/tymon-jwt-auth-package-show-error-in-laravel-5-8/57131871

and with command

composer require tymon/jwt-auth:dev-develop

I installed tymon/jwt-auth successfully, but trying to write config options in config/app.php:

'providers' => [
...

'aliases' => [
...
'Tymon\JWTAuth\Providers\JWTAuthServiceProvider' 

but next instructions

Also included is a Facade for the PayloadFactory. This gives you finer control over the payloads you create if you require it
'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory'

I did not find in which file I have to write it, if I really need it?

With next command I got error :

 php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

In ProviderRepository.php line 208:
                                                                    
  Class 'Tymon\JWTAuth\Providers\JWTAuthServiceProvider' not found  

Searching I net I found some decisions for different versions, but I failed to fix this error...

How to fix it? Is this issue with JWTFactory ?

My composer.json :
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "barryvdh/laravel-cors": "^0.11.4",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.8.9",
        "laravel/passport": "^7.0",
        "laravel/tinker": "^1.0",
        "spatie/laravel-activitylog": "^3.9",
        "tymon/jwt-auth": "dev-develop",
        "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"
        ]
    }
}
Nov
29
2 months ago
Activity icon

Replied to In Laravel Backend REST API App After Installing Tymon/jwt-auth Again Suffer CORS Error

Sorry, no possible decision ? Are there some examples/demo available with vue/cli / Laravel Backend REST API using jwt and CORS problem salved? It would be very interesting to upload / install and try to run locally...

Nov
28
2 months ago
Activity icon

Replied to In Laravel Backend REST API App After Installing Tymon/jwt-auth Again Suffer CORS Error

Thanks for your help! I applied your changes and it looks like that GET requests works ok, POST requests do not work.

so in my backend API routes/api.php with 3 routes :

Route::post('login', 'API\[email protected]', ['except' => []]);
Route::post('register', 'API\[email protected]');
Route::get('get_users_stats/{id}', 'API\[email protected]_users_stats');

only the last works ok.

In config/cors.php I have options :

    'supportsCredentials' => true,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], 
    'exposedHeaders' => [],
    'maxAge' => 0,

But if to change option :

'allowedMethods' => ['POST'], // ex: ['GET', 'POST', 'PUT',  'DELETE']

then both POST / GET DO NOT WORK and raise CORS error

Also as POST request needs csrf token provided, could it be the issue ?

Nov
27
2 months ago
Activity icon

Replied to In Laravel Backend REST API App After Installing Tymon/jwt-auth Again Suffer CORS Error

That does not work for me. In config/cors.php of backend app I set 

'supportsCredentials' => true

And in vue/cli in file src/main.js I added property

import axios from 'axios'
...

axios.defaults.crossDomain = true
axios.defaults.withCredentials = true  // Do you mean this format? 
...

Vue.prototype.$http = axios

Actually making login into the system I run POST request, like:

                let config = {
                    headers: {
                        'Content-Type': 'application/json',
                        'Access-Control-Allow-Origin': '*',
                        'withCredentials':true // I TRIED TO ADD THIS PARAM HERE
                    }
                }

                axios.post(apiUrl + '/login', userCredentials, config)
                    .then((response) => {
                    ...

But failed anyway. Which way is valid ?

Nov
26
2 months ago
Activity icon

Replied to In Laravel Backend REST API App After Installing Tymon/jwt-auth Again Suffer CORS Error

CONTINUED : config/cors.php :

<?php

return [

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
    
];

In config/app.php :

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
        Barryvdh\Cors\ServiceProvider::class,  // CORS ADDED LINE

        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

//        Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class, // I HAD PROBLEMS WITH THIS OPTION - SO I COMMENTED it

    ],


    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Arr' => Illuminate\Support\Arr::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'Str' => Illuminate\Support\Str::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,
        'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, // JWT ADDED !
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

    ],

Searching in net I found some possible decisions, but failed with any... What did I miss and how make it running ?

Activity icon

Started a new Conversation In Laravel Backend REST API App After Installing Tymon/jwt-auth Again Suffer CORS Error

Hello, I make @vue/cli 4.0.5 / vuex 3 app with data reading from Laravel Backend REST API and I used /barryvdh/laravel-cors(0.11.4) to salve CORS problem : and it worked ok, untill I added tymon/jwt-auth(1.0.0) and implementing this library I had some issues with included libs, but after I installed it I again encountered CORS error, like :

VM15:1 OPTIONS http://local-ctasks-api.com/api/login 403 (Forbidden)
(anonymous) @ VM15:1
dispatchXhrRequest @ xhr.js?b50d:172
xhrAdapter @ xhr.js?b50d:11
dispatchRequest @ dispatchRequest.js?5270:59
Promise.then (async)
request @ Axios.js?0a06:53
Axios.<computed> @ Axios.js?0a06:78
wrap @ bind.js?1d2b:9
eval @ index.js?4360:135
login @ index.js?4360:124
wrappedActionHandler @ vuex.esm.js?2f62:747
dispatch @ vuex.esm.js?2f62:438
boundDispatch @ vuex.esm.js?2f62:332
authenticate @ Login.vue?7463:164
submit @ Login.vue?2447:24
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1854
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6911
login:1 Access to XMLHttpRequest at 'http://local-ctasks-api.com/api/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
composer.json:
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "barryvdh/laravel-cors": "^0.11.4",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "^5.8.0",
        "laravel/tinker": "^1.0",
        "tymon/jwt-auth": "^1.0.0",
        "wboyz/laravel-enum": "^0.2.1"
    },
    "require-dev": {
        "fzaninotto/faker": "^1.8",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.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"
        ]
    }
}

app/Http/Kernel.php :

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Barryvdh\Cors\HandleCors::class,  // I ADDED THIS LINE !
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors',  // ALSO I ADDED THIS LINE - fount in net!
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

    
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

In config/auth.php :

<?php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt', // LINE WITH JWT as driver !
            'provider' => 'users',
        ],

    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    'password_timeout' => 10800,

];

config/cors.php :
Nov
25
2 months ago
Activity icon

Started a new Conversation Error Validating With Vee-validate 3

Hello, I try to implement vee-validate to my app and having

in /package.json :

 
{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",
    "vue-focus": "^2.1.0",
    "vue-js-modal": "^1.3.31",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vue2-filters": "^0.8.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  }
}

and

run npm install  

I made my login page according to https://codesandbox.io/s/rsmwq example with loginData defining as form data var:

<template>
    <div class="page_content_container">

        <div class="page_content_content col-xs-12 col-sm-10 col-md-6 mx-auto">

            <ValidationObserver ref="form">
                <form class="login" @submit.prevent="handleSubmit(onSubmit)">
                    <div class="card">

                        <div class="card-body card-block">

                            <div class="block_2columns_md m-3"> <!-- email -->

                                <div class="key_values_rows_label_13 m-0 p-0">
                                    <label class="col-form-label" for="email">Email:</label>
                                </div>
                                <div class="key_values_rows_value_13 m-0 p-0">
                                    <div class="col-12">
                                        <div class="input-group">
                                            <div class="input-group-addon">
                                                <i :class="'i_link '+getHeaderIcon('email')"></i>
                                            </div>
                                            <ValidationProvider
                                                    rules="required"
                                                    immediate
                                                    v-slot="{ errors }"
                                            >
                                                <input
                                                        v-model="loginData.email"
                                                        name="email"
                                                        id="email"
                                                        class="form-control editable_field" placeholder="Email Address"
                                                >
                                            </ValidationProvider>
                                        </div>
                                    </div>
                                </div>

                            </div> <!-- <div class="block_2columns_md m-0"> email -->

                            <div class="block_2columns_md m-3"> <!-- password -->

                                <div class="key_values_rows_label_13 m-0 p-0">
                                    <label class="col-form-label" for="password">Password:</label>
                                </div>
                                <div class="key_values_rows_value_13 m-0 p-0">
                                    <div class="col-12">
                                        <div class="input-group">
                                            <div class="input-group-addon">
                                                <i :class="'i_link '+getHeaderIcon('password')"></i>
                                            </div>
                                            <input type="password" v-model="loginData.password" id="password" name="password" class="form-control editable_field"
                                                   placeholder="Password"
                                            >
                                        </div>
                                    </div>
                                </div>

                            </div> <!-- <div class="block_2columns_md m-0"> password -->

                        </div> <!-- <div class="card-body card-block"> -->

                        <div class="card-footer m-0 p-0">
                            <div class="form-row m-1" style="justify-content: flex-end;">
                                <button type="reset" class="btn btn-danger btn-sm m-2">
                                    <i :class="'i_link '+getHeaderIcon('cancel')"></i>Home
                                </button>
                                <button type="submit" class="btn btn-success btn-sm m-2 ml-4 mr-4">
                                    <i :class="'i_link '+getHeaderIcon('save')"></i>Submit
                                </button>
                            </div>
                        </div>

                    </div> <!-- <div class="card"> -->

                </form>
            </ValidationObserver>

        </div> <!-- page_content_content -->

    </div> <!-- page_content_container -->
</template>

<script>
    import {bus} from '../../../src/main'
    import appMixin from '@/appMixin'

    import {ValidationObserver, ValidationProvider, localize, extend} from 'vee-validate'
    import en from 'vee-validate/dist/locale/en.json';
    import * as rules from 'vee-validate/dist/rules';

    localize('en', en);

    extend('required', {
        validate(value) {
            return {
                required: true,
                valid: ['', null, undefined].indexOf(value) === -1
            };
        },
        computesRequired: true
    });

    export default {
        name: 'loginPage',

        components: {
            ValidationObserver, ValidationProvider
        },

        data() {
            return {
                loginData: {
                    email: '',
                    password: ''
                },
                error: null,
                site_name: process.env.VUE_APP_SITE_NAME
            }
        },

        mixins: [appMixin],


        methods: {
            onSubmit() {

                    this.$refs.form.validate().then(success => {
                        if (!success) {
                            return;
                        }

                        alert('Form has been submitted!');

                        this.firstName = this.lastName = this.email = '';

                        this.$nextTick(() => {
                            this.$refs.form.reset();
                        });
                    });
            } // onSubmit

        }, // methods: {

        computed: {
            authError() {
                return this.$store.getters.authError
            }
        } // computed: {
    }

</script>

But clickinb on Submit button I got error:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "handleSubmit" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

and I do not see what is wrong with my code ?

Thanks!

Nov
22
2 months ago
Activity icon

Started a new Conversation How To Show Server's Errors In My @vue/cli App?

Hello, In laravel 5 / vuejs 2.6 app I used VeeValidate and VeeValidateLaravel libraries to validate data both on client and server, like:

      updateFacility() {
             this.is_page_updating = true
             axios({
                 method: (this.is_insert ? 'post' : 'patch'),
                 url: window.API_BACKEND_VERSION_LINK + '/admin/facilities' + (!this.is_insert ? "/" + this.facility_id : ''),
                 data: this.$data.facilityRow,
             }).then((response) => {
                 this.is_page_updating = false
                 this.showPopupMessage("Facilities", 'Facility ' + (this.is_insert ? 'added' : 'updated') + ' successfully !', 'success');
                 this.$router.push({path: '/admin/facilities'});
             }).catch((error) => {
                 console.error(error)
                 this.$setLaravelValidationErrorsFromResponse(error.response.data);
                 this.is_page_updating = false
                 this.showPopupMessage("Facilities", 'Error ' + (this.is_insert ? 'adding' : 'updating') + ' facility !', 'warn');
             });

and when I got server's errors(like not unique name field) server's error was shown in my app too.

Now with @vue/cli 4.0.5 / vuex "^3.0.1" I make saving of data on different Laravel(6) REST API app, like :

register ({ commit }, user) {
   return new Promise((resolve, reject) => {
     commit('auth_request')
     let apiUrl = process.env.VUE_APP_API_URL
     axios({ url: apiUrl + '/register', data: user, method: 'POST' })
       .then(resp => {
         const token = resp.data.token
         const user = resp.data.user
         localStorage.setItem('token', token)
         axios.defaults.headers.common['Authorization'] = token
         commit('auth_success', token, user)
         resolve(resp)
       })
       .catch(err => {
         console.error(err)
         // this.$setLaravelValidationErrorsFromResponse(err.response.data)
         commit('auth_error', err)
         localStorage.removeItem('token')
         reject(err)
       })
   })
 } // register ({ commit }, user) {

and in the console of my browser(network tab) I see error :

{"error":{"email":["The email has already been taken."]}}

But this error in not filled in my vueErrorsList error and in console of my browser I see : https://imgur.com/a/Z3RYiVm If to uncomment line:

  this.$setLaravelValidationErrorsFromResponse(err.response.data)

In the console I see erres :

POST http://local-ctasks-api.com/api/register 401 (Unauthorized)
index.js?4360:92 Error: Request failed with status code 401
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:59)
eval @ index.js?4360:92
Promise.catch (async)
eval @ index.js?4360:90
register @ index.js?4360:78
wrappedActionHandler @ vuex.esm.js?2f62:747
dispatch @ vuex.esm.js?2f62:438
boundDispatch @ vuex.esm.js?2f62:332
register @ Register.vue?0103:218
submit @ Register.vue?73da:27
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1854
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6911
index.js?4360:93 Uncaught (in promise) TypeError: _this2.$setLaravelValidationErrorsFromResponse is not a function
    at eval (index.js?4360:93)

In src/main.js I have defined :

import * as VeeValidate from 'vee-validate'
import VeeValidateLaravel from 'vee-validate-laravel' // https://github.com/RobertGlynWilliams/vee-validate-laravel

import { settingsTimeZone } from './../app.settings.js'

const veeValidateConfigArray = { // https://github.com/logaretm/vee-validate
  errorBagName: 'vueErrorsList', // change if property conflicts
  fieldsBagName: 'fields',
  delay: 0,
  locale: 'en',
  dictionary: null,
  strict: true,
  classes: false,
  classNames: {
    touched: 'touched', // the control has been blurred
    untouched: 'untouched', // the control hasn't been blurred
    valid: 'valid', // model is valid
    invalid: 'invalid', // model is invalid
    pristine: 'pristine', // control has not been interacted with
    dirty: 'dirty' // control has been interacted with
  },
  events: 'input|blur',
  inject: true,
  validity: false,
  aria: true
}
Vue.use(VeeValidate, veeValidateConfigArray)
Vue.use(VeeValidateLaravel)

Which is valid way to show server's errors in my @vue/cli app ?

in package.json :

{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "vee-validate": "^2.2.5",
    "vee-validate-laravel": "^1.1.0",
    "vue": "^2.6.10",
    "vue-focus": "^2.1.0",
    "vue-js-modal": "^1.3.31",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-eslint": "^4.0.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "@vue/eslint-config-standard": "^4.0.0",
    "babel-eslint": "^10.0.3",
    "bootstrap": "^4.3.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  }
}

Thanks!

Nov
16
3 months ago
Activity icon

Started a new Conversation Got Uncaught (in Promise) NavigationDuplicated Error On Invalid Credentials

Hello, In laravel 5 / vuejs 2.6 app I have login form and on login failure I got error :

app.js?dt=1571914585:131483 Uncaught (in promise) NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated", message: "Navigating to current location ("/login") is not allowed", stack: "Error↵    at new NavigationDuplicated (http://127.…/127.0.0.1:8084/js/app.js?dt=1571914585:148080:12"}

I found where error is triggered! In my resources/js/app.js I have :

const router = new VueRouter({
    routes,
    mode: 'history'
});

checkAuthorization(store, router);
axios.interceptors.response.use(null, (error) => {

    if (error.response.status == 401) {

        store.commit('setLogout');
        
        console.log("0012 route.path::")
        console.log( $route )      // THAT OUTPUTS NOTHING
        console.log( $route.path ) // THAT OUTPUTS NOTHING

        router.push('/login');  // THAT RISE ERROR !
    }

    return Promise.reject(error);
});


const app = new Vue({
    el: '#app',
    router,
    store,
    bus,
    components: {
        mainapp, appheader, appfooter, navigation
    },
});


router.afterEach(( to, from ) => {
    bus.$emit('page_changed', from, to);
});

and line

router.push('/login');

raise this error, but I do not know how can I can I check current path

Here https://stackoverflow.com/questions/57837758/navigationduplicated-navigating-to-current-location-search-is-not-allowed/58439497#58439497 I found about possible decision and I read :

const path = `/products/${id}`
if ($route.path !== path) this.$router.push(path)
Note: $route is an object provided by vue-router to every component

But $route is empty. I think I need to get $route.path inside of axios.interceptors.response.use How can I do it ?

Nov
09
3 months ago
Activity icon

Started a new Conversation Error Is Raised On Seeding With Index Defined

Hello, In laravel 5.8 app I created migration file with 1 field and 1 index added

class SubscriptionsTableAddIsFreeField extends Migration
{
    public function up()
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->boolean('is_free')->default(false)->after('source_service_subscription_id');
            $table->index([ 'user_id', 'is_free' ], 'subscriptions_user_id_is_free_index');

        });
    }

    public function down()
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropForeign('subscriptions_user_id_is_free_index');
            $table->dropColumn('is_free');
        });
    }

But running command

php artisan migrate:refresh --seed

I got error :

: SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists (SQL: alter table `vt2_subscriptions` drop foreign key `subscriptions_user_id_is_free_index`)

  at /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119

  2   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117

  Please use the argument -v to see more details.

What is wrong in defintion of my migration?

I know that laravel migration has methods

if (Schema::hasTable('users')) {
    //
}

if (Schema::hasColumn('users', 'email')) {
    //
}

But can I check indexes?

Thanks!

Nov
04
3 months ago
Activity icon

Replied to Using Laravel Cashier How To Fill Ends_at Fields?

Could, you, please share your expierence trial_ends_at and ends_at timestamp fields using Laravel Cashier ?

Nov
03
3 months ago
Activity icon

Started a new Conversation Using Laravel Cashier How To Fill Ends_at Fields?

Hello, In my Laravel 5.8 app using Laravel Cashier "^10.3" I have

subscriptions table, with trial_ends_at and ends_at timestamp fields and I want to clarify what are they for ? I suppose that trial_ends_at must be filled when user select Free(trial) subscription and ends_at must be filled when user select non free subscription and making subscription I do :

        $subscription_days_count       = config('app.subscription_days_count', 31);
        $free_subscription_days_count  = config('app.free_subscription_days_count', 31);
        $subscription_product_name     = config('app.subscription_product_name');

            $newSubscription = $user->newSubscription($subscription_product_name,
                $sourcePaymentPackage->stripe_plan_id)->create($requestData['purchaseDetails']['payment_token']);

            // I added 2 additive fields to subscriptions table and fill them 
            $newSubscription->source_payment_package_id = $requestData['purchaseDetails']['source_payment_package_id'];
            $newSubscription->is_free                   = $sourcePaymentPackage->is_free;
            if ( $sourcePaymentPackage->is_free ) {
                $newSubscription->trial_ends_at = Carbon::now()->addDays($free_subscription_days_count);
            } else {
                $newSubscription->ends_at = Carbon::now()->addDays($subscription_days_count);
            }
            $newSubscription->save();

But cancelling subscriptions with method:

            $ret = $userProfile->subscription($subscription_product_name)->cancelNow();

I see that in subscriptions table field ends_at is set to time of cancellation above. Is it configurable? Which way have I to follow ?

Thanks!

Oct
23
3 months ago
Activity icon

Started a new Conversation Defining Events In Stripe For Laravel Cashier

Hello, In my Laravel 5.8 app using Laravel Cashier I make subscription to Stripe Products and I want to create hooks for some events

Here https://laravel.com/docs/5.8/billing#handling-stripe-webhooks I found only some events I not I need

I need to create hooks for next events :

  1. user made payment(checkout or subscription)
  2. User created subscription
  3. User's subscription will expire in 3,2,1 day.

In stripe dashboard I added hook with some callback url and events: https://prnt.sc/pmwatm

But looks like that is not all I need. Which events have I to use? Please privide link to events and how Laravel Cashier can be used with it ?

Thanks!

Oct
20
3 months ago
Activity icon

Started a new Conversation How To Check If User Is Subscribed To Some Stripe's Plan

Hello, In my Laravel 5.8 I search how to check if used is subscribed to some stripe's plan. I make subscription with stripe and I have installed

        "stripe/stripe-php": "^7.2",
        "laravel/cashier": "^10.3",

In app/User.php :

use Laravel\Cashier\Billable;
...
class User extends Authenticatable implements MustVerifyEmail
{
    use Billable;
    use Notifiable;

When I ned to subscribe to stripe's plan I make :

      $ret= $user->newSubscription('main', 'plan_ID')->create($requestData['purchaseDetails']['payment_token']);
where plan_ID is id of plan registered at stripe dashboard

Searching for checking subscribed method I found and tried:

                if( Auth::user()->subscribed( 'main', $item['stripe_plan_id'] ) ) {
                    die("-1 XXZ ===  subscribed");
                }

I tried stripe_plan_id or stripe_plan_name - but failed in both cases

Also I tried :

$user->subscriptions

but it returned empty array. In Stripe dashboard I see that logged user is subscribed to stripe_plan_id... Which way is correct ?

Thanks!