mastermindlegion

mastermindlegion

Member Since 7 Months Ago

Experience Points
1,990
Total
Experience

3,010 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
6
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
1,990 XP
Oct
16
1 week ago
Activity icon

Replied to Cashier Coupon Not Found

@srasch Hello there and thanks for the reply. Here is the response from the stripe: Coupon name halfprice is there....

{
  "object": "list",
  "data": [
    {
      "id": "bhDLNZj7",
      "object": "coupon",
      "amount_off": 3000,
      "created": 1602780400,
      "currency": "czk",
      "duration": "once",
      "duration_in_months": null,
      "livemode": false,
      "max_redemptions": null,
      "metadata": {
      },
      "name": "halfprice",
      "percent_off": null,
      "redeem_by": null,
      "times_redeemed": 0,
      "valid": true
    }
  ],
  "has_more": false,
  "url": "/v1/coupons"
}
Oct
15
1 week ago
Activity icon

Started a new Conversation Cashier Coupon Not Found

Hello guys, I'm using Laravel Cashier with Stripe and I have a problem regarding to the coupon applying. If i'm trying to use a coupon I always get response coupon not found 'halfprice'

  1. I have created coupon in Stripe
halfprice
  1. Im sucesfully sending a coupon from to the backend a

3.Backend Handling


       $this->validate($request, [
           'token' => 'required',
           'plan' => 'required|exists:plans,slug',
           'coupon' => 'nullable'
       ]);

     $cleaned_plan =  Purifier::clean($request->plan);
     $request_plan = strip_tags($cleaned_plan);

     $cleaned_token = Purifier::clean($request->token);
     $request_token = strip_tags($cleaned_token);


     $plan = Plan::where('slug', $request_plan)->first();

        auth()->user()->newSubscription('pro', $plan->stripe_id)
       ->withCoupon($request->coupon)
       ->create($request_token);

Oct
11
1 week ago
Activity icon

Replied to Regex Check

@bestmomo Thank you, dear Regex Master

Activity icon

Started a new Conversation Regex Check

Hello guys,

do you have any idea, how to make a regex check for letters and dots (.), commas (,). Currently I have regex check, which searches the string only for letters, but I need to add commas and dots. Thanks very much.

Here is the code:

const reg = /^[A-Za-z]+$/
Sep
21
1 month ago
Activity icon

Started a new Conversation Laravel Pagination And Resources Problem

Hello guys, I have problem regarding to the pagination, where resuls are only displayed for the ?page=1 and if I try different page, only empty [] is returned.

I guess I have to paginate AdvertisementResource

Api Route:

Route::get('/categories/{advertisementCategory:slug}', 'Advertisements\[email protected]');

Controller:

 public function indexOneCategory(AdvertisementCategory $advertisementCategory)
    {
            $categoryID = $advertisementCategory->id;
            return AdvertisementCategoryResource::collection(AdvertisementCategory::where('id', $categoryID )->paginate(1));
    }

AdvertisementCategoryResouce:

 public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'advertisements' => AdvertisementResource::collection($this->advertisements),
        ];
    }

AdvertisementResource

    public function toArray($request)
    {
        return[
            'id' => $this->id,
            'category' => $this->categoryParent(),
            'advertisement_category_id' => $this->advertisement_category_id,
            'user_id' => $this->user_id,
            'name' => $this->name,
            'slug' => $this->slug,
            'location' => $this->location,
            'body' => $this->body,
            'views' => $this->views,
            'order' => $this->order,
            'user' => new UserAdvertisementResource($this->user),


        ];
    }

Result?page=2

{
  "data": [],
  "links": {
    "first": "http:\/\/www.pravopress.test:8080\/api\/categories\/test?page=1",
    "last": "http:\/\/www.pravopress.test:8080\/api\/categories\/test?page=1",
    "prev": "http:\/\/www.pravopress.test:8080\/api\/categories\/test?page=1",
    "next": null
  },
  "meta": {
    "current_page": 2,
    "from": null,
    "last_page": 1,
    "path": "http:\/\/www.pravopress.test:8080\/api\/categories\/test",
    "per_page": 1,
    "to": null,
    "total": 1
  }
}

Result ?page=1

{
  "data": [
    {
      "id": 21,
      "name": "test",
      "slug": "test",
      "advertisements": [
        {
          "id": 1,
          "category": "test",
          "advertisement_category_id": 21,
          "user_id": 1,
          "name": "Test advertisement",
          "slug": "test-advertisement",
          "location": "Prague",
          "body": "lorem ipsum ",
          "views": 1,
          "order": 1,
          "user": {
            "id": 1,
            "full_name": "Martin Chalupa",
            "full_name_and_degree": "JUDr., PhDr. Martin Chalupa LLM.",
            "email": "[email protected]",
            "role": "empty",
            "avatar": "http:\/\/www.pravopress.test:8080\/storage\/avatars\/default.png",
            "profile": {
              "id": 1,
              "user_id": 1,
              "description": "If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:",
              "working_on": "Poskytování nejlepších služeb",
              "learning": "Svěřenské fondx' => 'Překročena kapthis.submitSuccess = truethis.submitSuccess = truethis.submitSuccess = truethis.suthis.submitSuccess = truethis.submitSuccess = truethis.submitSuccess = truethis.submitSuccess = truebmitSuccess = truethis.submitSuccess = truethis.submitSuccess = true",
              "interests": "Právo, sport, programming",
              "location": "Praha this.handleErrors(e) this.handleErrors(e) this.handleErrors(e) this.handleErrors(e)",
              "advocate_office": "JUDr. Luboš Chalupa",
              "job_search": 1,
              "teaching": 0,
              "front_degree": "JUDr., PhDr.",
              "back_degree": "LLM.",
              "facebook": null,
              "twiter": null,
              "website": null,
              "email": "[email protected]",
              "show_email": 1,
              "created_at": "2020-09-02T14:49:35.000000Z",
              "updated_at": "2020-09-07T07:40:11.000000Z"
            },
            "created_at_diff": "před 2 týdny",
            "updated_at": "2020-09-02T16:39:22.000000Z"
          }
        },
        {
          "id": 3,
          "category": "test",
          "advertisement_category_id": 21,
          "user_id": 2,
          "name": "Juuu",
          "slug": "juuu",
          "location": null,
          "body": null,
          "views": 1,
          "order": 1,
          "user": {
            "id": 2,
            "full_name": "New user New",
            "full_name_and_degree": " New user New ",
            "email": "[email protected]",
            "role": "empty",
            "avatar": "http:\/\/www.pravopress.test:8080\/storage\/avatars\/default.png",
            "profile": {
              "id": 2,
              "user_id": 2,
              "description": null,
              "working_on": null,
              "learning": null,
              "interests": null,
              "location": null,
              "advocate_office": null,
              "job_search": 0,
              "teaching": 0,
              "front_degree": null,
              "back_degree": null,
              "facebook": null,
              "twiter": null,
              "website": null,
              "email": null,
              "show_email": 0,
              "created_at": "2020-09-04T13:31:29.000000Z",
              "updated_at": "2020-09-04T13:31:29.000000Z"
            },
            "created_at_diff": "před 2 týdny",
            "updated_at": "2020-09-04T13:31:28.000000Z"
          }
        },
        {
          "id": 6,
          "category": "test",
          "advertisement_category_id": 21,
          "user_id": 2,
          "name": "Listing new",
          "slug": "listing-new",
          "location": null,
          "body": null,
          "views": 1,
          "order": 1,
          "user": {
            "id": 2,
            "full_name": "New user New",
            "full_name_and_degree": " New user New ",
            "email": "[email protected]",
            "role": "empty",
            "avatar": "http:\/\/www.pravopress.test:8080\/storage\/avatars\/default.png",
            "profile": {
              "id": 2,
              "user_id": 2,
              "description": null,
              "working_on": null,
              "learning": null,
              "interests": null,
              "location": null,
              "advocate_office": null,
              "job_search": 0,
              "teaching": 0,
              "front_degree": null,
              "back_degree": null,
              "facebook": null,
              "twiter": null,
              "website": null,
              "email": null,
              "show_email": 0,
              "created_at": "2020-09-04T13:31:29.000000Z",
              "updated_at": "2020-09-04T13:31:29.000000Z"
            },
            "created_at_diff": "před 2 týdny",
            "updated_at": "2020-09-04T13:31:28.000000Z"
          }
        }
      ]
    }
  ],
  "links": {
    "first": "http:\/\/www.pravopress.test:8080\/api\/categories\/test?page=1",
    "last": "http:\/\/www.pravopress.test:8080\/api\/categories\/test?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http:\/\/www.pravopress.test:8080\/api\/categories\/test",
    "per_page": 1,
    "to": 1,
    "total": 1
  }
}
Sep
18
1 month ago
Activity icon

Started a new Conversation Nested V-for Loop

