How does laravel know which table of my bd will be used for my operation?

1

I have a table in my bd called lost_animals, it was created without using migrations.

I created a class for her:     

namespace App;
use Illuminate\Database\Eloquent\Model;

class AnimalPerdido extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'id_usuario', 'lat', 'lng', 'id_tipo_pet', 'raca', 'id_sexo', 'data', 'possui_identificador', 'id_cores', 'informacoes_adicionais' 
    ];

}

I created a controller to return all the data in this table:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App/AnimalPerdidoController;

class AnimalPerdidoController extends Controller
{
    //Retorna todos os cadastros
    public function index()
    {
        $animaisPerdidos = AnimalPerdido::->get();
        return response()->json($animaisPerdidos);
    }
}

And on my route:

Route::get('animalperdido', 'AnimalPerdidoController@index');

How can I talk about how my lost-animals table will use this model / controller?

    
asked by anonymous 24.11.2018 / 13:47

2 answers

1

Try to put a variable protected $table = 'nome_da_sua_tabela :

namespace App;
use Illuminate\Database\Eloquent\Model;

class AnimalPerdido extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'id_usuario', 'lat', 'lng', 'id_tipo_pet', 'raca', 'id_sexo', 'data', 'possui_identificador', 'id_cores', 'informacoes_adicionais' 
    ];

    protected $table = animais_perdidos

}
    
24.11.2018 / 14:06
3

Based on the official Documentation , but I added some notes:

  

Table names

     

Note that we did not say what the name of the template table Flight was. By convention, the plural of the class in snake_case (instead of uppercase, used a _ as a separator), but you can set another table manually in the model this way via a table property: / p>

<?php

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Flight extends Model
    {
        /**
         * Aqui vai a tabela que é associada com o model.
         *
         * @var string
         */
        protected $table = 'my_flights'; 
    }

In summary, the class declaration adds this property:

protected $table = 'nome_da_tabela';

already with the name of the table in snake_case .


Notes:

  • When the documentation speaks in the plural, it is the "plural ass," it only adds s to the end of the string

    NOTE: you have a pluralization class for English, which is a bad idea, and obviously in Portuguese it will be terrible if it is not adapted.

  • Conversion to snake_case is basically a case-sensitive change, and inserting a _ to separate the words: AbcDef = > abc_def

24.11.2018 / 14:06