pmusa

pmusa

Member Since 4 Months Ago

Experience Points 1,240
Experience Level 1

3,760 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.

12 Sep
3 days ago

pmusa left a reply on OrderBy() Not Compatible With Distinct()

I meant orderBy() instead of sortBy() of cours.

I can't sort later in the view, since that sql request does not return any comment but the users only. I just need the distinct users, but orderer by the time they left their comments on that post.

Plus I do not want to do that in a view anyway.

11 Sep
4 days ago

pmusa started a new conversation OrderBy() Not Compatible With Distinct()

I have 3 models: User Post Comment

Users can leave comments on a post.

I have a method within my Post model that allows me to list all users who left a comment on a post :

    /**
     * Get distinct commentators on a commentable model.
     *
     * @usage  $distinctCommentators = Post::find('post_UUID')->commentableCommentators()->get();
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function commentableCommentators(): belongsToMany
    {
        return $this->belongsToMany($this->retrieveUserModel(), 'comments', 'commentable_id', 'user_id')
            ->where('commentable_type', array_search(static::class, Relation::morphMap()) ? : static::class)
            ->distinct('user_id');
    }

I'd like to sort that users list so that the user that commented first appears first. So i appended this :

->orderBy('comments.created_at')

Which won't work since it collides with the distinct().

Thank you for your help.

pmusa left a reply on User Specific Alerts With Many Filters

you mean I would check against a specific table that would list every possible combinations of criterias/filters?

pmusa started a new conversation User Specific Alerts With Many Filters

Imagine an app where people would be able to submit best online deals. i.e : User posts a deal where Product is -50% off at online Shop.

Now let's say User2 wants to receive alerts everytime a new deal is submitted, but where price of Product is between $50 and $100, plus where Product is of family "electronics" only, plus where Product is at Shop named "Amzn" only.

How would this look like in Eloquent/Laravel? Do you have to run an SQL request for every single user of your DB, everytime a new deal is posted, to check if the deals fits in each user's criterias/filters, then send the alert?

This is a complete random example. Basically my question is, broader picture: how do you handle user specific alerts with very user specific filters?

Thank you

10 Sep
5 days ago

pmusa left a reply on Factory And Events / Call A Custom Method Instead Of Create()

Yes I do. Thank you for your link to that article. That's what I needed.

pmusa started a new conversation Factory And Events / Call A Custom Method Instead Of Create()

User can leave a Comment on a Post. Those are 3 models. When user comments a post, I store the comment through a custom method commentatorStoreComment(), which also triggers an event :

$user->commentatorStoreComment($post, 'here goes my interesting comment body blablabla');

https://i.imgur.com/ab1Juam.png

In order to test it, here is how I am forced to code my tests :

https://i.imgur.com/YMHg9hg.png

As you can see, I cannot use my Comment Factory since this would bypass my custom method that fires the event.

This passes the tests fine, but I am looking for a more elegant/maintainable/scalable way to write my tests involving Comment. Right now I have to duplicate that line everywhere for each test cases...

Thank you.

08 Sep
1 week ago

pmusa left a reply on Eager Load A Relation

Sure, but I was looking for something more elegant.

                ->when(auth()->id(), function ($query) {
                    return $query->withCount('userComments');
                })

All good!

pmusa left a reply on Eager Load A Relation

That works very well indeed. Thanks Muhammed!

Bonus question : is there a way to skip that additional "request" if the user is not logged in? I'd like to get rid of the highlighted request if there is no auth()->id() since there would be no point running that relationship :

https://i.imgur.com/cLeEcmJ.png

pmusa left a reply on Eager Load A Relation

Correct. You got it. I just want to show an info next to each post if the user has left a comment there.

I'm thinking about something like this :

->withCount('userComments')

which would then also allow me to display the number of comments left by the user on each post. With something such as this, on the Post model :

    public function userComments(): MorphMany
    {
        return $this->comments()->where('user_id', auth()->user()->id);
    }

Thoughts? Is there a better way to achieve this?

pmusa left a reply on Eager Load A Relation

Sorry. Let me explain it a different way.

This is what my partial view looks like:

{{ $post->title }}<br />
{{ $post->bodyTruncated }}<br />
<a href="{{ route('posts.show', $post->id) }}">Click here to read more about this post</a><br />             
@if(auth()->user() && $post->isCommentedByUser(auth()->user()))
    You left comments on this post.
@endif

Problem: the isCommentedByUser method fires an SQL request for every single $post (I have 12 per page). I'd like to find away that would grab the info whether the user commented (or not) any of the shown posts, with eager load.

pmusa started a new conversation Eager Load A Relation

my PostController.php :

    public function index()
    {
        $posts = Post::latest()
                ->with('user')
                ->withCount('comments')
                ->paginate(12);

        return view('posts.index', compact('posts'));
    }

my Post model :

    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

my User model :

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class, 'user_id', 'id');
    }

How do I eager load a boolean within my controller's $post so that my view can display the fact that auth()->user()->id left or not (true/false) a comment on each displayed post (12 per page)? I want to avoid the N+1 problem I currently encounter.

05 Sep
1 week ago

pmusa left a reply on [security] Creating Instance From POST Data

I wish I could.

https://i.imgur.com/q1npNpG.png

As you can see, I perform the validation using vars that are defined/assigned just above the validate() method. Those vars are $commentableTable and $commentableKeyName I haven't figured yet how to elegantly send those to the FormRequest. My controller needs that $commentable var, and I do not want to retrieve that var both in the controller and the FormRequest (since it would poll the DB twice)

04 Sep
1 week ago

pmusa left a reply on [security] Creating Instance From POST Data

I ended using the native ReflectionClass, which seems bulletproof to me.

My getCommentable() news up an instance only if it's ok to do so.

Only then it hits the validate() method, which at that point it almost just a second pass, but why not. Never paranoïd enough.

https://i.imgur.com/u4vLNGw.png

I'll move on from here.

I did not like the idea of maintaining an array of whitelisted values. The interface works great.

Thank you again for your lights ustam

03 Sep
1 week ago

pmusa left a reply on [security] Creating Instance From POST Data

I sure do, as you can see. I was wondering if it was ever possible for a malicious visitor to forge it in a way that it would run methods though, somehow.

teşekkürler kardeşim

pmusa started a new conversation [security] Creating Instance From POST Data

I'm creating an instance from user submitted data :

https://i.imgur.com/jrMUfYj.png

$instance = new $commentableType(); // App\Post

which comes from:

https://i.imgur.com/lRrD30N.png

$commentableType = 'App\\' . request('commentable_type'); // App\Post

Is such a thing safe? Thank you.

29 Aug
2 weeks ago

pmusa left a reply on Eager Loading

Users can comment articles (and files, and images, and whatever). A user can also comment comments. The "answerTo()" allows me to know which comment a certain comment replies to, through the "reply_to_id". In fact, I also do have a "parent_id" column in that same table, which fullfills about the same purpose. but since I do not want an infinite depth of "children", at some level of depth all comments have the same "parent_id" but a different "reply_to_id" (which still allows me to know who replies to who, without having a super deep multidimmensionnal array with that "parent/children" relationship). Not sure if clear enough.

28 Aug
2 weeks ago

pmusa started a new conversation Eager Loading

How to avoid this? https://i.imgur.com/JrB4bvw.png

This is redundant.

I have a HasComments.php trait with the following :

    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

And a Comment.php model with the following:

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

    public function answerTo()
    {
        return $this->belongsTo(self::class,'reply_to_id','id');
    }

And here is the faulty line that fires the two redundant SQL queries :

$comments = $this->comments()->with(['user', 'answerTo.user'])->get()->keyBy('id');

How do I make it so that Eloquent merges these 2 (highlighted in the screenshot above) and does not query unnecessarily? Thanks

24 Aug
3 weeks ago
21 Aug
3 weeks ago
18 Aug
4 weeks ago

pmusa left a reply on SetRelation To Collection

I could also chain strtoupper() onto the collection somehow. That will make it all full caps.

pmusa started a new conversation SetRelation To Collection

I'd like to make it so that my "reply" relation is not nested. Here is the $comments Collection : https://i.imgur.com/ELOCJT1.png Basically, one comment can reply to one other comment (the info is stored within the DB as a reply_to_id column). Here is how I "build" the Collection :

        $comments->filter(function (Comment $comment) {
            return $comment->reply_to_id; // 122
        })->each(function (Comment $comment) use ($comments) {
            $parent = $comments->get($comment->reply_to_id); // 119
            if ($parent && ! $comment->relationLoaded('reply')) {
                    $comment->setRelation('reply', new Collection);
                    $comment->reply->put($parent->id, $parent);;
            }
        });

        // return root comments
        return $comments->filter(function (Comment $comment) {
            return ! $comment->parent_id;
        });

The screenshot above shows comment id #123 is a reply to #122. But it also shows #122 is a reply to #119. And so on... I don't need that much "depth" of information. Is there a way I can avoid that? Thank you.

10 Aug
1 month ago

pmusa left a reply on On-the-fly Attribute

Yes. Building a tree requires a "path" column. Once again: not suitable for a Comments module.

pmusa left a reply on On-the-fly Attribute

I know about eager loading. You all seem to ignore how inappropriate these "nested set models" are for Comments. They are OK for menus/categories that do not change much, but way too expensive for Comments (inserts/updates). Do you even use the DebugBar? I prefer to build treeviews with php rather than sql relations. I've done it with Collections, php-side, as suggested. Now no matter how deep the nest is and how many hundreds of comments there are on a particular post, I only fire 1 sql select. which is crazy performant.

07 Aug
1 month ago

pmusa left a reply on On-the-fly Attribute

Guys...

I know I could do something like :

    public function childs() {

        return $this->hasMany('App\Comment','parent_id','id') ;

    }

But I do NOT want to do that. This is complete GARBAGE. Eventhough that seems simple/convenient/easier to you, this, unless I'm fully wrong, is full GARBAGE. This would force one to do some kind of unperformant recursion within my view like :

@if(count($comment->childs))

    @include('manageChild',['childs' => $comment->childs])

@endif

and then :

@foreach($childs as $child)

    @if(count($child->childs))

            @include('manageChild',['childs' => $child->childs])

        @endif

@endforeach

This. Is. Garbage.

That's why I need to build that tree with PHP (or any super magic Laravel collection method, which does not seem to exist). I somehow fixed it using an ugly trick, but we're not there yet...

$commentsById[$comment->parent_id]->children = array_merge([$commentsById[$comment->parent_id]->children], [$comment]);

...

06 Aug
1 month ago

pmusa left a reply on On-the-fly Attribute

I thought I was working on Objects but those are actually "Collections" ?

Basically my code gets all the comments for the Post #1, then it re-indexes the keys so that the key name is actually the comment's id. This way I can perform an other loop (the second foreach() above) and attach any subcomment to its parent since I know the parent comment's key. Sounds good?

Now the buggy part is that ->children[] part.

pmusa left a reply on On-the-fly Attribute

I kind of understand what you meant with that hasOne() relationship (a comment can only reply to one other comment), but I want to delegate the tree building to php as much as possible, instead of a super heavy sql requests with iterations/loops.

pmusa left a reply on On-the-fly Attribute

Hi,

This has nothing to do with the parent_id attribute.

I don't even need that attribute to return anything. I just want Laravel to let me populate my array with whatever key I want, that is: a children key, where i can nest sub-comments of a parent comment.

This is not a "hasOne" relationship. Multiple Posts can have multiple Comments. I use a morphMany relationship in that case (since users are not limited to comment just Posts, but other stuff as well). This is out of the scope of my problem anyway I believe.

pmusa started a new conversation On-the-fly Attribute

Here is what I have within my api.php :

Route::get('/test', function (Request $request) {
    $post = App\Post::findOrFail(1);
    $postComments = $post->comments()->with('user')->get();
    $commentsById = [];
    foreach ($postComments as $comment){
        $commentsById[$comment->id] = $comment;
    }
    foreach ($postComments as $k => $comment){
        if($comment->parent_id !== null){
            $commentsById[$comment->parent_id]->children[] = $comment;
            unset($postComments[$k]);
        }
    }
    return $postComments;
});

This raises following error message :

Indirect modification of overloaded property App\Comment::$children has no effect

Indeed, the "children" column does not exist at all within my "comments" table, but I want to set it as a key within an array so that I can build a tree with a bit of php. Can you help? I've read on GG about the setters/getters for attributes but I could not manage to fix this so I'm not sure it applies to my case? Thank you

23 Jun
2 months ago

pmusa started a new conversation Nested Comments

Hello I'm looking for guidance on how to set up a comments system where users can reply to each other. So far I have a comments table with columns like parent_id (for the nesting) and commentable_id + commentable_type since users can comment anything (posts, images, etc). I don't like it because the depth of the nesting is infinite, which is a huge concern for me (sql requests are heavy, and it does not look great when users reply to each others many time). Is it possible to limit the level of depth? how?

I'd like to achieve something like this, where after some depth, it stops padding the comment, but still indicates who replies to who (circled in red) :

https://imgur.com/a/N96d6QQ

https://imgur.com/a/A8DMLgJ

what would be the most appropriate tables/columns for the database?

many results on google and github, but none of them actually convincing/practical enough. thank you

17 Jun
2 months ago

pmusa left a reply on Same Form Request, But Different Policy?

Or I just set

    public function authorize()
    {
        return true;
    }

but then I keep all those

$this->authorize('xyz', $post);

in the controller methods.

pmusa left a reply on Same Form Request, But Different Policy?

@ARCTIC-ICE-COOL - That is not elegant at all, plus the create() and update() methods do not have the same arguments for the authorize() :

create() needs : $this->authorize('update', Post::class); while update() needs $this->authorize('update', $post);

I want the code to be cleaner. So far I'm thinking about creating 2 different Requests. I'm just wondering if there is a cleaner way so I do not end up wih tons of files in my "Requests" folder.

pmusa started a new conversation Same Form Request, But Different Policy?

Hello,

Within my controller, both the store() and update() methods take the same form request as a parameter. Reason is because they have the exact same validation rules(). However, store() uses following policy : $this->authorize('create', Post::class); while update() the following one : $this->authorize('update', $post);

Now, since store() and update() share the same MyRequest $request , they also do share the authorize() method alongside with the rules()

So, do I need to generate 2 Form Requests for this? Like MyStoreRequest $request + MyUpdateRequest $request, or is there a way to make it so that they share the same rules(), but different authorize() ?

Reference: https://laravel.com/docs/5.8/validation#form-request-validation (see "Authorizing Form Requests")

Thank you

08 May
4 months ago

pmusa left a reply on Merge 2 Collections

I already defined these relationships on each and every Model back and forth. See me eager loading above? I found the answer on StackOverflow. You can actually nest the Builder, such as:

with('user', 'comments', 'comments.user')

which is cool.

07 May
4 months ago

pmusa started a new conversation Merge 2 Collections

Hello,

Is there a method to merge 2 collections? I could not find any https://laravel.com/docs/5.8/collections#available-methods

Here is collection #1 : https://i.imgur.com/pDsxgEg.jpg Here is collection #2 : https://i.imgur.com/1YvZkbm.jpg

I'd like to merge those 2 collections based on "user_id" of collection #1 and "id" of collection #2. I'd like to call the key "user", so that in the end I can reach a comment's author like this:

foreach ($comments as $comment)
{
    echo 'Author is ' . $comment->user->name;
}

In case you wonder what's in my controller, here it is:

        $post = Post::with('user', 'comments')
                ->findOrFail($request->route('post'));
        $comments = $post->comments;
        $users = User::findMany($comments->pluck('user_id')->toArray());

Basically what I want to achieve is to build a big fat collection then send it to the view all ready to be read. I'm not super happy with how Laravel fires SQL requests (n+1 problem). Eager-loading helped retrieving the user infos of the post's author, but it fires a SELECT for every single comment author ("user_id" within parent "comments" of collection #2)...

Thank you

06 May
4 months ago

pmusa left a reply on Store() Method For Polymorphic One To Many Relationship

I was looking for this:

$post->comments()->create([array-of-comment-data]);

or this

$user->comments()->create([array-of-comment-data]);

which @goatshark explains in the thread I linked.

pmusa left a reply on Store() Method For Polymorphic One To Many Relationship

@goatshark 's replies on this thread helped me better : https://laracasts.com/discuss/channels/laravel/best-way-to-save-with-one-to-many-relationship

@nakov thank you for your confirmation about distinct controllers. I think that's the right thing to do as well.

05 May
4 months ago

pmusa started a new conversation Store() Method For Polymorphic One To Many Relationship

Hello,

Let's say I have a blog with posts and videos. Users can submit comments on both posts and videos.

So, I have a Post model with:

    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable')->whereNull('parent_id');
    }

a Video model with the same content.

and a Comment model with:

class Comment extends Model
{

    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }

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

    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
    
}

Since I want to store all the comments in a single table, I'm in a "Polymorphic One to Many Relationship" scenario, right?

I guess so.

But then I'm struggling with the store() method of my CommentsController. My draft so far looks like this:

public function store(Post $post)
    {
        $this->validate(request(),[
            'body' => 'required'
        ]);
        
        $comment = Comment::create([
            'user_id' => auth()->id(),
            'commentable_id' => $post->id, // ???
            'parent_id' => request('parent_id'),
            'body' => request('body'),
        ]);

        return redirect()->route('post.show', $post->id)
            ->with('success', 'Comment created successfully!');

    }

What I am trying to achieve is this: store the comment in the database, and redirect back either to /post/{the_post_id_here} or /video/{the_video_id_here}

So, first question: What's the proper create() syntax within my CommentsController's store() method to save the comment properly?

Second question: Do I need 2 controllers? Like "PostsCommentsController" and "VideoCommentsController"? Because as you can see, the store() method above is type-hinted for Post, and I have no idea how to make it so that this controller would work for both kinds (posts and videos, and whatever I might make "commentable" in the future).

Thank you very much.

28 Apr
4 months ago

pmusa left a reply on Grab REQUEST_URI Parameters

@jacobs that works great, thank you! @nakov thank you for the video!

pmusa left a reply on Grab REQUEST_URI Parameters

Not a big fan of the segment(), since I won't benefit from the route() in my view if I ever change the sequence in my web.php file.

However it works fine this way indeed :

    public function index($year='',$month='')
    {

        $posts = Post::latest()
            ->filter(compact('year','month'))
            ->get();
        
        return view('posts.index', compact('posts'));
    }

parameters are optional because I also have this:

Route::get('/posts', '[email protected]')->name('posts');

which references the same controller method. Not sure how elegant that is. I'm wondering if I should seperate the methods, although they run through the same Eloquent query and return the same view ...

pmusa started a new conversation Grab REQUEST_URI Parameters

Hello!

My route:

Route::get('/posts/archives/{year}/{month}', '[email protected]')
        ->where(['year' => '[0-9]{4}', 'month' => '[A-Za-z]+'])
        ->name('posts.archives');

My Controller:

    public function index()
    {
        //dd(request());
        $posts = Post::latest()
            ->filter(request(['year','month']))
            ->get();
        
        return view('posts.index', compact('posts'));
    }

My View:

<a href="{{ route('posts.archives', ['year' => $archive['year'], 'month' => $archive['month']]) }}">

My Model:

    public function scopeFilter($query, $filters)
    {

        if (isset($filters['month'])) {
            $query->whereMonth('created_at', Carbon::parse($filters['month'])->month);
        }

        if (isset($filters['$year'])) {
            $query->whereYear('created_at', $filters['$year']);
        }

    }

Is there a way to elegantly grab "2019" and "April" when the user visits https//dev.local/posts/archives/2019/March ?

This returns "null":

request(['year','month'])

I'd like to avoid the old fashioned way where I'd parse the $_SERVER['REQUEST_URI'] and explode() it for the fragments I'm looking for... I'm sure Laravel has something for me, right?

Thanks!

23 Apr
4 months ago

pmusa left a reply on Why Mass Assignments?

@CRONIX - Don't you validate() these 30 fields?

21 Apr
4 months ago

pmusa left a reply on Why Mass Assignments?

That's right. The fact that someone would use "request->all()" just blew my mind.

pmusa left a reply on Why Mass Assignments?

"And just set up the models the way Taylor recommends the man knows what he's doing." No. I like to understand what I do and why it's done that way. I found the answer in the (great) videos though. Thank you. I now understand that it's all related to the fact that some devs just send the entire array with request->all(), without explicitly naming each key. I didn't even think someone would do that. That's crazy. I'm actually glad he does not allow that by default. It makes sens to me now. Thank you all for your answers and your patience.

pmusa left a reply on Why Mass Assignments?

What if I create a custom parent model "Model" (that extends the Eloquent model). Then I state within "Model" that $guarded is an empty array. Then Post model extends my custom model. Then I keep my Post controller as it currently is: Post::create([ 'title' => request('title'), 'body' => request('body') ]);

Will it save "is_admin=1" if a user sends such a thing?

pmusa left a reply on Why Mass Assignments?

Post::create([ 'title' => request('title'), 'body' => request('body') ]);

those 4 lines translate into: "fill the title and the body in the database". why do I need to tell Laravel "hey, btw, title and body are fillable" on top of that in the Model file? I do not understand that redundancy. why such a behavior? also, by default?

pmusa left a reply on Why Mass Assignments?

I'm afraid I still do not understand. Within the Eloquent's method called "create()", I pass an array as a parameter (see the 4 lines code above). That array just contains the "title" and the "body", which means I just want to save/INSERT the "title" and the "body". Now let's say a hacker also submits a $_POST['is_admin']=1 Let's also say I indeed have a "is_admin" column within my "posts" table. I do NOT care if the user sends me a forged "is_admin", since the code above states that I just want to save the "title" and the "body", nothing else! I've never seen anyone do such a thing as "Post::create($request->all())". Don't they even validate/controle every single user inputs? "If you're explicitly naming what you're saving each time (like your example)" --> That is indeed what I have always been doing.

pmusa left a reply on Why Mass Assignments?

I understand that. What I do not understand is: I clearly state on the piece of code above that I just want to store the title and the body, why would Laravel even consider any other var the user might submit? Let's say a hacker also submits a "user_id" (which stores posts author id), well who cares?

pmusa started a new conversation Why Mass Assignments?

Hello, I'm new to Laravel. I learned how to solve the issue with the MassAssignmentException, however I do not understand why such a concept was introduced. Here is for example what's inside my Posts controller :

    Post::create([
        'title' => request('title'),
        'body' => request('body')
    ]);

As you can see, I clearly say I want to INSERT the title and the body. Why, ON TOP OF THAT, do I need to define what's fillable or guarded? Why such a redundancy?

Also, are the "created_at" and "updated_at" columns of my DB immune by default, or can a hacker forge a POST request to alter both those columns as well?

Thank you for your time.