0
   DB::table('New_Themes')
                ->where('id', $id)
                ->decrement('upVotes', 1);
                DB::table('New_Themes')
                ->where('id', $id)
                ->increment('downVotes', 1);
...

I have the update query, so I have at least 4 of this(where and increment stuff) which is repetitive and it takes time to search on an on.

My Question: There is any shortcut like doing so

DB::table('New_Themes')
                ->where('id', $id)
                ->decrement('upVotes', 1);
                ->increment('downVotes', 1);

but it doesn't work, any idea how to make it simpler?

Second Question: How to use firstOrCreate method in Laravel, I need this feature to make my code easier. But i don't know how to integrate it with models, controllers.

Ex. $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']); (from documentation)

What kind of variable is $flight, boolean or ...?, Any explanation will be very helpful for me, cause the laravel documentation lacks detailed information.

1
  • It will be object of created/updated element. Commented Jul 20, 2016 at 11:21

2 Answers 2

1

1.

function downVote($id)
{
      DB::table('New_Themes')
          ->where('id', $id)
          ->decrement('upVotes', 1)
          ->increment('downVotes', 1);
}

Then you don't have to type it if you use it more than once.

2.

$flight is an instance of the model Flight, you should learn how to use model, this will make your life easier when dealing with data and fully use the MVC architecture the Laravels doc is quite well documented about it.

Sign up to request clarification or add additional context in comments.

3 Comments

it says me: syntax error, unexpected '->' (T_OBJECT_OPERATOR), why this happens?
this happens when i add below the ->increment('downVotes', 1);
I found this finnaly DB::table('New_Themes') ->where('id', $id) ->update([ 'upVotes' => DB::raw('upVotes - 1'), 'downVotes' => DB::raw('downVotes + 1'), ]); works very well
1
/**
     * Get the first record matching the attributes or create it.
     *
     * @param  array  $attributes
     * @return static
     */
    public static function firstOrCreate(array $attributes)
    {
        if ( ! is_null($instance = static::where($attributes)->first()))
        {
            return $instance;
        }

        return static::create($attributes);
    }

You can see file vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.