Skip to content

Instantly share code, notes, and snippets.

@prasanth22
Last active December 27, 2020 16:58
Show Gist options
  • Save prasanth22/91586345902468a8ed8fe1371cadb371 to your computer and use it in GitHub Desktop.
Save prasanth22/91586345902468a8ed8fe1371cadb371 to your computer and use it in GitHub Desktop.

My Laravel Documentation

  • Create Thread model, migration and Resourceful controller

    php artisan make:model Thread -mr

  • Create Reply model, migration and simple controller

    php artisan make:model Reply -mc

  • Add the following code in reply migration code

    public function up()
      {
          Schema::create('replies', function (Blueprint $table) {
              $table->increments('id');
              $table->interger('thread_id');
              $table->interger('user_id');
              $table->text('body');
              $table->timestamps();
          });
      }
    

Factories:

  • To create Thread Factory
    php artisan make:factory ThreadFactory --model=Thread
    
    databases/factories/ThreadFactory.php
    <?php
    
    use Faker\Generator as Faker;
    
    $factory->define(App\Thread::class, function (Faker $faker) {
        return [
            'user_id' => function(){
                return factory('App\User')->create()->id;
            },
            'title' => $faker->sentence,
            'body' => $faker->paragraph,
        ];
    });
    
    Use the following command to fill 50 new records in Thread Table and user
    php artisan tinker
    >>> factory('App\Thread', 50)->create();
    
    Create a Reply Factory
    $factory->define(App\Reply::class, function (Faker $faker) {
      return [
          'thread_id' => function(){
              return factory('App\Thread')->create()->id;
          },
          'user_id' => function(){
              return factory('App\User')->create()->id;
          },
          'body' => $faker->paragraph,
      ];
    });
    
Run the following cmd to get replies to threads 

$threads->each(function($thread){factory('App\Reply',10)->create(['thread_id'=>$thread->id]);});


