Skip to content

Instantly share code, notes, and snippets.

@FernE97
Last active April 9, 2021 21:56
Show Gist options
  • Save FernE97/bc3a7231d789eef9d7bf766344f601e8 to your computer and use it in GitHub Desktop.
Save FernE97/bc3a7231d789eef9d7bf766344f601e8 to your computer and use it in GitHub Desktop.
Rails & Laravel comparisons

Rails & Laravel comparisons

Start console

# rails

bundle exec rails c
# laravel

php artisan tinker

New instance

user = User.new
user.email = '[email protected]'
user.save

# or

user = User.create(email: '[email protected]')

Laravel will alias the shorthand, such as User to App\Models\User so these examples will just use the aliased version.

$user = new User;
$user->email = '[email protected]';
$user->save();

Find by ID

user = User.find(1)
$user = User::find(1);

Find by attribute

user = User.find_by(email: '[email protected]')

# or

user = User.where(email: '[email protected]').first
$user = User::where('email', '[email protected]')->first();

Find by multiple attributes

aprroved_admins = User.where(admin: true, approved: true)
$approved_admins = User::where('admin', true)->where('approved', true)->get();

Update instance

user = User.find(1)
user.update(email: '[email protected]')

# or

user.email = '[email protected]'
user.save
$user = User::find(1);
$user->update(['email'=>'[email protected]']);

# or

$user->email = '[email protected]';
$user->save();

Delete

user = User.find(1)
user.destroy
$user = User::find(1);
$user->delete();

Collection all

users = User.all
$users = User::all();

Collection first & last

users = User.all
first_user = users.first
last_user = users.last
$users = User::all();
$first_user = $users->first();
$last_user = $users->last();

Count

User.count
User::count();

Pluck attribute

emails = User.all.pluck(:email)
$emails = User::all()->pluck('email');

Associations has_many

# has_many :posts

user = User.find(1)
posts = user.posts
# public function posts() { $this->hasMany('App\Models\Post'); }

$user = User::find(1);
$posts = $user->posts;

Associations belongs_to

# belongs_to :user

post = Post.find(1)
user = post.user
# public function user() { return $this->belongsTo('App\Models\User'); }

$post = Post::find(1);
$user = $post->user();

Collection loop

users = User.where(name: 'Rails')
users.each do |user|
  user.name = 'Ruby on Rails'
  user.save
end
$users = User::where('name', 'Laravel')->get();
foreach ($users as $user) {
  $user->name = 'Laravel PHP Framework';
  $user->save();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment