22

I make a table with number 22 as the column name. How to access this column?

enter image description here

content:

enter image description here

I've tryed thest

$obj = Tablename::find(1)->first();
$obj->22;
$obj->'22';   //'syntax error, unexpected ''22''
$obj->"22";
$obj->`22`;
$obj[22];
$arr = $obj->toArray();
var_dump($arr); //  array(15) { ["id"]=> string(2) "25" ["out_trade_no"]=> string(14) "14847080930025" ["22"]=> string(0) "2"
$arr[22];       // 'ErrorException' with message 'Undefined offset: 22'
$arr['22'];     // 'ErrorException' with message 'Undefined offset: 22'
$arr["22"];     // 'ErrorException' with message 'Undefined offset: 22'
$arr[`22`];     // 'ErrorException' with message 'Undefined index: ' in
$arr[{'22'}];   //  'syntax error, unexpected '{', expecting ']'' in

none works.

edited as the answer implemented: also get null.

var_dump($orders[0]);
var_dump($orders[0]->id);
var_dump($orders[0]->{'22'});
$col = '22';
$res = $orders[0]->{$col};
var_dump($res);

output:

object(Order)#537(21){
    [
        "connection": protected
    ]=>NULL[
        "table": protected
    ]=>NULL[
        "primaryKey": protected
    ]=>string(2)"id"[
        "perPage": protected
    ]=>int(15)[
        "incrementing"
    ]=>bool(true)[
        "timestamps"
    ]=>bool(true)[
        "attributes": protected
    ]=>array(15){
        [
            "id"
        ]=>string(2)"25"[
            "out_trade_no"
        ]=>string(14)"14847080930025"[
            "22"
        ]=>string(1)"2"[
            "user_id"
        ]=>string(2)"49"[
            "product_name"
        ]=>string(4)"test"[
            "amount"
        ]=>string(1)"3"[
            "fee"
        ]=>string(4)"0.03"[
            "address_id"
        ]=>string(1)"3"[
            "trade_status"
        ]=>string(13)"TRADE_SUCCESS"[
            "express_name"
        ]=>string(0)""[
            "express_no"
        ]=>string(0)""[
            "buyer_email"
        ]=>string(0)""[
            "modify_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "created_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "updated_at"
        ]=>string(19)"2017-01-18 10:55:26"
    }[
        "original": protected
    ]=>array(15){
        [
            "id"
        ]=>string(2)"25"[
            "out_trade_no"
        ]=>string(14)"14847080930025"[
            "22"
        ]=>string(1)"2"[
            "user_id"
        ]=>string(2)"49"[
            "product_name"
        ]=>string(4)"test"[
            "amount"
        ]=>string(1)"3"[
            "fee"
        ]=>string(4)"0.03"[
            "address_id"
        ]=>string(1)"3"[
            "trade_status"
        ]=>string(13)"TRADE_SUCCESS"[
            "express_name"
        ]=>string(0)""[
            "express_no"
        ]=>string(0)""[
            "buyer_email"
        ]=>string(0)""[
            "modify_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "created_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "updated_at"
        ]=>string(19)"2017-01-18 10:55:26"
    }[
        "relations": protected
    ]=>array(0){

    }[
        "hidden": protected
    ]=>array(0){

    }[
        "visible": protected
    ]=>array(0){

    }[
        "appends": protected
    ]=>array(0){

    }[
        "fillable": protected
    ]=>array(0){

    }[
        "guarded": protected
    ]=>array(1){
        [
            0
        ]=>string(1)"*"
    }[
        "dates": protected
    ]=>array(0){

    }[
        "touches": protected
    ]=>array(0){

    }[
        "observables": protected
    ]=>array(0){

    }[
        "with": protected
    ]=>array(0){

    }[
        "morphClass": protected
    ]=>NULL[
        "exists"
    ]=>bool(true)[
        "softDelete": protected
    ]=>bool(false)
}string(2)"25"NULLNULL

Edit: acording to Paras's comment

enter image description here

Edit2: to make question simple and clear:

migration:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Test extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tests', function($table)
        {
            $table->increments('id');
            $table->integer('22');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }

}

Model:

<?php
class Test extends Eloquent
{
}

Controller:

public function show()
{
    $tests = Test::all();
    foreach($tests as $test)
    {
        Log::info($test->id);
        Log::info($test->{'22'});
        Log::info($test->{"22"});
        Log::info($test->getAttribute("22"));
    }
}

data table:

enter image description here

and the log:

