orest

orest

Member Since 5 Months Ago

Experience Points
41,080
Total
Experience

3,920 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
382
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 9
41,080 XP
Jul
23
1 week ago
Activity icon

Replied to Load Data In Tabs Only Once

i do save the data to the respective component but when i click on another tab, the previously selected tab is not rendered and the data is not stored anymore.

Activity icon

Started a new Conversation Load Data In Tabs Only Once

I created some tabs following Jeffrey's approach from Vuecasts where he displays the content of the clicked tab and hides the other tabs using the

<tab v-if="selected"> </tab>

In my case, when each tab is selected, an AXIOS request is made to load the necessary data from the server.

I was wondering if there is a way to load the data only the first time the tab is clicked and not always.

For example

  1. if i click the tab About for the first time, then make the AXIOS request to load the data.
  2. If then i click on another tab and then click again the About tab, then don't make the AXIOS request again

How can i achieve this ?

Is the only way to do it using Vue-router ? ( I haven't used Vue-router so far since i'm not building an SPA, and it seems a little odd to use Vue-router only for this case in the application ).

Jul
20
2 weeks ago
Activity icon

Replied to Multiword Class/method Names Or Extract Class

@martinbean

Sorry for the confusion.

A use can have only 1 profile but many posts on that profile.

So when you visit a user’s profile, you will see the all the posts of the user’s profile ( the same concept with fb more or less )

I used the name ProfilePost to be more specific, because the term post is very generic since a reply or a thread are considered post.

Activity icon

Replied to Multiword Class/method Names Or Extract Class

@martinbean i just wasn’t sure whether it is a good practice to do they because the Profile model will exist only to make the connection between user and posts. In other words, it won’t have any other data other than the user_id

The profiles table will be like

profiles 
- id 
- user_id

Activity icon

Started a new Conversation Multiword Class/method Names Or Extract Class

I'm building a forum app where

  • A user has a profile
  • Any user can create a post on any profile

I can't decide whether it is better to have a compound word class and method names or to extract a new class to make the API cleaner.

More specifically, to have a model ProfilePost to represent the posts or whether it is better to have an intermediate Profile model which will have a relationship posts

For example

class User extends Model{

	
    public function postToProfile($profileUserId, $post)
    {
        ProfilePost::create([
            'profile_user_id' => $profileUserId,
            'poster_id' => auth()->id(),
            'body' => $post
        ]);
    }

    public function profilePosts()
    {
        return $this->hasMany(ProfilePost::class, 'profile_user_id');
    }
}

The api would be

$user->postToProfile($profileUserId, $post);

  • Where poster_id is the user who created the post
  • and profile_user_id is the user who owns the profile.

The other approach would be to have an intermediate Profile model

 class Profile extends Model{

        public function owner()
        {
            return $this->belongsTo(User::class);
        }

        public function posts()
        {
            return $this->hasMany(Post::class)
        }

        public function addPost($post)
        {
            $this->posts()->create([
                'profile_user_id' => $this->owner->id,
                'poster_id' => auth()->id(),
                'body' => $post
            ]);
        }

      
    }

The api would be

  $user->profile->addPost($post);
Jul
19
2 weeks ago
Activity icon

Started a new Conversation Polymorphic Relationship With Unused Columns

I have the followings tables

threads
- id

profile_posts
- id

replies
- id
- repliable_id
- repliable_type
- position
  • Both Threads needs a model that has id, body, position.
  • While, ProfilePosts needs a model that has id, body

The issue here is that if i use a polymorphic relationship, then for all ProfilePosts i will have the column position which is not used at all.

Is this a reason to use 2 tables instead of a polymorphic relationship. For example, to have

threads
 - id

thread_replies
- id
- body
- position

profile_posts
- id

profile_post_replies
- id
- body
Jul
18
2 weeks ago
Activity icon

Replied to Where Clause In Polymorphic Relationship

@chr15k thank you.

I don't know what happened, but now it seems that even my previous approaches work.

Jul
17
2 weeks ago
Activity icon

Started a new Conversation Where Clause In Polymorphic Relationship

I have the tables

threads
- id
replies
- id
- repliable_id
- repliable_type

I want to add another column to the Thread, which is the id of the most recent reply.

Thread::where('id',1)->withRecentReply()->get()

And the following query scope

