Skip to content

Instantly share code, notes, and snippets.

@superguigui
Last active March 16, 2022 11:15
Show Gist options
  • Save superguigui/e7f7a0730b71254f45ef to your computer and use it in GitHub Desktop.
Save superguigui/e7f7a0730b71254f45ef to your computer and use it in GitHub Desktop.
Laravel memo

Laravel help

Basics

Create controller

php artisan make:controller NameOfTheController --plain

Connect to Homestead VM

ssh vagrant@127.0.0.1 -p 2222

Laravel Eloquent help

Make model class

php artisan make:model ModelName

Don't forget to specify which table this model refers to

class Product extends Model
{
   /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'tablename';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title', 'description'];
}

Launch tinker

php artisan tinker

From this point on the commands are tinker commands


Create virtual entry

$item = new namespace\ModelName;
$item->fieldname = 'value';

View entry

$item->toArray();

or just

$item;

Save entry in database

It should return true.

$item->save()

Show all entries in database

namespace\ModelName::all()->toArray();

Find existing entry in table for a given id

$item = namespace\ModelName::find(1234);

Filter entries

$item = namespace\ModelName::where('fieldname', 'value');

Filter entries

$item = namespace\ModelName::where('fieldname', 'value')->get();

Create entry directly into database

Don't forget you can only assign fields specified in ModelClass->$fillable.

$item = namespace\ModelName::create(['fieldname1' => 'value1', 'fieldname2' => 'value2']);

Update entry and save directly to database

Don't forget you can only assign fields specified in ModelClass->$fillable.

$item->update(['fieldname' => 'value']);

Laravel Migration help

Migrate command

This action will populate DB defined in .env with the migrations in database/migrations (ie execute all the up functions).

php artisan migrate

Reset command

This action will perform all the down functions from the migrations in database/migrations.

php artisan migrate:reset

Reset rollback

This action will go back in time to previous migration.

php artisan migrate:rollback

Add a new table to database

php artisan make:migration add_tablename_table --create="tablename"

Add column to existing table

php artisan make:migration add_columnname_to_tablename_table --table="tablename"

In this case make sure the down function of the migration remove the column from the table.

public function down()
{
  Schema::table('tablename', function (Blueprint $table) {
    $table->dropColumn('columnname');
  });
}  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment