Trying to update integer in database by using increment function in laravel - php

I want to add 1 to my previous karma value in my database.
Here's what I am doing in my controller:-
public function response(Request $request, $id)
{
$globalPost = PublicAnswer::find($id);
if($request->resp == "normal")
{
$answered_by = DB::table('users')
->where('id', $globalPost->answered_by)
->increment('karma', +1);
}
}
Here's my database:-
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('karma')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
If I replace increment function with update this is the error that I am getting:-
Argument 1 passed to Illuminate\Database\Query\Builder::update() must be of the type array, string given,
I cannot see any errors and the karma attribute is null.
can anyone tell me whats wrong with my codes.

DB::table('users')
->where('id', $globalPost->answered_by)
returns a Illuminate\Database\Query\Builder ;
Illuminate\Database\Query\Builder has an increment function
public function increment($column, $amount = 1, array $extra = [])
and an update function
public function update(array $values)
so you can try
DB::table('users')
->where('id', $globalPost->answered_by)
->increment('karma');
or this, this would set karma to 1
DB::table('users')
->where('id', $globalPost->answered_by)
->update(['karma'=>1]);
if you want use update set karma=karma+1
use Illuminate\Database\Query\Expression;
DB::table('users')
->where('id', $globalPost->answered_by)
->update(['karma'=>new Expression('karma + 1')]);

According to the docs https://laravel.com/docs/8.x/queries#increment-and-decrement you simply want increment('karma') to increment by 1
The second argument may optionally be passed to control the amount by which the column should be incremented or decremented. You do not need to precede the amount with the plus sign either as increment and decrement mean add or subtract respectively

Related

Unique results from the Laravel database 5.8

I am beginner in Laravel. I use in my project Laravel 5.8.
I have schema:
Schema::create('statistics', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->text('agent')->nullable();
$table->date('date')->nullable();
$table->ipAddress('ip');
$table->bigInteger('user_id')->default(0);
$table->bigInteger('quest_id')->default(0);
$table->string('browser', 70)->nullable();
$table->string('platform', 70)->nullable();
$table->string('language', 12)->nullable();
// $table->string('url_address', 160)->nullable();
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
I get statistics from this function:
public function generateStatistics(string $dateFrom, string $dateTo, int $id)
{
return Statistics::whereBetween('date', [$dateFrom, $dateTo])->where('user_id', $id)->get();
}
This function returns all the results from the database to me and works correctly. I need to redo this function to display unique results. Unique result = unique ip on the selected day.
How to do it?
you need to add a dictinct ip
public function generateStatistics(string $dateFrom, string $dateTo, int $id)
{
return Statistics::whereBetween('date', [$dateFrom, $dateTo])->where('user_id', $id)->distinct('ip')->get();
}
or you can group by ip
public function generateStatistics(string $dateFrom, string $dateTo, int $id)
{
return Statistics::whereBetween('date', [$dateFrom, $dateTo])->where('user_id', $id)->groupBy('ip')->get();
}
What do you mean by unique? get the list of distinct IPs on that range? this would be like this:
public function generateStatistics(string $dateFrom, string $dateTo, int $id)
{
return Statistics::whereBetween('date', [$dateFrom, $dateTo])
->where('user_id', $id)
->select('ip')
->distinct()
->get();
}
EDIT: I saw that the thing you want is not the IPs values just the count for the statistics.
Transforming to MYSQL should be something like this (This maybe helps you to your code):
SELECT COUNT(id), ip
FROM statistics
WHERE user_id = {{id}} AND date BETWEEN {{dateFrom}} AND {{dateTo}}
GROUP BY ip;
So this will return the number of request grouped by IP. The SUM of all counts will give you the total of request, the count of IPs will give you the total of UNIQUE request.
To Laravel:
$requestPerIp = Statistics::whereBetween('date', [$dateFrom, $dateTo])
->where('user_id', $id)
->select('ip', DB::raw('count(*) as total'))
->groupBy('ip')
->get();
For the total unique request just:
$numberOfUniqueRequest = count($requestPerIp);

How to use hasOne relationship correctly?

I am learning Laravel and I'm trying to create simple online store.
I created tables Items and Amounts. Now I want to display all Items with their amount in stock but for some reason unknown to me, amount of item is not fetched into items.
These are my schemas for tables:
Items:
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name', 120)->nullable(false);
$table->float('price',8,2)->unsigned()->nullable(false);
$table->longText('short_specification');
$table->longText('specification');
$table->longText('description');
$table->string('photo', 100);
$table->engine = 'InnoDB';
$table->foreign('category_id')->references('id')->on('categories');
});
Amounts:
Schema::create('amounts', function (Blueprint $table) {
$table->integer('item_id')->unsigned();
$table->integer('amount')->unsigned()->nullable(false);
$table->engine = 'InnoDB';
});
Schema::table('amounts',function($table){
$table->foreign('item_id')->references('id')->on('items');
$table->primary('item_id');
});
These are my models:
Item:
class Item extends Model
{
public $timestamps = false;
function amount()
{
return $this->hasOne('App\Amount','item_id','id');
}
}
Amount:
class Amount extends Model
{
function item()
{
//$this->belongsTo('App\Item');
return $this->belongsTo('App\Item','item_id','id');
}
}
When I do:
$items = DB::table('items')->get();
dd($items);
return view('home')->with('items',$items);
Items are displayed correctly, but amount of item isn't there.
When I do:
#foreach($items as $item)
{{ $item->id }}
{{ $item->amount }}
#endforeach
I get:
Undefined property: stdClass::$amount (View: D:\2.
PROGRAMY\xampp\htdocs\silicon_store\resources\views\home.blade.php)
error.
From what I've seen on the web (I've been trying to fix this for over 3 hours now so I must be doing something totally wrong) it should work properly but it isn't.
With $items = DB::table('items')->get();, you're using the query builder. It won't have the value of the relationship unless you join the amounts table in the query.
$items = DB::table('items')
->leftJoin('amounts', 'items.id', '=', 'amounts.item_id')
->get();
I think you could also use an Eloquent query. In that case each $item would be an instance of the Item model rather than a StdClass object.
$items = App\Item::with('amount')->get();
or you can use kind of this query
$items = App\Item::whereHas('amount')->get()
Here link to understanding whereHas