public function scopeWithRecentReply() {
 	return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 'threads.id');
                })->latest('created_at')
                ->take(1),
        ]);
}

I have also tried

public function scopeWithRecentReply() {
   	return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->where('repliable_id', '=', 'threads.id')
                ->latest('created_at')
                ->take(1),
        ]);
}

But in both cases the

recent_reply_id => null

If instead of threads.id i enter an integer, it works and the recent_reply_id is not null For example

public function scopeWithRecentReply() {
 	return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 1);
                })->latest('created_at')
                ->take(1),
        ]);
}

My question is

Is there a way to be able to fetch the recent_reply_id using the respective threads.id ?

Jul
16
2 weeks ago
Activity icon

Replied to Manually Updating Timestamps When $touches Is Enabled

@michaloravec thanks!

It was the other way around

so when i add a reply to a thread, i have to empty the touched relations

$reply = new Reply();
$reply->setTouchedRelations([]);

$reply->update([
'body' => '....'
'id' => 1,
'thread_id' => $thread->id
]);
Activity icon

Replied to Manually Updating Timestamps When $touches Is Enabled

@michaloravec

that didn't work..

The thread's timestamps are not updating still.

Activity icon

Started a new Conversation Manually Updating Timestamps When $touches Is Enabled

When i create a new Thread, i also create a Reply.

In the Reply model, i use $touches to update the Thread's timestamps when a Reply is updated.

However, i noticed that i cannot manually update the thread's updated_at when $touches is enabled

class Reply extends Model {

  protected $touches = ['thread'];
}
$thread->update(['updated_at' => Carbon::now()->subMonth()]);

The line above does not change the updated_at when $touches is enabled in Reply model.

Is there a way to manually updated timestamps in this case ?

Jul
15
2 weeks ago
Activity icon

Replied to Hide Buttons Based On Query String

@nathalie

I didn't remember that even though i've seen the whole series.

That's good to know that Jeffrey has used this approach.

However, he uses it for something ''less important'' let's say and i'd like to know if this is acceptable in general or whether i should take a different approach.

Activity icon

Replied to Hide Buttons Based On Query String

@snapey

Do you mean to send data from the controller ( true or false ) in order to show or hide a button ?

For example,

If one of the requests is

myThreads = 1

Then to keep track of the request data and create a variable

if($request->has('myThreads')){
	$filterMyThreads = true;
}
return view('threads', compact('filterMyThreads'));

and use that to decide whether to show or hide the button My Threads

< a href="/threads?myThreads=1" v-if="{{ $filterMyThreads }}">My Threads </a>
Activity icon

Started a new Conversation Hide Buttons Based On Query String

I'm building a small forum app with Laravel and Vue and currently i'm adding filter buttons to fetch threads based on the filter button.

For example, in a Vue component, i have the following button, which essentially makes a get request to the back-end and fetches the threads created by the authenticated user

<a href="/threads?myThreads=1"> My Threads </a>

But in addition to the button above i have other filters as well

  1. Threads i have replied to
  2. Threads that were created 7 days ago

However, i want to hide the clicked buttons based on the query strings

window.location.href

For example if i click the button My Threads, then the href will be

/threads?=myThreads=1

In this case i want to hide the button My Threads, based on the href.

My question

Is this a bad approach ? To make decisions based on the href.

Should i try a different approach ? Such as, passing data from the backend to to front end

Jul
04
1 month ago
Activity icon

Replied to Append Attribute To Pagination

@michaloravec

I currently have

$replies = $thread->replies()
            ->with('likes')
	    ->withCount('likes')
            ->paginate(Reply::PER_PAGE);

        $replies->each(function ($reply) {
            $reply->append('is_liked');
        });

Is it overkill if I create a separate class that will hide all these lines and will just return the replies like

$replies = (new ReplyWithLikes)->forThread($thread)

Or can I create a static method in the Reply model that will do the same thing ( I see that people tend to avoid static methods though )

Jul
03
1 month ago
Activity icon

Replied to Difference Between Command And Jobs

Hi @bobbybouwmann

I do have a use case now.

I want to add a reply to a thread and after i add the reply i want to

  1. Increment the replies_counter which is in the threads table
  2. Award the user who posted the reply with points
  3. Notify the subscribers of the thread that a new reply has been posted

Can i dispatch job addReply which will create a new reply and also handle all the above 3 steps.

Or would it be better to first create the reply

$thread->addReply($reply);
event(new NewReplyWasPostedToThread($this, $reply));

and then fire an event that a new reply has been posted and in the event listener handle all the above 3 steps.

Jul
02
1 month ago
Activity icon

Replied to Append Attribute To Pagination

@michaloravec

I did check that but in my case i don't have a collection of data but paginated data, therefore i can't do


$thread->replies()->paginate(Reply::PER_PAGE)->append('is_liked');

or anything like that

Activity icon

Started a new Conversation Append Attribute To Pagination

I'm trying to append an attribute to paginated data during runtime.

More specifically, i have a Reply model and i want to append the following attribute

 public function getIsLikedAttribute()
    {
        return $this->likes()->exists();
    }

In the controller i have the following line

$replies = $thread->replies()->paginate(Reply::PER_PAGE);

Then the $replies data are passed in a VUE component.

To each reply, i want to append the is_liked attribute, without using

$appends = ['is_liked']

Because in other views i eager load the Reply model and i don't need the is_liked attribute.

Jun
29
1 month ago
Activity icon

Started a new Conversation Thread Subscription Relationship

Essentially, Jeffrey in the FORUM series, created a ThreadSubscription to build the relationship between threads and users.

Question : I was wondering whether it is wrong to avoid creating the ThreadSubscription model and just use the Thread and User model to create the subscription system.

Jeffrey in the FORUM series used the following models and relationships.

class ThreadSubscription extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function thread()
    {
        return $this->belongsTo('App\Thread');
    }
}
class Thread extends Model
{
  public function subscriptions()
    {
        return $this->hasMany(ThreadSubscription::class);
    }
}

Schema::create('thread_subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')
                ->constrained()
                ->onDelete('cascade');
            $table->foreignId('thread_id')
                ->constrained()
                ->onDelete('cascade');
            $table->unique(['user_id', 'thread_id']);

}

My solution would be something like this

class Thread extends Model {


public function subscribers()
{
	return $this->belongsToMany('App\User', 'thread_subscriptions');
}
}

class User extends Model {

public function subscriptions()
{
	return $this->belongsToMany('App\Thread', 'thread_subscriptions');
}

}
Activity icon

Commented on Thread Subscriptions: Part 4

we do have a pivot table

my question was whether there is a benefit in creating another model instead of just using the pivot table

Jun
23
1 month ago
Activity icon

Replied to Displaying Coordinates On Leaflet Map

What exactly is the issue ?

Activity icon

Replied to Laravel Permission

Have a look at the documentation in the Authorization section

https://laravel.com/docs/7.x/authorization

Activity icon

Replied to Help With Scope

No, there is no limit in adding clauses..that's why the query scopes are for.

The only thing that i would change is to remove the firstOrFail()

Normally, you want to return a query in order to be able to continue building the query.

So for example, if you don't execute firstOrFail() you can have

Model::popular()->IdFromTopic()->Active() 
Activity icon

Replied to Using JS (Vue) In Larvel To Toggle Hamburger Button

Yes that's ok.

Now you need to include the component in your blade

Activity icon

Replied to Help With Scope

what is your question exactly ? because to me at least is unclear what you are trying to do and what you need to know.

Activity icon

Started a new Conversation MPA With Laravel And Vue

I'm trying to understand when to how much to mix Laravel blade with Vue components.

Taking Laracasts as a reference.

  • When you create a discussion or a reply, the page reloads, which means that server-side routing is used.

  • When you click on Discussion title, the page again reloads.

  • When you edit the discussion or a reply, the changes are visible instantly without reloading the page, which means that a Vue component is used to render the body of the discussion/reply.

  • When you want to see more replies, then the new replies are fetched with AJAX call without reloading the page.

Therefore, from what i understand, the content of the discussion is rendered by the Vue component and not on the server-side. In this case, Laravel sends a new file with the relevant data, and the Vue component renders the data ( the content of the discussion ), which is not SEO friendly

My Questions are:

1

Is this a semi-SPA approach ? If yes, then what are the benefits of loading a new page each time which consists only ( or mostly ) of a Vue component, instead of using creating an SPA . To better illustrate what i mean :

<body>
        <vue-component :data="{{ $data }}"></vue-component>
 </body>

2

Are there any benefits of using server-side routing instead of client-side routing and yet use Vue components as the main part of a blade view ( at least in this case ) ?

Activity icon

Replied to Using JS (Vue) In Larvel To Toggle Hamburger Button

You need to create a Vue component, register it in the app.js and then include that component in your blade view.

The logic of toggling the button as well as the button itself ( html, css ) should be in the Vue component.

Jun
22
1 month ago
Activity icon

Replied to Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts.

@martinbean

I guess post = thread-body / reply-body

But in order to be able to edit a post, you have to also render it on the client-side which i guess this is what Jeffrey does here.

So for example, when you click on a discussion, a new page is loaded with the relevant data, such as thread body, reply body etc.

Then these data i guess are passed to a Vue component in order to be able to edit/delete without reloading the page. In addition to that, if you go to the bottom of the page, you can dynamically load new replies which are again rendered on the client-side.

Therefore, Google cannot read the content of the discussion page, is this correct ?

Activity icon

Replied to Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts.

@martinbean thanks!

Could you please provide an example which shows the "bad" case of combining laravel and vue ?

Because i thought that when the data ( text in this case ) is rendered on the client-side then it is not SEO-friendly.

Basically to me the discussion section of laracasts looks like a blade view which consists of just a vue component ( or a least a big part of it is a vue component), which is as you mentioned a "bad" practice because it is somewhere in between MPA and SPA.

Activity icon

Replied to Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts.

@martinbean

Laracasts itself loads a new page when you click on a discussion, but the body of the discussion as well as the body of the replies seem to be dynamic ( you can edit the text, add a new reply etc on the fly, without reloading the page )

Is this considered a "not good" practice with respect to SEO ?

I'm asking because i want to make more clear, in what cases should we add a Vue component and in what cases it is better to prefer the server-side rendering.

Jun
14
1 month ago
Activity icon

Started a new Conversation Load Different Relationships For Categories, Sub-categories

I have the following tables

groups
- id
- title

categories
- id
- title
- group_id
- parent_id

threads
- id
- category_id
  • A category has threads
  • A category has categories that have threads

To better illustrate this example

  • iOS

    • ios12, ios13
  • General

  • The subcategories ios12 and ios13 have threads, but ios which is the parent category is not directly associated with the threads, but only through ios12 and ios13

  • The category General is directly associated with threads since it doesn't have sub-categories

Therefore i have the following relationships

  • For General, ios12, ios13*
public function threads()
{
   return $this->hasMany(Thread::class);
}
  • For iOS
public function parentCategoryThreads()
    {
        return $this->hasManyThrough(
            Thread::class,
            Category::class,
            'parent_id',
            'category_id'
        );
    }

The issue that i have is that i want in the same view to load both relationships using withCount. For example, for *ios i want to load the parentCategoryThreads and for general i want to load threads Is there a way to avoid prefixing every method with parent ?

Jun
11
1 month ago
Activity icon

Replied to Make Query In Blade View

i found the solution, for anyone who is interested.

The withCount can be modified and as a result it can return the sum of a column instead of the count.


$category->withCount(['parentReplies' => function($query) {
 $query->select(DB::raw('sum(replies_count)');
}

I don't quite get that how it works so if anyone has a better understanding, it will be helpful to know..

Activity icon

Started a new Conversation Make Query In Blade View

I have the following tables

groups
- id
- title

categories
- id
- title
- parent_id
- group_id

threads 
- id 
- replies_count
- title
- category_id

replies
- id
- thread_id
  • For each group, i display the title of the group
  • For each category associated with a group, i display the title of the category, the total number of threads and replies associated with that category
  • The categories table consists of children and parent categories. Therefore, when i display the title of a parent category ( a category that has children ), i want to display next to the title, the total number of threads and replies that are associated with its children categories.

For the total number of threads for a parent category i have the following relationship and i load the count

protected $withCount = ['parentThreads']

  public function parentThreads()
    {
        return $this->hasManyThrough(
            Thread::class,
            Category::class,
            'parent_id',
            'category_id'
        );
    }

For the total number of replies associated with a group i have the following code

public function getParentRepliesCount() {
	return $this->parentThreads()->sum('replies_count');
}

The problem is that in the blade view then i have to call this accessor which makes a query ( which is a bad practice, if i'm not mistaken )

<p> {{ $category->parent_replies_count }} </p>

My question is if there is a better alternative ?

Also i'd like you ask whether it is a bad practice to have hierarchy in the same table, because currently i have a categories table which consists of parent and children, and in the Category model i end up with several methods that have parent and **children prefix **

Jun
08
1 month ago
Activity icon

Replied to Conditional Relationship / Query Based On Table Field

@guybrush_threepwood

that works but i didn't consider that approach because i want to eager-load the relationship.

So ultimately i need to do

Category::with('recentThread')->get();

And in this case

$this->parent_id

returns always null.

Activity icon

Replied to Conditional Relationship / Query Based On Table Field

@guybrush_threepwood

I just tried it again and for the parent_categories the recentThread has the proper value but for the children_categories the recentThread is null because as i said it enters the if statement always.

Could you please explain me though why is it different in a relationship and in query scope ? Since in both cases $this refers to the query builder i guess ( or more specifically $this refers to the Categories table if i am not mistaken )

Activity icon

Replied to Conditional Relationship / Query Based On Table Field

hi @guybrush_threepwood

I've tried that but the problem is that

$this->parent_id 

always returns null for some reason and thus it enters the the if statement

Activity icon

Started a new Conversation Conditional Relationship / Query Based On Table Field

I have the following tables

categories
- id
- parent_id

threads
- id
- title
- category_id
- updated_at

The categories table consists of children and parent categories and each thread belongs to a children category.

For each category ( either parent or children ) i want to fetch the thread that was most recently updated. Therefore, when i query all categories, i need to have an extra field which contains the title of that thread.

To better illustrate this, i will give an example.

  • parent_categoty = iOS
  • children_category = iOS13
  • children_category = iOS14

Now when i fetch all categories (iOS, iOS13 and iOS14 ), i want to have an extra field named 'recentThread'. However since threads belong to children_categories, the parent_category doesn't have any thread associated with it, but instead for the parent_category i want to fetch the most recent thread among its children categories.

Therefore i need to use a different relationship based on whether the parent_id is NULL.

public method recentThreadForParent(){

return $this->hasOneThrough(
            Thread::class,
            Category::class,
            'parent_id',
            'category_id'
        )->latest('updated_at');
}
public method recentThreadForChildren(){
 return $this->hasOne(Thread::class)->latest('updated_at');
}

After i did a research i found the following

public method scopeWithRecentTrhead($query){

 if ($this->parent_id == null ){

  // do something
}
else {

 // do something else
}
}

But it is always null so it enters always the firs condition.

On top of that i want in the end to have the same name for either relationship in order to be able to access the recent thread like this

$category->recentThread

Where category can be either parent or children. The solution that i found for this is to use addSelect

public method scopeWithRecentThread($query){

// For the children category
 $query->addSelect([
 'recentThread' => Thread::select('title')
                   ->whereColumn('category_id', 'categories.id')
                   ->orderBy('updated_at', 'desc')
                   ->limit(1)
 ]);

// For the parent category im not sure how to do it because i need the ids of the children for each parent category. ( this is the hasOneThrough relationship )

 $query->addSelect([
 'recentThread' => Thread::select('title')
                   ->whereIn('category_id', 'Ids of children')
                   ->orderBy('updated_at', 'desc')
                   ->limit(1)
 ]);

}

and in that case i don't know how to conditionally execute a different query. i've tried to use when but what i need to achieve is something like

$query->when('parent_id is NOT NULL') 

But that doesn't work either

Jun
07
1 month ago
Jun
06
1 month ago
Activity icon

Started a new Conversation Recently Active Threads And Replies

I have the following models and relationships:

  1. A Reply that belongs to a Thread
  2. A User who posted the Reply
  3. A Thread that belongs to a Category

The most recently active thread is defined by the thread that has the most recent reply posted by a user.

I have the following views.

  1. A view that displays all the category titles and i want next to each category title to display the most recently active thread and the name of the user who posted that last reply on that thread.
  2. A view that displays the list of threads and next to each thread title i want to display the name of the user who posted the last reply.

One solution would be

The Category Model :

Class Category Extends Model {

public function recentlyActiveThread(){

return $this->hasOne(Thread::class)->latest('updated_at');
 }
}

The Thread Model

Class Thread Extends Model {

public function recentReply(){

 return $this->hasOne(Reply::class)->latest('updated_at');
 }
}

The Reply Model


Class Reply Extends Model {

public function poster(){

	return $this->belongsTo(User::class, 'user_id');
 }
}

Then in the view i can do.

@foreach($categories as $category)
<p> $category->recentlyActiveThread->title </p> 
<p>  $category->recentlyActiveThread->reply->poster </p>
@endforeach

I was wondering if there is a better way to approach this because it seems a little messy to me that i have to access so many different models in order to get the user who posted that reply.

In addition, i give the responsibility to Category to know which one was the most recently active thread, which i don't know if that is ok.

Jun
05
1 month ago
Activity icon

Replied to Join With 'where' Clause

@michaloravec

thank you.

For some reason I get the same results. I see only the attributes of the categories table.

Activity icon

Replied to Join With 'where' Clause

@kalemdzievski

I mean that if I run that query in a db manager, then I get a table with the attributes from both categories and group_categories table. For example, both the categories and group_categories have the attribute title, But the issue that I have is that instead it returns only the title of the categories and not the title of the group_categories.

Activity icon

Started a new Conversation Join With 'where' Clause

I have two tables

  1. group_categories
  2. categories

Where each category belongs to a group.

I want to display in a view each group together with its categories ( the categories that have parent_id IS Null ).

@foreach($group_categories as $group)
	<p>  $group->title  </p>
	@foreach($group->categories as $category)
		<p>  $category->title </p>
	@endforeach
@endforeach

It works when I define a relationship between them using eloquent

public function categories()
{
	return $this->hasMany('Category::class', 'group_category_id')->whereNull('parent_id');
}

However, before that I tried to make the following query

DB::table('group_categories')->join('categories', function ($join) {
             $join->on('group_categories.id', '=', 'categories.group_category_id')->whereNull('categories.parent_id');
         })->get();

Now this query is supposed to join the group_categories table and categories with the condition that the parent_id of the categories is null.

I am using the Laravel-debugbar and the query that Is executed is

select * from `group_categories` inner join `categories` on `group_categories`.`id` = `categories`.`group_category_id` and `categories`.`parent_id` is null

The problem is that it returns only the categories ( with the condition that parent_id is null ) but none of the group_categories attributes is returned.

Am I missing something here or this is the expected behaviour ?

Jun
04
2 months ago
Activity icon

Started a new Conversation Mock Recaptcha In RegisterController

I have added a recaptcha in the registration form and i have also added a recaptcha rule in the validation of the registration form, which works fine.

The problem that i have is that i can't mock the Recaptcha class. In order to do that, i have to pass the Recaptcha class as an argument in the validator method of the RegisterController, but it complains about the number of arguments that are being passed

protected function validator(array $data, Recaptcha $recaptcha)
    {

        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'g-recaptcha-response' => ['required',  $recaptcha],
        ]);
    }
 $this->mock(Recaptcha::class, function ($mock) {
            $mock->shouldReceive('passes')->andReturn(true);
        });

Is there a way to mock it ?

Jun
03
2 months ago
Activity icon

Replied to Categories, Sub-categories And Threads

@michaloravec

Thanks again for your help. That's something i didn't think of.

However, in this case you display both the categories and threads in category.show ? Because i want to have separate views for each model and in this case

  1. If a category has a subcategory, then display only the sub-categories
  2. If a category doesn't have sub-categories, but it has threads, then display all the threads associated with that category.

Just out of curiosity, is it 'wrong' to redirect to another path ?

Activity icon

Replied to Categories, Sub-categories And Threads

@michaloravec

I just noticed an issue with the current approach.

if I hit the path /categories , I return a view with all categories, but now if I click on any of the categories, my options are either of the following two:

  1. Return a view with the list of the sub-categories
  2. Return a view with the threads associated with

The issue is that if I want to display the threads, then the url will be /categories. Is it ok if I redirect to another path in order to hit the ThreadController ?

CategoryController extends Controller {

public function show(Category $category)
{
	if ($category->children->exists())
	{
		return view('categories.sub_category.index' ,
 ['subCategories' => $category->children])
	}
	else {
		return redirect('/categories/' . $category->id . '/threads' )
	}
	

}

}
ThreadController exntends Controller {

	public function index(Category $category)
	{
		return view('threads.index', ['threads' => $category->threads]);
	}

}