What are the models for Laravel 5.3 for?

3

Excuse my ignorance. I create the models in the following way:

php artisan make:model Marcas -m

And the model I leave it as it is created:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Marcas extends Model
{
    //
}

I modify the migrations like this:

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

class CreateMarcasTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('marcas', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre');
            $table->string('descripcion');
            $table->boolean('status');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('marcas');
    }
}

I manipulate all the functions from the controller that created it like this:

php artisan make:controller MarcasController --resource

And I modify it until it looks like this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use Illuminate\Contracts\Auth\Guard;
use Closure;
use Auth;
use Session;
use Redirect;
use DB;
use PDO;
use Validator;
use Response;
use Datatables;
use Debugbar;
use Alert;
use Illuminate\Support\Facades\Input;
use App\Marcas;

class MarcasController extends Controller
{
    protected $auth;
    public function __construct(Guard $auth){
        $this->auth = $auth;
        $this->middleware('auth');
        $this->middleware('ruta:Marcas');
        $this->middleware('funciones:Marcas,crear',['only'=>['crear']]);
        $this->middleware('funciones:Marcas,editar',['only'=>['editar']]);
        $this->middleware('funciones:Marcas,eliminar',['only'=>['eliminar']]);
        $this->middleware('funciones:Marcas,estado',['only'=>['estado']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(){
        return view('marcas.index');
    }

    public function tabla(Request $request){
        try{
            $sql = Marcas::select(array('id', 'nombre', 'descripcion', 'status'));
            return Datatables::of($sql)
            ->addColumn('action', ' Editar  Eliminar')
            ->addColumn('estado', 'activo')
            ->filter(function ($query) use ($request) {
                if ($request->has('campo')) {
                    $query->where(DB::raw("CONCAT( nombre, ' ', descripcion )"), 'ilike', "%{$request->get('campo')}%");
                }
                if ($request->has('status')) {
                    $query->where('status', '=', "{$request->get('status')}");
                }
            })
            ->make();
        }catch(\Illuminate\Database\QueryException $e){
            $array = array(
                'mensaje' => $e->getMessage(),
                'codigo' => $e->getCode(),
                'sql' => $e->getSql(),
                'bindings' => $e->getBindings(),
            );
            return Response::json(array('ErrorSql' => $array));
        }
    }

    public function crear(Request $req) {
        $rules = array(
            'nombre' =>  'required|unique:cargos|min:5|max:30',
        );
        $validator = Validator::make ( Input::all (), $rules );
        if ($validator->fails()){
            return Response::json(array('errors' => $validator->getMessageBag()->toArray()));
        }else{
            try{
                $cargos = new Marcas();
                $cargos->nombre = $req->nombre;
                $cargos->status = 't';
                $cargos->save();
                return Response::json(array('correcto' => $cargos->toArray()));
            }catch(\Illuminate\Database\QueryException $e){
                $array = array(
                    'mensaje' => $e->getMessage(),
                    'codigo' => $e->getCode(),
                    'sql' => $e->getSql(),
                    'bindings' => $e->getBindings(),
                );
                return Response::json(array('ErrorSql' => $array));
            }
        }
    }

    public function editar(Request $req){
        $rules = array(
            'nombre' =>  'required|min:5|max:30',
        );
        $validator = Validator::make ( Input::all (), $rules );
        if ($validator->fails()){
            return Response::json(array('errors' => $validator->getMessageBag()->toArray()));
        }else{
            try{
                if(Marcas::where('nombre', 'ilike', $req->nombre)->where('id', '', $req->id)->exists()){
                    return Response::json(array('encontrado' => 'nombre ya ha sido registrado'));
                }else{
                    $cargos = Marcas::find ($req->id);
                    $cargos->nombre = $req->nombre;
                    $cargos->save();
                    return Response::json(array('correcto' => $cargos->toArray()));
                }
            }catch(\Illuminate\Database\QueryException $e){
                $array = array(
                    'mensaje' => $e->getMessage(),
                    'sql' => $e->getSql(),
                    'bindings' => $e->getBindings(),
                );
                return Response::json(array('ErrorSql' => $array));
            }
        }
    }

    public function eliminar(Request $req){
        try{
            Marcas::find($req->id)->delete();
                $array = array(
                    'mensaje' => 'todo bn',
                );
                return Response::json(array('correcto' => $array));
        }catch(\Illuminate\Database\QueryException $e){
            if($e->getCode()==23503){
                $array = array(
                    'mensaje' => $e->getMessage(),
                    'sql' => $e->getSql(),
                    'bindings' => $e->getBindings(),
                );
                return Response::json(array('ClaveForanea' => $array));
            }else{
                $array = array(
                    'mensaje' => $e->getMessage(),
                    'sql' => $e->getSql(),
                    'bindings' => $e->getBindings(),
                );
                return Response::json(array('ErrorSql' => $array));
            }
        }
    }

As I read in this article: link It says that there we define which fields we can modify, eliminate, etc. But I do not play them in the Laravel models and everything is fine.

What really do the models in laravel.

    
asked by Pablo Contreras 14.01.2017 в 22:32
source

2 answers

6

The answer to the question is found in the file: Illuminate\Database\Eloquent\Model , analyzing each property and each method can give you the idea of what a model is for and when to have one or not for a table.

In general with a model in Laravel you can:

  • Set the interaction parameters with the corresponding table in the database (name, keys, protected fields, etc.)
  • Establish relations with other tables, in order to preload said information as property of each model (perhaps the most important function of all, and the one that can save us the longest)
  • Perform certain simple and typical tasks such as saving, obtaining all records, deleting, etc.
  • Take advantage of "Eager Loading", quite useful in many situations
  • Shoot events
  • Handling paging

Among so many other functions that you can see in the file mentioned.

By the way, complex queries that you need to ask the database should not be made either from a controller (not your responsibility) or in the model, for this you can preferably use a repository.

    
answered by 19.01.2017 / 19:45
source
1

Well, I use it to manage my database from that point. I'll give you an example with a Model and I'll explain ...

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Cviebrock\EloquentSluggable\SluggableScopeHelpers;
use Carbon\Carbon;
class Articulo extends Model{
use Sluggable, SluggableScopeHelpers;

/**
 * Return the sluggable configuration array for this model.
 *
 * @return array
 */
public function sluggable()
{
    return [
        'slug' => [
            'source' => 'titulo'
        ]
    ];
}
 protected $table = 'articulos';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['titulo', 'contenido','slug','path','etiqueta','user_id','categoria_id'];

public function setPathAttribute($path){
    if(! empty($path)){
        $name = Carbon::now()->second.$path->getClientOriginalName();
        $this->attributes['path'] = $name;
        \Storage::disk('local')->put($name, \File::get($path));
    }
}



public function categoria(){
    return $this->belongsTo('Blog\Categoria');
}

public function user(){
    return $this->belongsTo('Blog\User');
}

public function scopeTitulo($query, $titulo){//Funcion para hacer una busqueda 
    if(trim($titulo) != ''){ //Funcion trim para eliminar los espacios
        $query->where(\DB::raw("titulo"),"LIKE","%$titulo%");
    }


}
}

In that model I have the sluggable This function is part of an eloquent that helps me so that when saving some post let's say and the title is something like "This is my first post" the sluggable saves it in my database like "This-is-my-first-post" and thus works in a cleaner way and better view the links

The function setPathAttribute use it so that when saving the images are not saved with a repeated name

The functions categoria and user I'm relating in some way to this model or table Articulo and then the time in my controller or in my HTML code to use some of my relationships between tables thanks to this

and finally the scopeTitulo this is a simple search engine ...

All this is inside my Model and it helps me to solve many things in my Database.

    
answered by 15.01.2017 в 00:54