Skip to content
Advertisement

How to use the passed data in to a sql query?

How do I pass the $id into my $record SQL query and what is the eloquent query as well?

I want to do this because the user_id is the foreign key from borrows. I want to pull data from payment_records that have the same id with the selected id.

This is the show method where I passed the id and do the query:

public function show($id)
{
    //the eloquent pull from borrows
    $borrows = borrows::find($id);

    $record = DB::select('SELECT `id`, `balance`, `amount_due`, `current_balance`, `created_at`, `updated_at`, `user_id` FROM `payment_records` WHERE user_id = 45');
    
    // $borrows = DB::select('select * from borrows, payment_records where id = $id');
    
    return view('borrows.show')->with('borrows', $borrows)->with('record',$record);
}

This is the query where I want to use the id to compare with user_id:

$record = DB::select('SELECT `id`, `balance`, `amount_due`, `current_balance`, `created_at`, `updated_at`, `user_id` FROM `payment_records` WHERE user_id = 45');

Advertisement

Answer

I think you are after something similar:

$users = DB::table('payment_records')
             ->select('id', 'balance', 'amount_due', 'current_balance', 'created_at', 'updated_at','user_id')
             ->where('user_id', '=', $id) // `$id` is used here
             ->get();

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement