Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Birdy's avatar

Eloquent Insert from Select

Hi all,

I’m creating a small application for a specific industry where there are two kinds of end users, a provider in basic terms (A seller) and a user in basic terms (A Buyer).

The user visits the site and requests a free instant quotation/estimation for the service they require, my whole goal for the project is to enable automation for the providers, this is so a provider can send estimations based on the budget the user selects during the form process.

So if a user selects a budget of let’s say £200, The provider will have a default estimation set for that price range within their account management dashboard.

To make it fair we only show 5 estimations to the user per quotation request and we do this by using the random function shipped within laravel and then use the orderBy function to refactor the view in desc order.

The only problem I have is that I’m not advanced with laravel as of yet I’m un sure as to how I can insert the visible 5 estimations provided to a database named saved_estimations so when the user comes back to their account and clicks to view the quotation again the model and controller does not reorder the list in any way from the orderBy or random functions.

So in other words I either only want this to happen once per project id and save the selected 5 providers id's and their estimated prices to a table or if there is another simple way round it as in my view I use a foreach loop to loop through the collect of 5 random selected providers ordering their estimated prices in a descending order.

-- Small update -- Would it be simple enough to just insert the results from the first query where i select the random 5 providers and their estimated prices directly straight into the saved_estimations table, If so what would be the best and most secure way of doing that?


Any input or advice would be greatly appreciated on this.

Thanks

0 likes
8 replies
StormShadow's avatar

@Birdy

Yes, you'd have to save the estimates somehow in another table, because as you mentioned that's the only way of guaranteeing that every time the client views the estimates they are the same and not random.

One approach could be: in the controller see if the records exist in the saved_estimations table for that quotation request id, if so return them to the view. If they don't, generate them with your random query, save them in your saved_estimations table and return them to the view. The next time the controller is hit, they will exist and be returned.

Hope that helps

1 like
Birdy's avatar

@StormShadow

As a novice to laravel and still learning the ins and outs after watching as many tutorials from Jeffery and other channels im not to advanced with the query builders as of yet, How would you recommend being able to insert all 5 results into the saved_estimations table if they dont already exist from the collection that is being sent to the view, That may sound like a silly question to you but the reason i ask is because the only way i know how to present the data in the view the way i need it is within a foreach loop so say for example i had a query that i want to send them to the saved_estimations table was to look like this:

DB::table('saved_estimations')->insert(array( 'project_id' => $projects->project_id, 'providers_id' => $providers->providers_id, 'category_id' => $projects->category 'bid_price' => BidsTable::orderBy('bid_price', 'desc')->first()->bid_price ));

I think it would cause issues trying to insert the 5 given results that im refering to if the query was to look something like the above am i right in what im thinking?

Much appreciate your time for helping out, Thanks.


Update:

It seems to me that the only way of doing it so that all 5 results get inserted on the same query as such, Would be to use a foreach on the actual query if thats possible, and have the query insert the values into the required collumns then end the foreach loop after its looped through the 5 results it should have done 5 seperate inserts to the table something like:

saved_estimations table after the foreach loop has inserted the result from the inital query.


id 1 ... ... ... ... ... ... 2 ... ... ... ... ... ... 3 ... ... ... ... ... ... 4 ... ... ... ... ... ... 5 ... ... ... ... ... ...


Do you think thats possible?

Thanks

Birdy's avatar

@StormShadow

Ive done some custom php work in my controller and come up with the following, This works tempory and im hoping i can work on making it a little better and more cleaner, Possibly even refactor it to a more suitable laravel 5.2 version.

Whats your thoughts,

    $results = $bidders;
    foreach($results as $row){
        $project = $projectid;
        $category = $row->category_id;
        $provider = $row->service_providers_id;
        $bidprice = $row->bid_price;
        $propvalue = $row->property_value_id;

        DB::table('static_bids')->insert(array(
            'project_id' => $project,
            'category_id' => $category,
            'service_providers_id' => $provider,
            'bid_price' => $bidprice,
            'property_value_id' => $propvalue
        ));
      }

Thanks

StormShadow's avatar
Level 51

@Birdy First of all no problem, happy to help! Secondly welcome to Laravel!

Yes try to minimize database queries when you can. Laravel has a way to do multiple inserts in a single query. If you look at the docs you want to do something like this (in this case it is inserting two rows at once) :

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]); 

So what you have to do is first get the results from your random quote query that you are passing to your view. Then loop through the results and build up an array containing all of the data you need to insert into your saved_estimations table.

So I'm guessing something like this

//initialize array
$inserts = [];

$bids = [insert your random query here]

foreach($bids as $bid) {
    $inserts[] = [ 'project_id' => $projects->project_id,
           'providers_id' => $providers->providers_id, 
           'category_id' => $projects->category , 
           'bid_price' => $bid->bid_price]; 
}

DB::table('saved_estimations')->insert($inserts);

2 likes
StormShadow's avatar

@Birdy I just saw your code above. That would work but the problem is you would be doing an insert for every result. I think it would be better to just build up an array and do the inserts all in one go. Its generally better to try to minimize round trips to the database.

2 likes
Birdy's avatar

And this is why asking for help now and again can really pay off :) !

I Really appreicate that, I have gone through a lot of the docs but as im still on the starting line with laravel it is somewhat difficult at times to know exactly what to research when it comes down to the terms used and phrases refered to.

I must say laravel has become something of a superstar in my eyes though more time consuming when your first starting out just because of the reasons i say above, Other than that it can save you a lot of coding and repeating yourself over and over like you would hard coding without OOP or Frameworks.

Again, Much appreciated and i thank you for taking time out to lend a helping hand, Enjoy your weekend :)

StormShadow's avatar

No problem at all! Good luck with your learning and with your project! Laravel is one of the best frameworks out there, once you know the basics it is incredible how productive you can be. It appeals to both novice and experienced programmers alike. As with all things in the dev world there is so much to know, almost too much for any one person! The best we can do is take one day at a time and support one another in the journey.

Cheers mate

1 like
StormShadow's avatar

@Birdy whoops looks like there is a Laracasts forum bug because I received your reply via Email as I was subscribed to the thread but I cant see it on here, oh well.

i need to figure a way to check if there is already 5 rows inserted in the saved_estimations table with the same following fields: project_id, category_id, property_value_id and if there is then either update them or skip the process entirely and move to the next step. I have tried a few different ways but not yet found a way to get this work.

Perhaps something like this?

$bids = DB::table('saved_estimations')->where([ 'project_id' => $project_id, 
'category_id' => $category_id,  
'property_value_id' => $property_value_id])->get();

if( $bids ) {
  
   return view('your-view', compact('bids'));

} else {

    $inserts = [];

    $bids = [insert your random query here]

    foreach($bids as $bid) {
        $inserts[] =  ['project_id' => $project_id,
            'category_id' => $category_id,
            'service_providers_id' => $service_providers_id,
            'bid_price' => $bid->bid_price,
            'property_value_id' => $property_value_id]; 
    }

    DB::table('saved_estimations')->insert($inserts);

     return view('your-view')->with('bids', $inserts);
}

Let me know if this helps or if you have any more questions :)

Note: take this code as just a guide I don't know what your database tables or your random query looks like or what is required in your views ;)

Please or to participate in this conversation.