Automatically saving relationships when creating models with Eloquent ORM - php

I seem to be stumped on how to automatically save related models when creating a model instance in Laravel. Consider:
A User Model:
<?php
// file: User.php
class User extends Eloquent
{
public function role()
{
$this->hasOne('Role');
}
}
A Role Model:
<?php
// file: Role.php
class Role extends Eloquent
{
public function user()
{
$this->belongsTo('User');
}
}
Now lets say I want to create a new user and assign a it a role. Its quite easy to get the association to work if I set the role relationship after I save the user. For example, this works great:
$user = new User();
$user->name = 'Bobby';
$user->save();
$role = new Role();
$role->type = "Super Hero";
$user->role()->save($role);
However, if I want to push or cascade the save it fails to assign the foreignKey. I'd like to save() only once, and have the relationships save via cascade. For example, this doesn't work:
$user = new User();
$user->name = 'Bobby';
$role = new Role();
$role->type = "Super Hero";
$user->role = $role; // or $user->role()->save($role);
$user->save(); // push()?
This would be somewhat similar to how Doctrine 2 handles persisting. Is it possible to create both at the same time in Eloquent?

Related

yii2 bound two new models by id created on same action

Have one action where i am creating few models at the same time both are extends from ActiveRecord.
<?php class User extends ActiveRecord
{
}
class Balance Extends ActiveRecord
{
}
Controller class:
...
actionSignup(){
$model = new User();
$balance = new Balance();
$user->balance_id = ???;
$balance->user_id = $user->balance_id;
}
So till i do not save any models, i cant get id of this models! The best way to bound this models is generate some unique id in code and add specific column to database?
actionSignup(){
$balance = new Balance();
$balance>save();
$model = new User();
$user->balance_id = $balance->id;
$user->save();
$balance->user_id = $user->user_id;
$balance->save();
}

eloquent: How to load and set model variables, inside the model itself?

Laravel documentation suggests the following way to set up an eloquent model:
$user = user::with($conditions)->first();
What if I want to set up my eloquent model inside the model itself:
$user = new user();
$user->setup($conditions);
// class definition
class user extends Eloquent{
public function setup($conditions){
// load current object with table data
// something like
$this->where($conditions)->first();
// previous line output is dangling, is ok to assign it to $this variable?
}
}
If you're extending from Eloquent model, you may try the following approach. I assume you have a unique id column.
public function setup($conditions)
{
$model = self::with($conditions)->first();
if (! is_null($model)) {
$this->exists = true;
$this->forceFill(self::find($model->id)->toArray());
}
return $this;
}
Hope this solve your issue.

Can't access static methods in Eloquent (used outside Laravel)

I've followed Jeffrey Way's explanation and several other blog posts and articles, yet still cannot get this to work.
I want to use the Eloquent ORM outside of Laravel. I've included the requirements in my composer.json:
"illuminate/database": "v5.*",
"illuminate/events": "v5.*",
Then I instantiated the Capsule Manager:
$db = new Illuminate\Database\Capsule\Manager();
$db->addConnection($config['database']);
$db->setEventDispatcher(new Illuminate\Events\Dispatcher(new Illuminate\Container\Container));
$db->setAsGlobal();
$db->bootEloquent();
I've built a basic User model that extends the Eloquent Model:
use Illuminate\Database\Eloquent\Model as Eloquent;
class User extends Eloquent
{
public $incrementing = false;
protected $primaryKey = 'username';
protected $keyType = 'string';
}
Now I can create a new User as intended:
$u = new User([
'username' => $username,
'fullname' => $fullname,
'role_id' => $role_id,
]);
$u->save();
And this works like a charm, the user appears in the intended users table fine, yet I can't retrieve a user by any of these methods, my response is always null:
$user = User::find('foo'); // no dice
$user = User::where('username', 'foo')->get(); // nope
$user = User::first(); // nothing
Does anyone know why I can't use the static methods that come with Eloquent models? Or better yet, how to fix this?

Laravel : add new row in model table

I have a user model defined, and I'm trying to add a new user in my database using a form, what is the best and fastest way to do it, I have read something about model forms binding but I think it's just for updating not for adding new rows.
I'm new in Laravel and couldn't find some good tutorials, I must recognize that Laravel documentation is really poor, so any links to some good and well explained tutorials are welcomed.
Thank you
Assumed that, you have a User model (app/models/User.php) the one came with Laravel by default, which may look like this:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
Now, from a controller (Basically) you may use somethng like this:
$user = new user;
$user->username= 'Me';
$user->email = 'me#yahoo.com';
// add more fields (all fields that users table contains without id)
$user->save();
There are other ways, for example:
$userData = array('username' => 'Me', 'email' => 'me#yahoo.com');
User::create($userData);
Or this:
User::create(Input::except('_token'));
This requires you to use a property in your User model like this:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('username', 'email');
// Or this, (Read the documentation first before you use it/mass assignment)
protected $guarded = array();
}
Since, you are still new to Laravel you may use first example and read about Mass Assignment, then you may use the second one if you want.
Update:
In your controller, you may use Input::get('formfieldname') to get the submitted data, for example:
$username = Input::get($username);
So, you can use these data like this:
$user = new User;
$user->username= $username;
Or directly you can use:
$user->email = Input::get($email);
$user->save();
In the form, you have to set the form action, where you'll submit the form and in this case you have to declare a route, for example:
Route::post('user/add', array('as' => 'user.add', 'uses' => 'UserController#addUser'));
Then in your controller you have to create the method addUser, like this:
class UserController extends addUser {
// other methods
public function addUser()
{
$user = new user;
$user->username = Input::get('username');
$user->email = Input::get($email);
$user->save();
}
}
In your form you may use this:
Form::open(array('route' => 'user.add'))
Read the documentation properly, you can do it easily.

Doctrine 2 - Updating a user password without the user being logged in

I am using Doctrine 2 in Zend framework.
What I want is to update a user password, without the user being logged in. Is this the right way to do it in entity class?
public function updatePassword($userId, $new_pass, $em){
$em->getConnection()->getConfiguration()->setSQLLogger( new \Doctrine\DBAL\Logging\EchoSQLLogger());
$qb = $em->createQueryBuilder();
$q = $qb->update('\Application\User\Entity\User', 'u')
->set('u.password', $qb->expr()->literal($new_pass))
->where('u.userId = ?1')
->setParameter(1, "$userId")
->getQuery();
$p = $q->execute();
return $p;
}
The entity class should never utilize the entity manager. The entity class is just a data storage.
User entity class:
namespace Entity;
class User {
// ...
public function setPassword($password)
{
$this->password = some_hash_algorythm($password);
return $this;
}
// ...
}
Your controller or whereever you want to update a user's password:
$repo = $em->getRepository('Entity\User');
$user = $repo->find($userId);
$user->setPassword($newPassword);
$em->persist($user);
$em->flush();
This divides the data storage from actual persistence layer.
If you do not like to have the code in place and want to have it in a central place look in doctrine's documentation for custom repository classes (they are aware of the entity manager and there for "table-actions")

Categories