View does not show string value in the primary key field

Asked

Viewed 69 times

1

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

As it is below, it shows as follows: 0 (but its true value is 00LDA922)

immovable 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($immovable)

    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

inserir a descrição da imagem aqui

  • Send dd of the immovable variable of the list method

  • Amazing that for it picks up correct but does not show properly.

  • The final result of the screen you can send?

  • How do I do that? Send the msmo code or a screen prt?? Excuse my ignorance, I’m new to the community and I don’t know how to do it

  • The HTML Code with the for, and the screen print even of your problem, and when your questions get quiet, over time you will understand how it is faster to solve when you have the overview of the problem

  • Beauty. As you see in the values q contains letters it shows 0, qndo step only numbers shows correctly

  • Diumanuel put your model?

  • I just can’t identify what I’m missing

Show 3 more comments

1 answer

1


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

Why does that happen?

Your model is missing set up to primary key to accept the data in text format and not make the conversion to number, there are two things to be done in the model:

Setar the auto increment as false:

public $incrementing = false;

this ensures that the data is not incremented and that it can be done its 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 summary its model it must look 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
}

i.e., the model needs to be configured to not have the default behavior (convention) and follow the behavior you did in your table.

References

  • 1

    Really, I tested this definition and solved my problem! Thank you for your explanation dear Virgilio. It made perfect sense now!

  • 1

    He even solved another little problem that said he was trying to access an unknown or null object when there was an owner associated with a property. Thanks Virgilio and Mauricio for their help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.