Hello friends, I got problem-related to the v-for loop. I'm trying to loop over multiple objects/arrays using v-for. It successfully loops over but renders multiple numbers of empty div above. My page:

     <template v-else>
            <div class="">
                <h1>{{advertisementsCategory.name}}</h1>
                <template v-for='advertisements in advertisementsCategory' >

                     <advertisements-block v-for='advertisement in advertisements' :advertisement='advertisement' :key='advertisement.id' />

                </template>
            </div>
         </template>

than passing prop to the component:

<div class=" bg-white flex">
       <div class="" >

           {{ advertisement.name  }}
        </div>

       </div>

Result is xxxx empty divs:

</div></div>

Thanks for any suggestions

Sep
07
1 month ago
Activity icon

Started a new Conversation Remove Plugin From CkEditor Vue

Hello guys, do you have any idea, how to delete plugin Image from the CkEditor and toolbar itself? I used removePlugins as is stated in the docs...https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/configuration.html Here is the code

<template>
   <ckeditor
      :editor="editor"
      :value="value"
      :config="editorConfig"
     @input="ev => $emit('input', ev)"
   />
</template>

<script>
import CKEditor from '@ckeditor/ckeditor5-vue'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'


export default {
  name: 'RichEditor',
  props: {
    value: [String],
    removePlugins: [  'Image', 'ImageToolbar' ],
    image: {},
    options: {
      type: [Object],
      default: () => {
        toolbar: [ 'bold', 'italic', 'heading', 'link' , 'bulletedList', 'numberedList', 'blockQuote'  ]

      }
    }
  },
  components: {
    ckeditor: CKEditor.component
  },
  data() {
    return {
      editor: ClassicEditor,
      editorConfig: this.options,

    }
  },
  mounted() {
    console.log('plugins list', ClassicEditor.builtinPlugins.map( plugin => plugin.pluginName ))
  }
}
</script>


Aug
29
1 month ago
Activity icon

Commented on Testing Avatar Uploads: Part 2

Hey there, the process is in the documentation -> https://laravel.com/docs/7.x/filesystem#the-public-disk

Jul
24
3 months ago
Activity icon

Started a new Conversation Editors And Chicago Style Quotations

Dear friends ,

Am I able to quote as this in Editor? Thanks in advance.

Example:

https://www.scribbr.com/citing-sources/citation-styles/

Chicago A example (book)
Chicago in-text citation
The book uses success stories from the authors’ own lived experiences to make the case for a creative revolution in the business world.1 ->>> integer should be small and above

UnderLine is this:

Chicago style footnote
1 Dave Stewart and Mark Simmons, The Business Playground: Where Creativity and Commerce Collide (Berkeley: New Riders Press, 2010).

Activity icon

Replied to Compare Two Collections

Thanks for your reply. I managed to solve it as follows:

   $favorites = Favorite::where('user_id', $this->id)
                    ->where('favorited_type', 'App\Article')
                    ->get();

        $arr = $favorites->map(function ($item, $key) {
            return $item->favorited_id;
        });
        $favorited = collect($arr);


        $articles = Article::whereIn('id', $favorited)
                ->get();

        return $articles;
Activity icon

Started a new Conversation Compare Two Collections

Greetings friends, I got question regarding to the comparing two collections. My goal is to return only articles->id, where is same $favorites->favorited_id.

Thanks

   $favorites = Favorite::where('user_id', $this->id)
                    ->where('favorited_type', 'App\Article')
                    ->get();
        $userArticles = $this->articles;

        foreach ($userArticles as $article) {
            foreach ($favorites as $favorite) {
                if($article->id == $favorite->favorited_id) {
                    echo $article;
                }
            }
            }
Jun
19
4 months ago
Activity icon

Started a new Conversation Search Results To Collection Resource

Hello guys, I want to search for a model using Scout and Algolia driver. I have a controller like this:

    public function index(Request $request)
    {
      //  return Article::search($request->q)->get(); ->>>>>works

        return ArticleResource::collection(Article::search($request->q)->get()); –>>>does not work

    }

The first solution returns successfully results based on search, which is provided in $request->g = lorem ipsum -> than its well searches model, where lorem ipsum is presented.

but I would like to have returned ArticleResource instead of the pure model....

Thanks

Jun
12
4 months ago
Activity icon

Replied to Increment A Value In DB

Or could I be able to make an update as this?

   DB::table('articles')
            ->where('id', $event->article->id)
            ->update(['views' => ++]); -> something similiar 
Activity icon

Replied to Increment A Value In DB

@michaloravec hello there,

here is the listener

RAW method works, but for now is commented

   public function handle($event)
    {
        // DB::table('articles')
        //     ->where('id', $event->article->id)
        //     ->update( ['views' => DB::raw('views + 1')]);

        $event->article->increment('views', 1);
    }
Activity icon

Replied to Increment A Value In DB

@james_moore here is the api response. But still, increment is not being saved to the db

 "data": {
    "id": 1,
    "user": {
      "id": 1,
      "full_name": "Martin Chalupa",
      "email": "[email protected]"
    },
    "slug": "robb-harvey-1",
    "name": "Robb Harvey",
    "body": "Autem est velit cum qui tenetur neque quo impedit. Sed eius minima alias aliquid ut qui dolore. Dolor quisquam aperiam suscipit amet numquam sit. Ipsa itaque dolores est ut.",
    "countFavorite": 3,
    "isFavorited": false,
!!!
    "views": 1, -> not being saved in DB
!!!
    "comments": 0,

... and so on
Activity icon

Replied to Increment A Value In DB

@james_moore hello there, I thank you for your response.

Regarding event. I'm not able to use $article model without $event->article.

Your code I have used inside my controller - just to check if it's functional and there is no increment being saved in DB... Here is the code:

    public function index(Article $article, Request $request)
    {
        // 1. Article has been showed - increment a views table

      //  event(new ArticleHasBeenViewedEvent($article));
      //
        $article->increment('views', 1);
        $article->save();

        //2. LOAD relationships
        $article->load(['user', 'tags']);

        // 3. Return resource
        return new ArticleResource($article);
    }
Activity icon

Started a new Conversation Increment A Value In DB

Hello guys, I got an event listener for incrementing views table in DB. The raw method works fine, result is successfully saved in DB, but I would like to avoid using raw method...

  DB::table('articles')
            ->where('id', $event->article->id)
            ->update( ['views' => DB::raw('views + 1')]);

I have tried increment() as is shown here. Views table is not being updated like using raw method.

$event->article->increment('views', 1);

My controller

   public function index(Article $article, Request $request)
    {
        // 1. Article has been showed - increment a views table

        event(new ArticleHasBeenViewedEvent($article));

        //2. LOAD relationships
        $article->load(['user', 'tags']);

        // 3. Return resource
        return new ArticleResource($article);
    }
Jun
01
4 months ago
Activity icon

Replied to Pagination Data[] Changes To Data{}

It's working :) what was the difference with pagination? Thanks

Activity icon

Replied to Pagination Data[] Changes To Data{}

@tykus hello there, for now yes; I got only three articles there so it is for testing. Gonna change it later on

Activity icon

Started a new Conversation Pagination Data[] Changes To Data{}

Hello guys, I got a problem regarding pagination. When i'm at the first ?page=1 data is [ ] and at the ?page=2 data is {}. Thank you very much I don't know how to proceed. Here is my controller:

public function index(Request $request, Tag $tag)
    {
     $collection = ArticleResource::collection($tag->articles);
     return $collection->paginate(1);
    }

?page=1 response is also quite weird is that there is no meta object { } being created...

{
"current_page": 1,
"data": [
{
"id": 1,
"user": {
"id": 1,
"full_name": "Martin Chalupa",
"email": "[email protected]"
},
"slug": "ethan-howell-v-1",
"name": "Ethan Howell V",
"body": "Non quo sit ipsum placeat dignissimos. Et repellendus sequi consequatur aut veritatis officia hic. Dolores voluptate et et et velit sit consequatur.",
"tags": [
{
"id": 1,
"slug": "php",
"name": "PHP"
},
{
"id": 2,
"slug": "laravel",
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-27T09:35:49.000000Z",
"updated_at": "2020-05-27T09:35:49.000000Z"
}
}
],
"first_page_url": "articles?page=1",
"from": 1,
"last_page": 2,
"last_page_url": "articles?page=2",
"next_page_url": "articles?page=2",
"path": "articles",
"per_page": 1,
"prev_page_url": null,
"to": 1,
"total": 2
}

?page=2 response is:

{
"current_page": 2,
"data": {
"1": {
"id": 2,
"user": {
"id": 1,
"full_name": "Martin Chalupa",
"email": "[email protected]"
},
"slug": "kayleigh-kshlerin-1",
"name": "Kayleigh Kshlerin",
"body": "Aperiam ipsum quos atque dolore. Rem ea quos dolor ad commodi recusandae nihil. Rem omnis adipisci velit quos. Eos maiores eos et omnis aut sit accusantium. Quo quod nostrum veritatis ut ex.",
"tags": [
{
"id": 3,
"slug": "ruby",
"name": "Ruby"
},
{
"id": 4,
"slug": "javascript",
"name": "Javascript"
},
{
"id": 1,
"slug": "php",
"name": "PHP"
},
{
"id": 2,
"slug": "laravel",
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-27T09:35:49.000000Z",
"updated_at": "2020-05-27T09:35:49.000000Z"
}
}
},
"first_page_url": "articles?page=1",
"from": 2,
"last_page": 2,
"last_page_url": "articles?page=2",
"next_page_url": null,
"path": "articles",
"per_page": 1,
"prev_page_url": "articles?page=1",
"to": 2,
"total": 2
}
Activity icon

Replied to Query Nested Collection

yes, it is working cheef :). Thank you and wish you a great day

Activity icon

Started a new Conversation Query Nested Collection

Greetings guys, I got a problem with querying the collection instance.

I have my controller where I want to return only Articles where tags ['slug' => 'php'] is equal to route bounded model $tag->slug = 'php'. So only return articles where a slug is route bounded slug.

 public function index(Request $request, Tag $tag)
    {

        $articles = ArticleResource::collection(
            Article::get()
         );
        return $articles;
    }

returned slug = php

return $tag->slug;

Response example:

data: [
{
"id": 1,
"user": {
"id": 1,
"full_name": "Martin Chalupa",
"email": "[email protected]"
},
"slug": "ethan-howell-v-1",
"name": "Ethan Howell V",
"body": "Non quo sit ipsum placeat dignissimos. Et repellendus sequi consequatur aut veritatis officia hic. Dolores voluptate et et et velit sit consequatur.",
"tags": [
{
"id": 1,
"slug": "php",
"name": "PHP"
},
{
"id": 2,
"slug": "laravel",
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-27T09:35:49.000000Z",
"updated_at": "2020-05-27T09:35:49.000000Z"
}
},
]
Activity icon

Replied to Query Nested Collection

@tykus hello there, I would like to have a returned collection of articles where: inside the collection tag: [ 'slug' => 'php' ] is equal to $tag->slug = 'php' from model bound route

Activity icon

Started a new Conversation Query Nested Collection

Hello friends, I got problem with quering the collection instance.

I have my controller where I want to return only $tag->slug, which is equal to $articles->tags->slug. How to solve this problem? thank you

 public function index(Request $request, Tag $tag)
    {
        $articles = ArticleResource::collection(
            Article::get()
         );
        return $articles;
    }

Currently my return is :

data: [
{
"id": 1,
"user": {
"id": 1,
"full_name": "Martin Chalupa",
"email": "[email protected]"
},
"slug": "ethan-howell-v-1",
"name": "Ethan Howell V",
"body": "Non quo sit ipsum placeat dignissimos. Et repellendus sequi consequatur aut veritatis officia hic. Dolores voluptate et et et velit sit consequatur.",
"tags": [
{
"id": 1,
"slug": "php",
"name": "PHP"
},
{
"id": 2,
"slug": "laravel",
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-27T09:35:49.000000Z",
"updated_at": "2020-05-27T09:35:49.000000Z"
}
},
]
May
27
4 months ago
Activity icon

Awarded Best Reply on Access MorphedByMany

@mkshingrakhiya hey there, I thank you for trying. Here is what was wrong there with the code:

Tag model:

public function articles()
    {
        return $this–>morphedByMany(Article::class, 'taggable' ) ->>>>>>>>>>> there is extra space! haha;
    }

Thanks a lot, cheers

Activity icon

Replied to Access MorphedByMany

@mkshingrakhiya hey there, I thank you for trying. Here is what was wrong there with the code:

Tag model:

public function articles()
    {
        return $this–>morphedByMany(Article::class, 'taggable' ) ->>>>>>>>>>> there is extra space! haha;
    }

Thanks a lot, cheers

Activity icon

Replied to Access MorphedByMany

Yes my friend, thanks for reply :). Here it is:

Tag model :

<?php

namespace App;

use App\Article;
use App\Taggable;
use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
// protected $primaryKey = 'id';
//
 protected $fillable = [
        'name',
     ];

    // Relationships

    public function articles()
    {
        return $this–>morphedByMany(Article::class, 'taggable' );
    }

    // public function related()
    // {
    //     return $this->hasMany(Taggable::class);
    // }

}

The first return is for testing, if relationship is being loaded

<?php

namespace App\Http\Controllers\Tags;

use App\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\SingleResource\TagResource;

class TagController extends Controller
{
    public function index(Request $request, Tag $tag)
    {
        return $tag->load(['articles']);
        return new TagResource($tag);
    }
}

Activity icon

Replied to Access MorphedByMany

It does

Activity icon

Started a new Conversation Access MorphedByMany

do you know how to access morphedByMany relationship?

I got this api route, where when I access this path I will be presented with all articles where certain TAG is attached:

Route::get('/tags/{tag:slug}', 'Tags\[email protected]');

Tag model:

  public function articles()
    {
        return $this–>morphedByMany(Article::class, 'taggable' );
    }

Controller:

return $tag->load(['articles']);

I got this error: Call to undefined function App\morphedByMany()

Activity icon

Started a new Conversation Access MorphedByMany Relationship

Greetings guys,

do you know how to access morphedByMany relationship?

I got this api route, where when I access this path I will be presented with all articles where certain TAG is attached:

Route::get('/tags/{tag:slug}', 'Tags\[email protected]');

Tag model:

  public function articles()
    {
        return $this–>morphedByMany(Article::class, 'taggable' );
    }

Controller:

return $tag->load(['articles']);

I got this error: Call to undefined function App\morphedByMany()

May
26
4 months ago
Activity icon

Awarded Best Reply on Add Meta To Paginated Collection

hey there, problem was that I wasn't using static collection. This example works well:

        return  ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3));

this doesn't work, meta is not being included:

  $collection = new ArticlesCollection(
          ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3))
        );
         return $collection;
Activity icon

Replied to Add Meta To Paginated Collection

hey there, problem was that I wasn't using static collection. This example works well:

        return  ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3));

this doesn't work, meta is not being included:

  $collection = new ArticlesCollection(
          ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3))
        );
         return $collection;
Activity icon

Replied to Paginate Collection

@michaloravec hey there, problem was that I wasn't using static collection. This example works well:

        return  ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3));

Activity icon

Awarded Best Reply on Eager Load Laravel Resource

This is how I solved the above query problem:

    public function index(Request $request, User $user)
    {
        $user->load(['articles', 'articles.tags', 'articles.user']);
        return response()->json([
            new UserResource($user)
        ]);
    }
Activity icon

Replied to Eager Load Laravel Resource

This is how I solved the above query problem:

    public function index(Request $request, User $user)
    {
        $user->load(['articles', 'articles.tags', 'articles.user']);
        return response()->json([
            new UserResource($user)
        ]);
    }
Activity icon

Replied to Eager Load Laravel Resource

@snapey with this method I got 26 queries

 $user->with('articles');
        return response()->json([
            new UserResource($user)
        ]);
Activity icon

Replied to Eager Load Laravel Resource

Thanks for your reply.

Here is my ArticlesResource:

 $data = [
            'id' => $this->id,
            'user' => new UserArticleResource($this->user),
            'slug' => $this->slug,
            'name' => $this->name,
            'body' => $this->body,
            //'tags' => TagResource::collection($this->tags),
            //'eager_tags' => TagResource::collection($this->whenLoaded('tags')),
            'tags' => TagResource::collection($this->tags),
            'time' => [
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ],
        ];

And this is my controller for just getting articles. I have just 4 queries, this is where it's being eager loaded properly:

  $collection = new ArticlesCollection(
          ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3))
        );

       //  return $collection;
        return response()->json([
               $collection

        ]);
Activity icon

Started a new Conversation Eager Load Laravel Resource

Greetings friends, I got problem with eager loading my json resource. For some reason I end up with a great number of executed queries...

My UserResource looks like this:

     return  [
            'id' => $this->id,
            'email' => $this->email,
            'info' => [
                 'first_name' => $this->first_name,
                 'last_name' => $this->last_name,
                 'full_name' => $this->first_name . ' ' . $this->last_name,
                 'gender' => $this->gender,
                 'url' => 'https://www.gravatar.com/avatar/' . md5(strtolower( trim($this->email)))
            ],
            // Eeager Load
            'articles' => ArticleResource::collection($this->articles),
            //'eager articles' => $this->articles,
            'time' => [
                 'created_at' => $this->created_at,
                 'updated_at' => $this->updated_at,
            ]
        ];

And my controller is this:

  public function index(Request $request, User $user)
    {
        $user->with('articles');
        return response()->json([
            new UserResource($user)
        ]);
    }


