0

I need to generate a number from database and show it on input at view.

I use function on MySQL to achieve that so I use raw expression.

    $nomor = DB::table('customers')- 
    >selectRaw('concat(year(now()),lpad(month(now()),2,0),lpad(id, 3, 0))  
    as nomor')
    ->where('id', '=', $customers->id)->get();

When I pass the variable into view,

<input type="text" class="form-control  @error('nomor') is-invalid @enderror" id="nomor" placeholder="" name="nomor" value="{{ $nomor }}">

current result:
current result

"[{"nomor":"201909001"}]"

my expected result is:

201909001 withoutquote

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

When you call get() function, the function returns an array with all results of your query.

As example, if your select returns 3 lines, the $nomor returns a collection (like an array with steroids) with 3 positions, one per line returned by the query and, in each position, the get() function returns an object with the properties as your select, so, in this case, the correct way to access the nomor column is:

<input type="text" class="form-control  @error('nomor') is-invalid @enderror" id="nomor" placeholder="" name="nomor" value="{{ $nomor[0]->nomor }}">

Note, instead calling only $nomor object, we access the first line of the result $nomor[0] and get the property that corresponds to the column name of the query $nomor[0]->nomor

William Prigol Lopes
  • 1,803
  • 14
  • 31
0

When you use ->get(), you get a Collection, which is essentially an array with additional functionality. When you use {{ $nomor }}, you're outputting the whole contents of the Collection. To fix this, use ->first():

$nomor = DB::table('customers')
->selectRaw('concat(year(now()),lpad(month(now()),2,0),lpad(id, 3, 0)) as nomor')
->where('id', '=', $customers->id)
->first();

Then in your view, access it as an object (since DB::table()->first() will return a stdClass):

<input type="text" ... value="{{ $nomor->nomor }}"/>
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102