Artisan Tinker With Laravel

Nov 21, 2016 database php laravel artisan tinker
WhatsApp
A neat tool to literally tinker/interact with your website. It's new to me at the moment but I currently use it to test relationships between models and fiddle with the database.

To use Tinker, bring up the command line interface and we'll move to the directory with artisan. All you have to type is

php artisan tinker


It reminds me of Swift's Playground feature but you don't see code run live. You can add, modify, delete to the database and check data held inside. Let's take a look at that.

First imagine we have a super hero model. Let's add a new super hero object.

$superHero = new App\Superhero();


Usually a super hero will have a name, age, job etc. So let's fill those in too

$superHero->name = 'Iron Man';
$superHero->age = '40';
$superHero->job = 'Avenger';


Pretty simple! Once we're done, don't forget to save it to apply it to the database.

$superHero->save();


Easy. Reload your database and you should see your data.

Now how do we deal with relationships. A superhero has to have super power, not just one, but many super powers. Imagine we have a one to many relationship between our superhero and abilities. Assuming we have set up the relationship between a superpower and a superhero we can explore the relationship like so:

$superHero->getSuperPowers;


Yes leave out the brackets -> (). Which would be the same line of code you would use in your controller. An array should print and a list of all your data regarding the super power should print out.

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb