# rails
bundle exec rails c
# laravel
php artisan tinker
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();
user = User.find(1)
$user = User::find(1);
user = User.find_by(email: '[email protected]')
# or
user = User.where(email: '[email protected]').first
$user = User::where('email', '[email protected]')->first();
aprroved_admins = User.where(admin: true, approved: true)
$approved_admins = User::where('admin', true)->where('approved', true)->get();
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();
user = User.find(1)
user.destroy
$user = User::find(1);
$user->delete();
users = User.all
$users = User::all();
users = User.all
first_user = users.first
last_user = users.last
$users = User::all();
$first_user = $users->first();
$last_user = $users->last();
User.count
User::count();
emails = User.all.pluck(:email)
$emails = User::all()->pluck('email');
# 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;
# 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();
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();
}