May
25
4 months ago
Activity icon

Started a new Conversation Add Meta To Paginated Collection

Hello guys, could you please help me with adding meta to paginated collection?

Here is my provider ExtendCollectionServiceProvider:

    public function boot()
    {
                Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page', $queryParams= []) {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

            return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
                'path' => 'articles',
                'pageName' => $pageName,
                'query' => $queryParams
            ]);
        });
    }

Here is controller:

 public function index()
    {
     $collection = new ArticlesCollection(
      ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3)));
     return $collection;
    }

And I got this response, pagination works. I can swap pages, but there is no meta. I dont know, which is the last...

{
"data": [
{
"id": 1,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "davonte-sawayn-1",
"name": "1",
"body": "Aliquam placeat veritatis alias sed et inventore. Animi animi amet recusandae qui voluptates quidem. Eos qui culpa aut molestias.",
"tags": [
{
"id": 6,
"name": "testTag"
},
{
"id": 1,
"name": "PHP"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 2,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "lura-weimann-iii-1",
"name": "2",
"body": "Praesentium velit deserunt eaque quia consequatur dolor. Delectus nulla quasi in maiores. Et recusandae sed et magnam aperiam exercitationem dolor et.",
"tags": [
{
"id": 3,
"name": "Node"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 11,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "raphaelle-hudson-jr-1",
"name": "3",
"body": "Maiores in ullam error odio accusantium rerum aliquam. Numquam explicabo fugiat facilis natus accusantium. Non et perferendis fugit in quas ipsum voluptate sit.",
"tags": [],
"time": {
"created_at": "2020-05-06T12:18:51.000000Z",
"updated_at": "2020-05-06T12:18:51.000000Z"
}
}
]
}
Activity icon

Replied to Paginate Collection

@michaloravec Hello Michal, sorry for disturbing, but would you know how to add meta tags in this pagination?

Thank you very much. I'm certain it would help many people

This is my controller:

 $collection = new ArticlesCollection(
      ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3)));
     return $collection;
    }

This is my response:

{
"data": [
{
"id": 1,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "davonte-sawayn-1",
"name": "1",
"body": "Aliquam placeat veritatis alias sed et inventore. Animi animi amet recusandae qui voluptates quidem. Eos qui culpa aut molestias.",
"tags": [
{
"id": 6,
"name": "testTag"
},
{
"id": 1,
"name": "PHP"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 2,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "lura-weimann-iii-1",
"name": "2",
"body": "Praesentium velit deserunt eaque quia consequatur dolor. Delectus nulla quasi in maiores. Et recusandae sed et magnam aperiam exercitationem dolor et.",
"tags": [
{
"id": 3,
"name": "Node"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 11,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "raphaelle-hudson-jr-1",
"name": "3",
"body": "Maiores in ullam error odio accusantium rerum aliquam. Numquam explicabo fugiat facilis natus accusantium. Non et perferendis fugit in quas ipsum voluptate sit.",
"tags": [],
"time": {
"created_at": "2020-05-06T12:18:51.000000Z",
"updated_at": "2020-05-06T12:18:51.000000Z"
}
}
]
}
May
06
5 months ago
Activity icon

Replied to Paginate Collection

I will dig deep into it. Thanks anyways for replies and help :). have a great day

Activity icon

Replied to Paginate Collection

Code in ExtendCollectionServiceProvider:

  Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

            return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, 				$page, [
                'path' => 'articles',
                'pageName' => $pageName,
            ]);
        });

This is same as you said, didn't change anything

My controller:

 $collection = new ArticlesCollection(
      ArticleResource::collection(Article::with(['user', 'tags'])->get())->paginate(4));
     return $collection;

The first pagination ?page=1 returns:

response.data [
  {
    id: 1,
    user: {
      id: 1,
      full_name: 'test [email protected]',
      email: '[email protected]'
    },
    slug: 'davonte-sawayn-1',
    name: '1',
    body: 'Aliquam placeat veritatis alias sed et inventore. Animi animi amet recusandae qui voluptates quidem. Eos qui culpa aut molestias.',
    tags: [ [Object], [Object], [Object] ],
    time: {
      created_at: '2020-05-05T15:19:26.000000Z',
      updated_at: '2020-05-05T15:19:26.000000Z'
    }
  },
    ...... REST OF THE OBJECTS ....
]

I got array of objects as expected -> this is what I want, that s awesome,but

The returns after ?page= 2 and more always returns an object instead of arrays :( :

 {
  '5': {
    id: 11,
    user: {
      id: 1,
      full_name: 'test [email protected]',
      email: '[email protected]'
    },
    slug: 'raphaelle-hudson-jr-1',
    name: '3',
    body: 'Maiores in ullam error odio accusantium rerum aliquam. Numquam explicabo fugiat facilis natus accusantium. Non et perferendis fugit in quas ipsum voluptate sit.',
    tags: [],
    time: {
      created_at: '2020-05-06T12:18:51.000000Z',
      updated_at: '2020-05-06T12:18:51.000000Z'
    }
  }

  ...... the rest
}
Activity icon

Replied to Paginate Collection

@michaloravec hello, it is correctly formated now, if you want to have a look :) thanks in advance

Activity icon

Replied to Paginate Collection

Thanks for replie, this should be more explained

1.) The first return ?page=1 ->>>>>

