Ahmadz Issa
Ahmadz Issa

Reputation: 765

How to pass id from while loop to controller [laravel]

I'm new to laravel, so I'm searching for how to send a specific id to the controller in order to get data from another table ?

For example

while($shipment = sqlsrv_fetch_array($get_customer_rule,SQLSRV_FETCH_ASSOC)) {

    //display some data ......

    // inside the loop i will have another query to get data from another table has //relation with shipment table

    $id = $shipment['id'];
    $customer = "SELECT * FROM [ccctadm].[customer] WHERE id = '$id' ";

    $get_customer_info = sqlsrv_query($conn, $customer);
    $get_customer_id = sqlsrv_fetch_array($get_customer_info,SQLSRV_FETCH_ASSOC);

    $customer_id = $get_customer_id['customerid'];
}

I can't write query in while loop in laravel, so how can I pass shipment id to the controller so I can get customer data related to the shipment

Upvotes: 0

Views: 1378

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Since you are new to Laravel, maybe you should learn the Laravel way first. Watch this video on how to work with Eloquent and perhaps every other video in that series. https://laracasts.com/series/laravel-from-scratch-2017/episodes/7

Once you get your head around that, you will be able to rewrite your query as

$shipments = Shipement::all();
foreach( $shipments as $shipment ) {
    $customer = $shipment->customer;
    $customer_id = $customer->id;
}

Even better when you get a bit further with laravel and be able to work with eager loading, you will just do

$shipments = Shipment::with('customer')->get();

And in your view

@foreach($shipments as $shipment)
    Customer ID is : {{ $shipment->customer->id }}
@endforeach

You have decided you to work with Laravel. Take advantage of it. It will make everything easier and speed up your development process.

If you want to stick to your raw SQL queries, you can use the query builder

$result = DB::select("SELECT * FROM [ccctadm].[customer] WHERE id = ?", [$id]); 

And work with the result

Upvotes: 2

Related Questions