Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elegant solution to create a Post when request attributes change

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading