How can i get last inserted row By using Laravel DB::table()->insert()? - laravel

I user this code for insert data .
$conv = DB::table('conversations')
->insert([
'is_seen' => $other_user_id,
'user_one' => $user_id,
'user_two' => $other_user_id,
'user_one_status' => 1,
'user_two_status' => 0,
'message_status' => 0,
'last_message' => $messageCon
]);
Its return true false value. I need last inserted row.

Assuming there's a reason you're not using Eloquent, you could use insertGetId.
$conv = DB::table('conversations')
->insertGetId([
'is_seen' => $other_user_id,
'user_one' => $user_id,
'user_two' => $other_user_id,
'user_one_status' => 1,
'user_two_status' => 0,
'message_status' => 0,
'last_message' => $messageCon
]);
Caveats from the documentation:
Auto-Incrementing IDs
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method.

Insert cant return whole row.
You can change it to insertGetId and then select it from database by that id.
Or use models, and use create method (Conversation::create([...]))

Related

save both field same name relationship one to one backpack laravel

I have two tables with relationship one to one hasOne and have column same name
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'new_title', // the db column for the foreign key
]);
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'achive.new_title', // the db column for the foreign key
'entity' => 'achive',
]);
I just want show once but save both to two table
You need something that's call the callbacks method, the simplicity of that method is you can control what you want after create, edit, delete and etc.
So, in your controller just need one field name,
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'new_title',
]);
After that, you can create a new trait in your controller for creating/updating your relationship,
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation { store as traitStore; }
And then, declare the store function,
public function store() {
// Get the value from the request
$request = $this->crud->getRequest();
// And then you can insert/update data into your relationship table
\DB::table('achives') // Your relation table
->updateOrInsert(
['new_title' => $request->new_title],
['other_column_name' => 'Value of your other column']
);
$response = $this->traitStore();
// do something after save
return $response;
}
The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated. more info here

How to increment column with Laravel Eloquent updateOrCreate()?

Is it possible to return the model id from the request below ?
Bar::insert([
'foo_id' => Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
])->increment('count')->id
]);
I also tried this:
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('count + 1')
])->id
But it doesn't work at inserting because it count is not yet set.
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("id", "name", "count") values (123, Hello, count+1) returning "id")
=== EDIT ===
With DB::raw('IFNULL(count,0) + 1'), I'm getting:
SQLSTATE[42703]: Undefined column: 7 ERROR: column "count" does not exist
LINE 1: ... ("code", "name", "count") values ($1, $2, IFNULL(count,0) +...
^
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("code", "name", "count") values (123, Hello, IFNULL(count,0) + 1) returning "id")
Unfortunately I don't think this is possible to reference the count column only when the update happens (since this is what is happening here). You will need to take the roundabout way:
$model = Foo::firstOrNew([
'code' => $row[0],
'name' => $row[1]
]);
$model->count = ($model->exists ? $model->count : 0) + 1;
$model->save();
Here $model->exists will be true if the model was retrieved from the database or false if a new one was created.
Efficiency-wise firstOrCreate is what updateOrCreate does anyway so there's no query cost added
try using IFNULL
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
])
if you want the id, try it like this:
$id=(Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
]))->id;
note: this is working on mysql, not PostgreSQL
you just need to set column auto-increment in database and not need set it column in your eloquent

How do I get a value of another table on Laravel?

I'm trying to get just value of id column on a table but it returns
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '[{"id":1}]' for column 'id_jenis' at row 1 (SQL: insert into `pesanan` (`name`, `telpon`, `alamat`, `id_jenis`, `jenis`, `do`, `updated_at`, `created_at`) values (Pradita Candrani, 0813, Jalan Sunan Ampel Kasin, [{"id":1}], Cuci Basah Standar, None, 2019-11-27 12:18:35, 2019-11-27 12:18:35))
Here it is my code on Controller
public function pesan(Request $request){
$harga = Harga::select('id')->where('nama',$request->jenis)->get();
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => $harga,
'jenis' => $request->jenis,
'do'=>$request->do
]);
return redirect('/pesanan');
}
how can I fix this? Please help
You're getting object now and passing it to id_jenis directly. use first() instead of get(). and pass the $harga->id in id_jenis.
$harga = Harga::select('id')->where('nama',$request->jenis)->first();
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => $harga->id,
'jenis' => $request->jenis,
'do'=>$request->do
]);
If you want to store multiple ids in id_jenis then use pluck.
$harga = Harga::where('nama',$request->jenis)->pluck('id')->toArray();
Here you'll get multiple ids in array. so use json_encode to store JSON in db as below.
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => json_encode($harga),
'jenis' => $request->jenis,
'do'=>$request->do
]);
$harga = Harga::select('id')->where('nama',$request->jenis)->get();
After this line, write
\Log::info(['Harga', $harga]);
and check the latest file and error in /storage/logs/laravel.log
Welcome to the wonderful world of debugging

Laravel relationship with method "with" returns null

Today I wanted to do some clean code so just started selecting columns for with relationship. With this code:
\App\Genre::with([
'family'
])->where([
'slug' => $slug,
'is_active' => true
])->first();
everything is working fine. But when I start selecting columns for "with" method:
\App\Genre::with([
'family' => function ($query) {
$query->select('name_pl', 'name_lat');
}])->where([
'slug' => $slug,
'is_active' => true
])->first();
I got that family is null (but it should be an object with columns: name_pl, name_lat). What I am doing wrong?
family method in Genre class looks like this:
public function family () {
return $this->belongsTo(Family::class);
}
I am using Laravel 5.4
Pretty sure you need to add a related column to the list of selected columns, otherwise Laravel won't b able to match the data to eager-load.
Assuming that Genre has a family_id and Family has an id primary key column specified, you need this:
$query->select('id', 'name_pl', 'name_lat'); // See the id added here?
Should do the trick.
For clarity, the matching I mentioned is this one:
select * from genre
select * from family where id in (1, 2, 3, 4, 5, ...)
-- where the comma-separated list of IDs consists of the unique family_id values retrieved in the first query.
Why don't you try:
\App\Genre::with('family:name_pl,name_lat')->where([
'slug' => $slug,
'is_active' => true
])->first();

how to get rid of primary column in doctrine queries

Doctrine always includes an ID column in a query, for example:
$new_fees = Doctrine::getTable('Stats')->createQuery('s')
->select('s.sid')->where('s.uid = ?', $this->uid)
->andWhere('s.operation = ?', PPOperationType::FEE_PAID_BY_REFERRED_OWNER)
->andWhere('s.created_at > ?', $lastwd)
->groupBy('s.sid')->execute();
won't work, because s.id is included (which I didn't ask doctrine for). How do I get rid of that id column? Having to use a raw SQL here kills the usefulness of doctrine.
You have to set some column of that table to be the primary in the setTableDefinition, so that doctrine doesn't use default primary as id.
Let's say you sid is you actual primary key.. then...
public function setTableDefinition(){
....
$this->hasColumn('sid', 'decimal', 2, array(
'type' => 'decimal',
'length' => 2,
'unsigned' => 0,
'primary' => true,
'default' => '0',
'notnull' => true,
'autoincrement' => false,
));
}
Notice the 'primary' => true, this prevents doctrine to use id as the default primary key (even when it's not even defined in the table definition file.
This isn't the prettiest solution, but you can call isSubquery(true) on the Doctrine_Query to remove the primary key, in your case s.id.
http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_query.html#isSubquery()

Resources