Greg Ostry Greg Ostry -3 years ago 151
PHP Question

How to build a query in Laravel

I'm new to laravel and have some problems with the understanding how the query builder is working.

I created a laravel project and connect it successfuly to the sqlsrv. And now i would like to retrive data from the database.

For first without models just in the

wep.php
for understanding.

Route::get('/tasks', function () {
$tasks = DB::table('WebShops')->get();
dd($tasks);
});


This is working it shows me all the db rows.

Now i would like to filter the rows with
find
command and i get an error:

Route::get('/tasks/{ShopID}', function($ShopID){
$task = DB::table('WebShops')->find($ShopID);
dd($task);
});



SQLSTATE[42S22]: [Microsoft][ODBC Driver 11 for SQL Server][SQL
Server]
Invalid column name "id". (SQL: select top 1 * from
[WebShops] where [id] = 1)


This is confusing because i assigned find to the
ShopID
and now i get the error that is searching for an
id
. Why ?

I tried also this:

Route::get('/tasks/{ShopID}', function($ShopID){
$task = DB::table('WebShops')->where('ShopID', $ShopID);
//dd($task->name); here comes also an error
dd($task);

});


This is showing me a big array with the data that i don't really understand.

enter image description here

My DB look like this:
enter image description here

Answer Source

In code

Route::get('/tasks/{ShopID}', function($ShopID){
    $task = DB::table('WebShops')->find($ShopID);
    dd($task);
});

you try to find rows where what field is equal to $ShopID value?

Laravel doesn't know. So, it assumes, you have field id as a primary key. As you don't have such field, according to your table structure, you have an error.

According to manual, you can redefine primary key with:

public $primarykey = 'ShopID';

in your model file.

In second attempt, to receive collection of records - add get():

Route::get('/tasks/{ShopID}', function($ShopID){
    $task = DB::table('WebShops')->where('ShopID', $ShopID)->get();
    dd($task);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download