View does not show string value in primary key field

1

Good people. I'm trying to list the attributes of my table in Laravel 5.6 through a view list, but in the registration (PK) field the contained values are not displayed completely. This field is a code and is of type string but in the view it shows only positive values.

The way it looks down, it looks like this: 0 (but its true value is 00LDA922)

real estate table

   public function up() {
    Schema::create('imoveis', function (Blueprint $table) {
        $table->string('matricula')->primary();
        $table->string('tipo_imovel');
        $table->float('area')->unsigned();
        $table->float('limites')->unsigned();
        $table->float('longitude');
        $table->float('latitude');
        $table->float('valor_patrimonial',9,2)->nullable();
        $table->timestamps();
    });
}

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Imovel extends Model
{
    //
    protected $table = 'imoveis';

    protected $primaryKey = 'matricula';

    protected $fillable = [
        'matricula',
        'tipo_imovel',
        'area',
        'limites',
        'longitude',
        'latitude',
        'valor_patrimonial',
        'administracao_distrital_id',
    ];

    public function users()
    {
        //
        return $this->belongsToMany(User::class);
    }

    public function proprietarioSingular()
    {
        //
        return $this->belongsToMany(ProprietarioSingular::class);
    }

    public function administracaoDistrital()
    {
        //
        return $this->belongsTo(AdministracaoDistrital::class);
    }
}

Controller

    public function listar()
{
    $total_imoveis = $this->imovel->count();

    $total_proprietarios_s = ProprietarioSingular::count();

    $imoveis = $this->imovel->latest()->paginate(6);

    return view('painel.imovel.listar', compact('imoveis', 'total_imoveis', 'total_proprietarios_s'));
}

dd ($ imoveis)

    LengthAwarePaginator {#338 ▼
       #total: 9
       #lastPage: 2
       #items: Collection {#344 ▼
          #items: array:6 [▼
            0 => Imovel {#345 ▼
               #table: "imoveis"
               #primaryKey: "matricula"
               #fillable: array:15 [▶]
               #connection: "mysql"
               #keyType: "int"
               +incrementing: true
               #with: []
               #withCount: []
               #perPage: 15
               +exists: true
               +wasRecentlyCreated: false
               #attributes: array:17 [▼
                  "matricula" => "LD047214033"
                  "tipo_imovel" => "Residencial"
                  "area" => 44.0
                  "limites" => 45.0
                  "longitude" => 65.0
                  "latitude" => 77.0
                  "valor_patrimonial" => 45000.0
                  "created_at" => "2018-03-29 18:00:49"
                  "updated_at" => "2018-03-29 18:00:49"
               ]
               #original: array:17 [▶]
               #changes: []
               #casts: []
               #dates: []
               #dateFormat: null
               #appends: []
               #dispatchesEvents: []
               #observables: []
               #relations: []
               #touches: []
               +timestamps: true
               #hidden: []
               #visible: []
               #guarded: array:1 [▶]
            }
            1 => Imovel {#346 ▶}
            2 => Imovel {#347 ▶}
            3 => Imovel {#348 ▶}
            4 => Imovel {#349 ▶}
            5 => Imovel {#350 ▶}
          ]
       }
       #perPage: 6
       #currentPage: 1
       #path: "http://127.0.0.1:8000/painel/imovel/listar"
       #query: []
       #fragment: null
       #pageName: "page"
    }

view

@extends('adminlte::page')

    @section('title', 'Listar imóvel')

    @section('content_header')
        <h1>
            Listar
            <small>Imóveis</small>
        </h1>

        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Dashboard</a></li>
            <li class="active">Imóvel</li>
        </ol>
    @stop

    @section('content')
        <div class="box">
            <div class="box-header with-border">
                <a href="{{route('painel.imovel.novo')}}" class="btn btn-default pull-right">
                    <i class="fa fa-plus" aria-hidden="true"></i> Novo imóvel
                </a>
            </div>
            <div class="box-body">

            @if($message = Session::get('success'))
                <!-- /.alert-dismissible-operação -->
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                        <h4><i class="icon fa fa-check"></i> Alerta!</h4>
                        <p>{{ $message }}</p>
                    </div>
                @endif

                <div class="small-box bg-aqua-active">
                    <div class="inner">
                        <h3>{{ $total_imoveis }}</h3>

                        <p>Imóveis Registratados</p>
                    </div>
                    <div class="icon">
                        <i class="ion ion-home"></i>
                    </div>
                    <a href="#" class="small-box-footer">
                        Listar todos <i class="fa fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="box">
            <div class="box-header with-border">
                <i class="fa fa-home"></i>

                <h3 class="box-title">Lista de imóveis</h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
                <!-- /.listar imovel -->
            @forelse($imoveis as $imovel)
                <!-- /.box-header -->
                    <div class="col-md-4">
                        <div class="box box-default box-solid">
                            <div class="box-header with-border">
                                <h3 class="box-title">Imóvel</h3>

                                <!-- /.controlo-de-permissão -->

                                <div class="pull-right box-tools">
                                    <a href="{{ url("painel/imovel/editar/$imovel->matricula") }}"
                                       class="btn btn-default btn-sm">
                                        <i class="fa fa-edit" aria-hidden="true"></i> Editar
                                    </a>
                                    <a href="{{ url("painel/imovel/excluir/$imovel->matricula") }}"
                                       class="btn btn-default btn-sm">
                                        <i class="fa fa-trash" aria-hidden="true"></i> Eliminar
                                    </a>
                                </div>

                            </div>
                            <!-- /.box-header -->
                            <div class="box-body">
                                <dl class="dl-horizontal">
                                    <dt>Matrícula</dt>
                                    <!-- var_dump($imovel->matricula) -->
                                    <dd>{{ $imovel->matricula }}</dd>
                                    <dt>Tipo</dt>
                                    <dd>{{ $imovel->tipo_imovel }}</dd>
                                    <dt>Área</dt>
                                    <dd>{{ $imovel->area }}</dd>
                                    <dt>Localização</dt>
                                    <dd>{{ $imovel->provincia }}</dd>
                                    <dd>{{ $imovel->municipio }}</dd>
                                    <dt>Valor patrimonial</dt>
                                    <dd>{{ number_format($imovel->valor_patrimonial,2,',','.') }}</dd>
                                </dl>
                            </div>
                            <!-- /.box-body -->
                            <div class="box-footer">
                                <a href="{{ url("painel/imovel/$imovel->matricula/proprietario-singular") }}"
                                   class="pull-left">
                                    <i class="fa fa-user" aria-hidden="true"></i> Proprietário
                                </a>
                                <a href="#" class="uppercase pull-right">Mais detalhes</a>
                            </div>
                        </div>
                    </div>
                @empty
                    <p class="alert-warning">Nenhum imóvel cadastrado!</p>
                @endforelse
            </div>
            <!-- /.box-body -->
        </div>
    @stop

    
asked by anonymous 28.03.2018 / 19:38

1 answer

1

Next, the works like this: primary key in the default convention is an auto increment number so at the time of showing the result the field is submitted to a integer conversion, but since the field is a text it will not work and so the return is a 0 .

  

Why does this happen?

Your model is missing setting the primary key to accept the data in text format and do not convert to number, there are two things to do in model :

Set auto increment as false :

public $incrementing = false;

This ensures that the data is not incremented and can be done in its own way with other types ( string , int , etc) and also a cast for string which is the factor of your model :

protected $casts = ['matricula' => 'string'];

In general, your model should look something like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Resume extends Model
{    
    protected $table = 'resume';
    protected $primaryKey = 'matricula';
    protected $fillable = ['matricula', 'name' ];

    public $incrementing = false; // auto incremento desabilitado
    protected $casts = ['matricula' => 'string']; // cast
}

That is, model needs to be set to not have the default behavior (convention) and to follow the behavior it did in your table.

30.03.2018 / 15:19