Insert from select in laravel using eloquent - php

I am using laravel 8. I want to insert multiple rows by selecting from one table to another. I am using DB::statement() but now want to do it using eloquent. Here is my sample code:
DB::statement("insert into bank_information (user_id, bank_id, account_name,account_number)
select applicant_id,bank_id,account_name,account_number from applicant_bank_information
where erec_applicant_bank_information.applicant_id =".$applicant_id);
How can I do it using single eloquent command ? Also, Is there any other smarter/faster way for it in laravel ??

I do not know of a Eloquent way for this, but after Laravel 5.7.17 we have a new method in the query builder insertUsing(). Unfortunately this is not mentioned in the official documentation.
The query builder code will be something like this:
$select = DB::table('applicant_bank_information as abi')
->select('applicant_id','bank_id','account_name','account_number')
->where('abi.applicant_id', $applicant_id);
$rows_inserted = DB::table('bank_information')
->insertUsing(['user_id','bank_id', 'account_name','account_number'], $select);
Tested and working. Keep in mind that you do not run the select request with ->get().

Related

Question: how to use and with where in laravel

when I want to get data from a database in native PHP I use queries but in laravel, you don't write queries you use their model and their functions to get the data for example:
ex::where('name','test')->get();
in native PHP:
select * from ex where name='test'
and my issue is I don't know how to use and like this query:
select * from ex where name='test' and id='5'
I searched and looked thru the documentation but no answer was found.
Just put another where, its really simple just put it like this
ex::where('name', 'test')->where('id', 5)->get();
//or if you want directly the instance and not a collection
ex::where('name', 'test')->find(5);
If you want to use the OR operator you can also do something like this
ex::where('name', 'test')->orWhere('id', 5)->get();
More in documentations
There is no 'AND' with where in Laravel Eloquent.
You have to write another 'where' with the required condition.
Another way is: run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, delete, and statement.
Ex. DB::statement("UPDATE teachers SET price = ".$price." where id=".$id." AND status='A'");
Do not forget to use DB

Show countif mysql query table to html

I have a countif query in mysql and I would like to show the table on my html. I'm currently using laravel 6.0 framework.
Here is the picture of the table i want to show:
Here is my code in html:
Here is my code in the controller:
There should be numerous errors with index function in your controller. Specifically with how you are trying to assign $count a value. Read these: Eloquent Methods all() vs get(), Eloquent Selects, Eloquent Ordering, Grouping, Limit and Offset, Eloquent Where.
Laravel has an excellent documentation, if you were to follow it - working with Laravel would become much easier.

Query Builder and find records from one table which don't exist in another using laravel

I am using Laravel 5 and its Query Builder to retrieve data from database.
I want to take following output.
I want to take this question thinks using Query Builder
Now I try this code, but not successfully:
$all_members = CommiteeMember::join('members', 'commiteeMembers.memberId', '<>', 'members.id')
->where('commiteeId', $commitee->id)->get();
I don't know what are you trying to achieve.
But from your title looks like what you need is left join.
$all_members = CommiteeMember::leftJoin('members', 'commiteeMembers.memberId', '<>', 'members.id')
->where('commiteeId', $commitee->id)->get();

Laravel Query Builder where max id

How do I accomplish this in Laravel 4.1 Query Builder?
select * from orders where id = (select max(`id`) from orders)
I tried this, working but can't get the eloquent feature.
DB::select(DB::raw('select * from orders where id = (select max(`id`) from orders)'));
Any idea to make it better?
You should be able to perform a select on the orders table, using a raw WHERE to find the max(id) in a subquery, like this:
\DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();
If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON or toArray will not work without using Eloquent models.
$order = Order::whereRaw('id = (select max(`id`) from orders)')->get();
That, of course, requires that you have a model that extends Eloquent.
class Order extends Eloquent {}
As mentioned in the comments, you don't need to use whereRaw, you can do the entire query using the query builder without raw SQL.
// Using the Query Builder
\DB::table('orders')->find(\DB::table('orders')->max('id'));
// Using Eloquent
$order = Order::find(\DB::table('orders')->max('id'));
(Note that if the id field is not unique, you will only get one row back - this is because find() will only return the first result from the SQL server.).
Just like the docs say
DB::table('orders')->max('id');
For Laravel ^5
Orders::max('id');
I used it is short and best;
No need to use sub query, just Try this,Its working fine:
DB::table('orders')->orderBy('id', 'desc')->pluck('id');
Laravel 5+:
DB::table('orders')->orderBy('id', 'desc')->value('id');
For objects you can nest the queries:
DB::table('orders')->find(DB::table('orders')->max('id'));
So the inside query looks up the max id in the table and then passes that to the find, which gets you back the object.
You can get the latest record added to the Orders table you can use an eloquent method to retrieve the max aggregate:
$lastOrderId = Order::max('id');
To retrieve a single row by the id column value, use the find method:
$order = Order::find(3);
So combining them, to get the last model added to your table you can use this:
$lastOrder = Order::find(Order::max('id'));

Laravel 4 Build Query where clause on the fly

I am porting my code from CodeIgniter to Laravel. and have some question regarding the query builder.
In codeigniter, I can just add where clause to the active record object, as I initialize each property in a class like
$this->db->where('xxxx','bbbb');
in one property initialize function, and
$this->db->where('yyyy','aaaa');
in another property function, and it will all chain up until i fire off the query. But this doesn't seem to be the case of Laravel.
Here is what I do in laravel in each property initialize function
DB::table($this->table)->where('xxxx','bbbb');
DB::table($this->table)->where('yyyy','aaa');
and when a actual method is call from outside, it runs
DB:table($this->table)->get();
but this gives me a SELECT * FROM TABLENAME without anywhere clause. So what am I doing wrong here :x or I just shouldn't treat laravel same as codeigniter and think of something totally different to handle this kind of dynamic where clause?
Also in codeigniter, you can set a section of the query to cache, so even after you fire off the query , those section retains for next query, usually the where clause. Is there a similar function in Laravel? Thank you!
You can assign your current workings to a variable, and build upon that, let me show you an example based on your example:
Instead of this
DB::table($this->table)->where('xxxx','bbbb');
DB::table($this->table)->where('yyyy','aaa');
Try this...
$query = DB::table($this->table)->where('xxxx','bbbb');
$query->where('yyyy','aaa');
$results = $query->get();
I just shouldn't treat laravel same as codeigniter and think of something totally different to handle this kind of dynamic where clause?
This is not dynamic where clause.
and please, make a habit of reading the documentation.
From the docs of Fluent query builder
$users = DB::table('users')->where('votes', '>', 100)->get();
you can set a section of the query to cache, so even after you fire off the query , those section retains for next query, usually the where clause. Is there a similar function in Laravel?
$users = DB::table('users')->remember(10)->get();
Next time, just open up the docs. they contain all this.

Categories