john clyde dagpin
john clyde dagpin

Reputation: 11

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');

Upvotes: 0

Views: 52

Answers (2)

Mohammad Akbari
Mohammad Akbari

Reputation: 446

You must use double-quote instead of single-quote

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

Upvotes: 0

oreopot
oreopot

Reputation: 3450

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();

Upvotes: 3

Related Questions