Reputation: 564
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.
Upvotes: 0
Views: 899
Reputation: 2166
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.
$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.
Upvotes: 1
Reputation: 3907
/**
* 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
Upvotes: 1