response.data [
  {
    id: 1,
    user: {
      id: 1,
      full_name: 'test [email protected]',
      email: '[email protected]'
    },
    slug: 'davonte-sawayn-1',
    name: '1',
    body: 'Aliquam placeat veritatis alias sed et inventore. Animi animi amet recusandae qui voluptates quidem. Eos qui culpa aut molestias.',
    tags: [ [Object], [Object], [Object] ],
    time: {
      created_at: '2020-05-05T15:19:26.000000Z',
      updated_at: '2020-05-05T15:19:26.000000Z'
    }
  },
    ...... REST OF THE OBJECTS ....
]

2.) return after ?page=2 ++ ->>>>>>

response.data {
  '5': {
    id: 11,
    user: {
      id: 1,
      full_name: 'test [email protected]',
      email: '[email protected]'
    },
    slug: 'raphaelle-hudson-jr-1',
    name: '3',
    body: 'Maiores in ullam error odio accusantium rerum aliquam. Numquam explicabo fugiat facilis natus accusantium. Non et perferendis fugit in quas ipsum voluptate sit.',
    tags: [],
    time: {
      created_at: '2020-05-06T12:18:51.000000Z',
      updated_at: '2020-05-06T12:18:51.000000Z'
    }
  }

  ...... the rest
}
Activity icon

Replied to Paginate Collection

Thank you a lot

Activity icon

Replied to Paginate Collection

the first paginated page return an array of objects -> [ objects- 4 paginated ] and after the ?page=2 + it returns an array [ extraObj.{ {paginated objects} } ]

Do you have clue how to get rid of the extra object? here:

Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
        $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

        return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
            'path' => 'articles',
            'pageName' => $pageName,
        ]);
    });
Activity icon

Replied to Paginate Collection

Its working fine, thank you :) after I cleared config cache https://tecadmin.net/clear-cache-laravel-5/

Thanks a lot. I hope its going to help someone

Activity icon

Replied to Paginate Collection

Hello, thank you for replie.

So as you said I have created and registered ExtendCollectionServiceProvider, but there is the same result, where I got fetched collection, but with no meta...

Activity icon

Started a new Conversation Paginate Collection

Hello guys, please help me with paginating collection please.

I'm using approach to add this in appServiceProvider (https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e)

Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') { $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

        return new LengthAwarePaginator(
            $this->forPage($page, $perPage),
            $total ?: $this->count(),
            $perPage,
            $page,
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );
    });
}

this: I have this in my controller -> $collection = new ArticlesCollection( ArticleResource::collection(Article::with(['user', 'tags'])->paginate(2))); return $collection; It succesfully returns the two items per page -> ?page=... is working

But I have no meta tags included -> how many pages I have and so on... Please with including it. Thank you and with the best regards Martin

May
05
5 months ago
Activity icon

Started a new Conversation Laravel WhenLoaded Return An Empy Array

got an api resource, which returns an empty array even though I use whenLoaded('tags') function or eagerLoading in controller using with(['tags]) when I want to access objects relationship. I even tried both functions combined or separetly... My Resource

$data = [
        'id' => $this->id,
        'user_id' => new UserArticleResource($this->user),
        'slug' => $this->slug,
        'name' => $this->name,
        'body' => $this->text,
        'tags' => TagResource::collection($this->tags),
        'eager_tags' => TagResource::collection($this->whenLoaded('tags')),
        'time' => [
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ],
    ];

    return $data;

My controller

return response()->json([ new ArticlesCollection(ArticleResource::collection(Article::with(['user', 'tags'])->get() ) ) ]);