Join using associatif table

I set up a relationship between the following three tables : Card, Event and Presence (associatif table). Presence my associatif table, which contains id_card and id_event. I tried to create a fuction that return $count (number of event foreach member).
But my problem is $count return if the number of all event or zero and the result have been 1
My controller :
$count = DB::table('presences')
->join('cards','cards.id','presences.id_card')
->join('events','events.id','presences.id_event')
->where('presences.date','like','%event.dateEvent%')
->where('presences.qrcode','like','%cards.qrcode_membre%')
->get()
->count();
Model Card :
public function event()
{
return $this->belongsToMany('App\Event');
}
Migration :
$table->bigIncrements('id');
$table->string('nom');
$table->string('prenom');
$table->string('cin');
$table->date('dateNaissance');
$table->date('dateAffection');
$table->string('qrcode_membre')
Model Event :
public function card()
{
return $this->belongsToMany('App\Card');
}
Migration :
$table->bigIncrements('id');
$table->string('libelle');
$table->string('description');
$table->date('dateEvent');
Model Presence :
$table->bigIncrements('id');
$table->date('heureEntree');
$table->date('heureSortir');
$table->date('date');
$table->string('qrcode');
$table->unsignedInteger('id_card');
$table->foreign('id_card')->references('id')->on('cards');
$table->unsignedInteger('id_event');
$table->foreign('id_event')->references('id')->on('events');

Column not found: 1054 Unknown column 'id' in 'where clause' - Laravel

There has been lot of issues on this but i am following the exact procedure to solve this issue as described in the other related S.O questions yet i get the same error.
Shop
public function products()
{
return $this->hasMany('App\Product');
//->withTimestamps();
}
Product
public function shop()
{
return $this->belongsTo('App\Shop');
//->withTimestamps();
}
This is how my schema looks like
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->integer('shop_id')->unsigned()->nullable();
$table->foreign('shop_id')->references('id')->on('shops');
$table->timestamps();
);
Controller
$products = new Product(array(
'name' => $request->('name');
));
$shop->products()->save($products);
After submitting my form data into the products table, i get an error Column not found: 1054 Unknown column 'id' in 'where clause'. Laravel by default seems to take id by default as my primary key but then it is product_id.
In my model, i have specified protected $primaryKey = 'product_id' and it wouldn't solve my problem. What am i doing differently ?
In the relationships you have to specify the name of the primary key when it is not called id, try to change the model like this:
SHOP
public function products()
{
return $this->hasMany('App\Product', 'product_id');
//->withTimestamps();
}
PRODUCT
public function shop()
{
return $this->belongsTo('App\Shop', 'product_id');
//->withTimestamps();
}
In the documentation explains how it works:
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
If you are using resoure routes, then you need to specify the route key name as well:
public function getRouteKeyName()
{
return 'product_id';
}
I had tried with my local with following:
Schema:
Schema::create('shops', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('name');
$table->integer('shop_id')->unsigned()->nullable();
$table->foreign('shop_id')->references('id')->on('shops');
$table->timestamps();
});
Model relationship exactly same as your post.
Controller code:
$shop = new Shop;
$shop->name = 'test';
$shop->save();
$products = new Product;
$products->name = 'test';
$shop->products()->save($products);
And final result? It is saved into products table without error.
I am using Laravel 5.4 at my local.
When it stated Unknown column 'id' in 'where clause' but does it stated is products table? Can you show the full Sql error log?
I suspect it might be other relationship caused the error.

Laravel compare between date field and date now

I am trying to compare between date field that saved to my database and current date!
The circle is:
admin will add a new career with deadline date
when someone fill the application he/she will see the available jobs only in drop down list ( that its deadline date less than the current date )
so this is the Jobs model
protected $fillable = ['job_name','job_req', 'expire'];
this is jobs migrations
public function up()
{
Schema::create('jobs', function(Blueprint $table)
{
$table->increments('id');
$table->string('job_name');
$table->string('job_req');
$table->date('expire');
$table->timestamps();
});
}
public function down()
{
Schema::drop('jobs');
}
this is the ApplicationController.php
public function create()
{
$dt = Carbon::now()->toDateString();
$jobs = Jobs::get()->where('$dt', '<', 'expire');
return view('post.create',compact('jobs'));
}
Now when i open application form it doesn't returns any job title, but when i remove where clause from the controller it works well!
change
$jobs = Jobs::get()->where('$dt', '<', 'expire');
to
$jobs = Jobs::where('expire', '>', $dt)->get();
->get() will do query instantly, you must use ->where() before it.
Use ->where after ->get(), you will call this function
http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Collection.html#method_where

Categories