Learning Objectives: How to fetch data from the database using the Model.
What is the Laravel Model?
Laravel Model is the class to interact with your MySQL database table. You just need to provide a few details about the model, and then you can easily use this model to fetch data from the table or insert data into the table.
How to Create a Laravel Model?
To create Laravel model, execute the following command on the terminal.
php artisan make:model Flight
Now you need to add the following code to your model file.
use HasFactory; protected $table="products"; protected $primaryKey="id";
How to display data from a database table using the Laravel Model?
Now create a Route to display data from the tables
Route::get('/products', function () { $p = products::all(); echo "<pre>"; print_r($p->toArray()); });
Now open the following URL to view this data:
http://127.0.0.1:8000/products
Now Let’s Do the same process via URL > Route > Controller > View
use App\Models\Flight;
// php artisan make:migration create_flights_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFlightsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('flights');
}
}
// Code for web.php Routing file
use App\Models\Flight;
Route::get('/flight', [FlightController::class, 'index']);
// code for controller
// php artisan make:controller FlightController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Flight;
class FlightController extends Controller
{
//
public function index()
{
$p = Flight::all();
return view('flight',["mydata" => $p]);
}
}
// php artisan make:model Flight
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
use HasFactory;
protected $table="flights";
protected $primaryKey="id";
}
If you would like to generate a database migration when you generate the model, you may use the --migration
or -m
option:
php artisan make:model Flight --migration
php artisan make:model Flight -mcr