[2017-02-25 09:16:48] production.INFO: 1 [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO: 2 [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
  • 3
    The only thing you didn't try: `->{'22'}` – Marty Jan 18 '17 at 04:50
  • 1
    @Marty will you explain it more, what's the issue here, or where i can refer to ? thank you very much. – LF00 Jan 18 '17 at 04:52
  • Any reason it has to be called `22`? The quickest fix, and the best solution, would be to rename it as a string indicating what it is – WebKenth Feb 21 '17 at 09:58
  • @WebKenth I agree with you here. I just find a substitute way when I've no possibility to modify the database table. Thank you all the same. – LF00 Feb 21 '17 at 10:24

13 Answers13

12

You can use the following syntax, as found in the variable variables topic in the PHP documentation:

$obj->{'22'};

...

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Marty
  • 39,033
  • 19
  • 93
  • 162
5

Try this:

$obj->getAttributeValue("22");

Please post the error if it doesn't work

Paras
  • 9,258
  • 31
  • 55
  • $pri = Cloud_printer::all(); foreach($pri as $v) { Log::info($v->getAttributeValue("22")); } production.ERROR: exception 'BadMethodCallException' with message 'Call to undefined method Illuminate\Database\Query\Builder::getAttributeValue()' – LF00 Feb 23 '17 at 11:23
  • This doesn't make sense. `getAttributeValue` is a function of an Eloquent model. What **version** of Laravel are you using? – Paras Feb 23 '17 at 17:22
  • Also could you post the output of `dd($pri)`? – Paras Feb 23 '17 at 17:31
  • check the question – LF00 Feb 24 '17 at 02:31
  • Looks like Cloud_Printer is not an Eloquent model. It seems to be a custom class. Please post the code of this class – Paras Feb 24 '17 at 04:51
  • getAttribute works here, just like nvisser's answer http://stackoverflow.com/a/42354778/6521116 but get empty value. – LF00 Feb 24 '17 at 04:54
  • @KrisRoofe post the Cloud_Printer class code. I think it may be a problem in the class – Paras Feb 24 '17 at 17:08
  • Paras you check the question now. Thanks for you time and impatience. – LF00 Feb 25 '17 at 01:23
  • `class Test extends Eloquent` doesn't make sense. Please post the actual code snippet. Posting test snippets wont help you. There's no Eloquent class, it should be `class Test extends Model` where Model refers to `Illuminate\Database\Eloquent\Model` – Paras Feb 25 '17 at 17:46
  • If you post the actual code, we can help. Otherwise, there's no way anyone can help you – Paras Feb 25 '17 at 17:47
3

Try this:

$col = '22';
$res = $obj->{$col};
var_dump($res);
Thanh Nguyen
  • 5,174
  • 11
  • 43
  • 74
3

if you always know the name is 22, you can do this.

 $myfield = 22;
 dd($obj->$myfield);

I tested it and it returns the value in the 22 field correctly.

Onix
  • 2,129
  • 2
  • 17
  • 26
3

Best way is NOT to use Integer as a fieldname. It is bad praxis. But if you need, you should access the database with raw method:

public function show()
{
     $tests = DB::table('test')
        ->select("22 as twentytwo")
        ->get();
    foreach($tests as $test){
        Log::info($test->twentytwo);
    }
}
DvdEnde
  • 112
  • 3
2

You can use model attribute $maps to give your troublesome column a different name. Try

$maps = ['22' => 'twentytwo'];

$hidden = ['22'];

$appends = ['twentytwo'];

Then with your model instance

echo $model->twentytwo;
Jeremy Giberson
  • 1,063
  • 8
  • 15
2
$arr= Tablename::where('id', 1)->lists('22', 'id')->toArray();
$result = $arr[1];

As 1 is the $id var. I tried it in my localhost and it works
2

The question is similar to this:

Hide number field from Eloquent model in Laravel

Presently this is not possible in Laravel as seen in this line of code located in vendor\symfony\var-dumper\Symfony\Component\VarDumper\Cloner\VarCloner.php at line 74.

if ($zval['zval_isref'] = $queue[$i][$k] === $cookie) {
   $zval['zval_hash'] = $v instanceof Stub ? spl_object_hash($v) : null;
}

Here is the hack.

if ($zval['zval_isref'] = (isset($queue[$i][$k])) ? ($queue[$i][$k] === $cookie) : false) {
   $zval['zval_hash'] = $v instanceof Stub ? spl_object_hash($v) : null;
}

Issue has been discussed here:

https://github.com/laravel/framework/issues/8710

Community
  • 1
  • 1
Angelin Calu
  • 1,905
  • 8
  • 24
  • 44
1

Possible duplicate of how can I use exists column with laravel model

The same answer applies here; you can use $model->getAttribute('22') to get the value of a model attribute.

3472948
  • 801
  • 4
  • 15
  • Nope here for the numbers; – LF00 Feb 23 '17 at 11:31
  • it just get empty values, like : [2017-02-23 19:30:28] production.INFO: [] [] [2017-02-23 19:30:28] production.INFO: [] [] [2017-02-23 19:30:28] production.INFO: [] [] [2017-02-23 19:30:28] production.INFO: [] [] [2017-02-23 19:30:28] production.INFO: [] [] [2017-02-23 19:30:28] production.INFO: [] [] – LF00 Feb 23 '17 at 11:32
1

Try to use where: Tablename::where('22','=','value')->first();

iamj
  • 173
  • 1
  • 10
1
$table = Tablename::get();

foreach ($table as $value){
   echo $value->22 // Getting column 22 from table
}
1

I know this is a question from years ago but hope someone find this helpful, if you have a database table column name set to 'Numbers' or Integer, you can fetch its data like this;

in your controller example:

$your-table = users::all(); //or use find etc.. 

//then loop

foreach ($your-table as $key)
{

 return $key['1']; <br><br>//['1'] is my db column name that is set to integer

}
xrak
  • 111
  • 6
0

Try use pluck()

$plucked = $collection->pluck('22');

$plucked->all();
nmtri
  • 444
  • 3
  • 6