Home > Enterprise >  Specific question Laravel Database Homepage
Specific question Laravel Database Homepage

Time:07-15

I started using Laravel few days before.

I'm actually struggling with a problem, I created a homepage and I want to replace some text of the page with content from my database. So how do I create a model/controller, and after that I will make an admin panel, so I can edit them.

The only tutorials/docs I see are for making a form/post to create users

Example

In basic php it's easy you just do a pdo connection and then a fetch and you use your date as you want. How do you do it in laravel ?

CodePudding user response:

To fetch data from the DB in Laravel can be done in 1 of two ways, 1. using a Model (the best way) or using a Query Builder, which is much more familiar to those migrating from pure PHP.

  1. Using a Model

Create a model using php artisan make:Model (change Model with a name of your choosing) then open the model once created (found in app/Http/Models) and add the following under use HasFactory;:

protected $table = 'your_table_name';
protected $primaryKey = 'id'; // This is the column you usually set to PRIMARY
public $timestamps = true;
protected $fillable = [
    'table_column',
    'table_column',
];

To use the Model, import it into your Controller file like so use App\Models\Model; and then use it as so:

$flights = Flight::where('destination', 'Paris')->get();

Learn more about Models in Laravel here.

  1. Using a Query Builder, not best practice

Import the DB facade in the controller like so use DB; then call upon it like so:

$db = DB::table('users')->where('name', 'John')->first();

Learn more about the Query Builder here.

I hope this helps, if not let me know how I can assist further.

  • Related