If you're working with Laravel you have to think about MVC (even though Laravel has more layers).
What we should do:
1 ° Create and define the model and controller
php artisan make:model Tabla -c
This generates a model in App/
and a controller in App/Http/Controllers
.
In the model is where we will configure the data of the table something like
File App\Tabla.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tabla extends Model
{
protected $table = 'Tabla'; // Nombre de la tabla
protected $primaryKey = 'id'; // Clave primaria
// Columnas de la tabla
protected $fillable = ['nombre','apellidos'];
}
In the controller is where we execute the logic, something like:
File App\Http\Controllers\TablaController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
// Incluimos el modelo
use App\Tabla;
class TablaController extends Controller
{
// Creamos un método para atender la peticion llamado show
public function show($id)
{
// Buscamos el id en la tabla
$dato = Tabla::find($id);
// retornamos la vista con los datos
return view('tabla.show')->with('dato', $dato);
// with() nos permite pasar variables a la vista
// el primer parámetros es el nombre con el que estará disponible en la vista
// el segundo son los datos.
}
}
2 ° Create and define the route and view.
For the view we go to the path resources/views/
and create a new folder to save the views that our controller will use with the name tabla
(for the example) and inside this we create a file with the name of the view with extension .blade.php
(show.blade.php for the example).
Once the above is done we open the created file resources/views/tabla/show.blade.php
and we can define the view, we will also have the variable $dato
that we return next to the view in the controller.
For example
Id: {{ $dato->id }} <br>
Nombre: {{ $dato->nombre }} <br>
Apellidos: {{ $dato->apellidos }} <br>
Now we just need to define the route, for that we go to the file routes/web.php
and create a route that points to our controller, for example
Route::get('/mi/ruta/{id}', 'TablaController@show');
// {id} Será la variable que recogeremos en el controlador
// en $id: public function show($id)
To access this example we should use the url dominio.es/mi/ruta/1