Home > Software design >  Elegant solution to create a Post when request attributes change
Elegant solution to create a Post when request attributes change

Time:12-23

I am wondering how I can implement this the best way:

I have a site where a user can make a post, he has 2 checkboxes there for "resumes" and "more documents". Those two are not required, but when they are I need to save a "true" in the database in the column for this.

I thought I could implement it by writing if loops, like:

  1. if both are present this code:

    Post::create([ 'resumee' => true, 'more_docs' => true,]);

  2. If only resume is present like this:

    Post::create(['resumee' => true, 'more_docs' => false]);

and if only more_docs is present then the other way around.

however I figured there would be a way better approach to implement this, but I am fairly new to laravel so I cant think about any.

My first guess was to do something like this inside the create statement:

Post::create([
                'resumee' => true,
               if($request->has(more_docs)
                'more_docs' => true,
               else ....
            ]);

But all I got were red lines haha. So maybe someone of you more experienced guys have an idea, any help appreciated!

CodePudding user response:

You can use something like this:

Product::create([
    // ... other fields
    'resumee' => $request->filled('resumee'),
    'more_docs' => $request->filled('more_docs'),
]);

If you would like to determine if a value is present on the request and is not empty, you may use the filled method. I think this mthod will more appropriate for your task.

  • Related