© Sanjib Sinha 2019
S. SinhaBeginning Laravel https://doi.org/10.1007/978-1-4842-4991-8_7

7. Using Tinker

Sanjib Sinha1 
(1)
Howrah, West Bengal, India
 

Since Laravel depends heavily on command-line interfaces, you will need to know a number of helpful commands to assist you while you build your applications.

Let’s first try to understand what a command-line interface is. Basically, it is a type of interactive shell that takes in single-user inputs, evaluates them, and returns the result to the user, in the form of a read-eval-print-loop (REPL) mechanism. Therefore, you can say that Tinker is a kind of REPL.

Actually, PHP has its own interactive shell, called PsySH; Justin Hileman created it, and Tinker is powered by PsySH.

Tinker helps you when you want to do some quick CRUD operations in the database records of your application through the terminal. Before Laravel 5.4, it was part of the Laravel package; now in Laravel 5.8 it extracts itself into a separate folder, although you can use it easily in your terminal.

Handling a Database Using Tinker

Writing PHP code through a command line is not easy. It is especially difficult when you want to add dummy data in your database tables and you don’t have immediate access to your database.

In such cases, Tinker is your friend.

You can even update or delete table records in the database through the Tinker.

As mentioned, Tinker is a REPL powered by the PsySH ( https://github.com/bobthecow/psysh ) package. In Laravel, the use of Tinker is not limited to only database handling. Tinker allows you to interact with your entire Laravel application on the command line, including the Eloquent ORM, jobs, events, and more. To enter the Tinker environment, run the artisan tinker command from the Laravel codebase, as follows:
//code 7.19
$ php artisan tinker

Remember, you have to be inside the Laravel application environment for this to work. And you’ll want to be working on a database that has a connection to your application because you’ll want to use your Eloquent models .

Once you have entered the Tinker environment, you can use any model you have. Suppose you have a model called Listtodo ; you can create a new list instance like this:
//code 7.20
$list = new Listtodo;
$list->name = 'First Job';
$list->description = 'Go to market';
$list->save();

Once you issue the save() command , the records are saved in your database tables.

You could have created the same thing with a single command, as shown here:
//code 7.21
$list = Listtodo::create(
array('name' => 'First Job',
'description' => 'Go to Market')
);
You can get the output of all lists with this command:
//code 7.22
echo Listtodo::all()->count();
You can get the first record, as shown here:
//code 7.23
$lists = Listtodo::select('name', 'description')->first();
You can get all lists ordered by name, as shown here:
//7.24
$lists = Listtodo::orderBy('name')->get();
Here is the command to get the list in descending order:
//code 7.25
$lists = Listtodo::orderBy('name', 'DESC')->get();
// order results by multiple columns
lists = Listtodo::orderBy('created_at', 'DESC')->orderBy('name', 'ASC')->get();
You have many choices such as using conditionals, where you can check whether your listed job is completed.
//code 7.26
$lists = Listtodo::where('isComplete', '=', 1)->get();
Suppose you want to get five records in descending order, as shown here:
//code 7.27
$lists = Listtodo::take(5)->orderBy('created_at', 'desc')->get();
You may want to skip five records, as shown here:
//code 7.28
lists = Listtodo::take(5)->skip(5)->orderBy('created_at', 'desc')->get();
For a random output of records, these commands are useful:
//code 7.29
$list = Listtodo::all()->random(1);
$list = Listtodo::orderBy(DB::raw('RAND()'))->first();
For a quick CRUD operation, Tinker is extremely useful. Suppose you want to update a part of your existing records, as shown here:
//code 7.30
$list = Listtodo::find(1);
$list->name = 'Going to market and buying fish';
$list->save();
The effect may be achieved with this command, as shown here:
//code 7.31
$list = Listtodo::updateOrCreate(
array('name' => 'Going to market and buying fish'),
);
Deleting a record is easy. You can use either the delete() or destroy() method . The advantage of the destroy() method is that it takes a record ID as the parameter, as shown here:
//code 7.32
$list = Listtodo::find(2);
$list->delete();
Listtodo::destroy(2);
Using a DB facade in Tinker is often useful. In that case, you don’t use Eloquent ORM; instead, you use a database facade directly. However, you get the same effect.
//code 7.33
$lists = DB::table('liststodos')->get();
foreach ($lists as $list) {
echo $list->name;
}
In this case, you need to identify the lists by ID. Here you want to find the ID number 6:
//code 7.34
$list = DB::table('liststodos')->find(6);
Here you get all the names in one go:
//code 7.35
$lists = DB::table('liststodos')->select('name')->get();
Traditional querying is also possible, as shown here:
//code 7.36
$lists = DB::select('SELECT * from todolists');
Inserting data into the database tables is also easy, as shown here:
//code 7.37
DB::insert('insert into todolists (name, description) values (?, ?)',
array('Second job', 'Finishing the last chapter');
With a single command, you can delete a record, as shown here:
//code 7.38
DB::delete('delete from todolists where completed = 1');
Want to drop a table entirely? Well, you don’t have to open your MySQL wizards; you can achieve the result in your terminal, as shown here:
//code 7.39
$lists = DB::statement('drop table todolists');

Tinker is helpful when doing any database operation, not only the small and easy ones but the complex ones too.

SQLite Is a Breeze!

If you want to make a new company/project/task management application, which is also a CRUD-based application, you can make this application entirely based on a SQLite database. However, for a big and complex application, people opt for MySQL or PgSQL because each of these can handle more visitors.

SQLite may not be big enough and basically file-based and light in nature, but it can easily tackle small to medium applications with 100,000 visitors. So, you can feel free to use it for any small or medium-sized CRUD applications. Especially for Laravel, SQLite is a breeze to use because you can use Tinker to manipulate the database.

To use SQLite in Laravel, you need to change the default database setup. Two lines need to be changed. Here’s the first one:
//Code/test/blog/config/databse.php
'default' => env('DB_CONNECTION', 'sqlite'),
In the second line, you need to mention the SQLite database file path, as shown here:
//Code/test/blog/config/databse.php
'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            //'database' => storage_path('database.sqlite'),
            'database' => env('DB_DATABASE', database_path('/../database/database.sqlite')),
            'prefix' => ",
        ],

Suppose your local Laravel application is in the Code/test/blog directory. In that case, you will keep your SQLite file in the Code/test/blog/database/ folder. Many people go for the storage folder. Either one of them will work.

Second, you need to change the .env file. In the original file that comes with Laravel, the default database is mentioned like this:
//Code/test/blog/.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testdb
DB_USERNAME=root
DB_PASSWORD=pass
You must change it to this:
//Code/test/blog/.env
DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306

From now on, any database operation you do on your application will automatically be registered on the SQLite database file that you create in the Code/test/blog/database folder. Normally people don’t create a new SQLite file in the Code/test/blog/database folder. They choose the Code/test/blog/storage/databse.sqlite file that comes with Laravel by default. In that case, you need to change the database path Code/test/blog/config/databse.php.

If you want to take a little break from the usual path and create a database.sqlite file in the Code/test/blog/database folder, you must go to the desired folder first, as shown here:
cd Code/test/blog/database
Next you have to use the touch command to create the file.
touch database.sqlite

Now you’re ready to make any type of CRUD application using SQLite.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.255.234