To write the given query in Laravel with Eloquent relation, you can use the selectRaw method to write the subquery and then use the fromSub method to use it as a subquery in the main query. Here's an example:
$subquery = DB::table('sales')
->select('productCode', 'quantity', 'salesDate')
->where('productCode', '1001000029')
->where('salesType', 0)
->where('quantity', '>', 0)
->orderByDesc('salesDate')
->limit(3);
$salesdataByProduct = $row->sales()
->select('*')
->fromSub($subquery, 'sales')
->get();
In this example, we first create the subquery using the DB::table method and the various query builder methods to build the query. We then use the selectRaw method to select the columns we want.
In the loop, we use the fromSub method to use the subquery as a table in the main query. We pass the subquery and a table alias to the fromSub method, and then use the select method to select all columns from the subquery.
Note that we use the get method instead of the find method to retrieve the results, since the subquery may return multiple rows.