0

How can I select a column from a db and store it in a variable in the controller to operate with it? I’m starting on php/laravel I tried this

 $nametable = DB::table('nametable')->get();
 $variable =  $nametable->nameofcolumn;

And i tried this too:

$variable = DB::table('nametable')->select('nameofcolumn')->where('id', 1)->first();

1 Answer 1

1

The DB facade, in your second case, will return an object. You can then access the name of the column using the -> operator.

For example:

$result = DB::table('table')
    ->select('column')
    ->where('id', 1)
    ->first();

To access the column, you would then do

$result->column; 

The following can also be a decent alternative:

$variable = DB::table('table')
    ->where('id', 1)
    ->value('column'); // The value is returned directly. 

Now, in your first case:

$results = DB::table('nametable')
    ->get();

This, would return an instance of Collection. You would then need to loop over the collection to access individual rows

foreach($results as $result) {
    echo $result->column; // for example
}

You could also play around with this example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.