Tinkering with your Laravel application is an excellent way to interact with your application, explore your database, and debug your code. Laravel provides a console command, php artisan tinker
, which allows you to play with every part of your application interactively. However, using a PHP file for tinkering can be even more convenient, as it allows you to write, modify, and save your code easily.
In this blog post, we will demonstrate how to tinker with your Laravel application using a PHP file. This method is advantageous because it is easier to work with a PHP file than with a console command.
Getting Started
First, create a PHP file named tinker.php
, If you are using an IDE like PhpStorm, you can create a scratch file so that you don't have to delete it each time you commit your code. This approach ensures a cleaner and more organized workflow.
Next, set up the Laravel application in tinker.php as follows:
<?php
const BASE_PATH = '/Users/ellite/code/jobins';
require_once BASE_PATH.'/vendor/autoload.php';
use Illuminate\Foundation\Console\Kernel;
$app = require BASE_PATH.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
dd(\App\Model\AdminModel::query()->first());
Explanation
Autoload Dependencies:
const BASE_PATH = '/Users/Bedram/code/example';
require_once BASE_PATH.'/vendor/autoload.php';
# This line sets the base path to your Laravel project directory.
Bootstrap the Laravel Application:
use Illuminate\Foundation\Console\Kernel;
$app = require BASE_PATH.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
These lines initialize the Laravel application by requiring the app.php file and bootstrapping the Kernel. That's it, That all you need to setup your tinkering.
Additional Examples
Fetching All Records:
dd(\App\Model\AdminModel::all());
dd(\App\Model\AdminModel::where('status', 'active')->get());
Handling Relationships:
$admin = \App\Model\AdminModel::with('roles')->first();
dd($admin);
Creating a New Record:
$newAdmin = \App\Model\AdminModel::create([
'name' => 'New Admin',
'email' => 'newadmin@example.com',
'password' => bcrypt('password123'),
'status' => 'active',
]);
dd($newAdmin);
Updating a Record:
$admin = \App\Model\AdminModel::first();
$admin->update(['status' => 'inactive']);
dd($admin);
Deleting a Record:
Deleting a Record
$admin = \App\Model\AdminModel::first();
$admin->delete();
dd('Record deleted');
Conclusion
Laravel's Eloquent ORM and the php artisan tinker command make it incredibly easy to interact with your application and database. However, using a PHP file for tinkering can offer even more flexibility and ease of use. By following the steps outlined in this blog post, you can quickly set up a PHP file to explore and debug your Laravel application efficiently.
Happy tinkering!
Top comments (0)