## Relationships
<b>one to one :</b></br>
user can have profile or address
user has one profile:</br>
add this in user model as:</br>
```php
public function profile()
{
 return $this->hasOne(Profile::class);
}

now create this model with migration using:
`php artisan make:model Profile -m`

add fields to the profile model:

public function up()
  {
      Schema::create('profiles', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->unsignedInterger('user_id');
          $table->string('website_url');
          $table->string('github_url');
          $table->string('twitter_url');
          $table->timestamps();
      });
  }

php artisan migrate

Add data in the tables
use tinker to see in action as:
php artisan tinker
get user data from table as:
$user = App\User::first();
Because we have one to one relationship with user and profile we can use the following command to get user profie:
$user->profile
and $user->profile->github_url

to see the sql queries which are running behing the seens use:(in tinker)
DB::listen(function ($sql) { var_dump($sql->sql, $sql->bindings);});

We can also use
DB::enableQueryLog();
DB::getQueryLog();

one to many :
user can have many posts
add this line in user model

public function posts()
{
  return $this->hasMany(Post::class);
}

create model along migration:
php artisan make:model Post -m

add the following code in migration

public function up()
  {
      Schema::create('posts', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->unsignedInteger('user_id');
          $table->string('title');
          $table->text('body');
          $table->timestamps();
      });
  }

to test we can hard code in table or we can use factories as:
php artisan tinker
factory(App\User::class)->create();

for the user we already have user factory
, for post we can create using php artisan make:factory PostFactory -m Post

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'user_id' => function(){
		return factory(App\User::class)->create()->id;
		},
        'title' => $faker->sentence,
        'body' => $faker->sentence,
    ];
});

php artisan tinker

factory(App\Post::class)->create();

it will create the post and respective user in user table as well

we can also pass the user id manually by overiding
factory(App\Post::class)->create(['user_id' => 2]);

php artisan tinker
$user = App\User::find(2);
$user->posts

for one to one and one to many we say user can have one profile and user has many post to reverse it we say profile blongs to user and post blongs to user we represent them on profile model as

public function user()
{
  return $this->belongsTo(User::class);
}

In One to One:

You have to use HasOne on the first model and BelongsTo on the second model

to add record on the first model (HasOne) use the save function

example: $post->comments()->save($comment);

to add record on the second model (BelongsTo) use the associate function

example: $user->account()->associate($account); $user->save();

in One to Many:

You have to use HasMany on the first model and BelongsTo on the second model

to add record on the first table (HasMany) use the save or saveMany functions

example: $post->comments()->saveMany($comments);

to add record on the second model (BelongsTo) use the associate function

example: $user->account()->associate($account); $user->save();

in Many to Many:

You have to use BelongsToMany on the first model and BelongsToMany on the second model

to add records on the pivot table use attach or sync functions

both functions accepts single ID or array of ID’s

the difference is attach checks if the record already exist on the pivot table while sync don’t

example: $user->roles()->attach($roleId);

in Polymorphic One to Many:

You have to use MorphMany on the main model and MorphTo on all the (***able) models

to add records on all the other models use the save

example: $course->tags()->save($tag);

the pivot table should have the following columns:

. main model ID

. (***able) ID

. (***able) Type

in Polymorphic Many to Many:

You have to use MorphByMany on the main model and MorphToMany on all the (***able) models

to add records on all the other models use the save or saveMany

example: $course->tags()->save($tag);

example: $course->tags()->saveMany([$tag_1, $tag_2, $tag_3]);

the pivot table should have the following columns:

. main model ID

. (***able) ID

. (***able) Type

in Has Many Through (shortcut):

You have to use HasManyThrough on the first table and have the normal relations on the other 2 tables

this doesn’t work for ManyToMany relationships (where there’s a pivot table)

however there’s a nice and easy solution just for that

Building Database Seeds

  • create our issues model and migration from the artisan console command
  php artisan make:model Issues -m
  • open the app/User.php model file and define the issues relationship:
  public function issues()
  {
    return $this->hasMany('issues');
  }
  • Open database/migrations/datetime_create_issues_table.php and adjust the up method to the following:
    public function up()
    {
      Schema::create('issues', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('user_id');
          $table->string('subject');
          $table->text('description');
          $table->timestamps();
      });
    }
    
  • Run the migration now:
    php artisan migrate
    
  • Let’s start by creating a seed for users.
    php artisan make:seeder UserTableSeeder
    
  • create one for issues as well:
    php artisan make:seeder IssueTableSeeder
    
  • Now open the database/seeds/DatabaseSeeder.php file and adjust the run method to the following:
    public function run()
    {
      Model::unguard();
    
      $this->call(UserTableSeeder::class);
      $this->call(IssueTableSeeder::class);
    
      Model::reguard();
    }
    

Creating Model Factories

  • Open database/factories/ModelFactory.php and you will see a default one already defined:
    $factory->define(App\User::class, function (Faker\Generator $faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->email,
            'password' => bcrypt(str_random(10)),
            'remember_token' => str_random(10),
        ];
    });
    
  • Please Note: If your app is going to send real email then you should utilize $faker->safeEmail instead of just ->email. The reason for this is ->email can potentially generate a real email, where safeEmail uses example.org that is reserved by RFC2606 for testing purposes.
  • create a new factory for our Issues model.
    $factory->define(App\Issues::class, function (Faker\Generator $faker) {
        return [
            'subject' => $faker->sentence(5),
            'description' => $faker->text(),
        ];
    });
    
  • Open the UserTableSeeder and adjust the run method:
    public function run()
    {
      factory(App\User::class, 2)->create()->each(function($u) {
        $u->issues()->save(factory(App\Issues::class)->make());
      });
    }
    
  • Now run php artisan migrate --seed

To use SQL

Add this line to the top of your controller

use DB;

Then you can write SQL functions like

$var = DB::select(‘SELECT * FROM dbname’);

Displaying Errors

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment