Getting a specific string different from the first ()

I have a little problem with laravel that can be easily solved. In short, the situation is this: I have two tables, one for users, and the other for products with a "user_id" column, so I can identify the associated user.

In Laravel I can use

$user = Sentry::getUser();        //Or Auth::user() if you're not using Sentry
$products = DB::table('table2')->where('user_id',$user->id);

And that should give me every product the user has. Good.

Now I want to show products individually on the screen, but unfortunately this does not work. It seems that I cannot repeat this information in a row, because it consists of several lines. I get

Object of class Illuminate\Database\Query\Builder could not be converted to string

For the solution, since the maximum associated products that I allowed in the system are 3, I came up with the idea to split each line and repeat them. For the first, this is simple: $products->first();but I have no idea how to get the other two.

And maybe I'm new here, but I don’t think I can use product identification information since $ products-> id returns an error.

Can anybody help me?

Thanks in advance!

+4
source share
3 answers

You want to use it take, limit the number of results to three, and then print each of them using the foreach loop. Documents: Laravel Requests, see skipandtake .

$products = DB::table('table2')->where('user_id',$user->id)->take(3)->get()

:

@foreach($products as $p)

, PHP , - :

foreach ($products as $product) { var_dump($product); }

( , , . , ($product) .)

+2

, : all, get first.

all:

$products = DB::table('table2')->all();

.

first, , , :

$products = DB::table('table2')->where('user_id',$user->id)->first();

get, , , :

$products = DB::table('table2')->where('user_id',$user->id)->get();

, get .

+1

When you use

$products = DB::table('table2')->where('user_id',$user->id);

Then $ products is an array and you don't need an echo array. To display products, you need to use the foreach loop, as shown below.

foreach ( $products as $key => $product ) {
   var_dump( $product );
}

If you want to show only three products, you can use a loop for inside foreach .

You can learn more about foreach from the link below.

http://php.net/manual/en/control-structures.foreach.php

0
source

Source: https://habr.com/ru/post/1569189/


All Articles