I'm working on a project built on Laravel 3, and I'm trying to see if I can shorten the code for working with relationships (better ways of doing the following)
user controller
create user function
$newUser = new User;
if($userData['organization'])
$newUser->organization = self::_professional('Organization', $newUser, $userData);
else
$newUser->school = self::_professional('School', $newUser ,$userData);
create or retrieve school/organization id
private function _professional($type, $newUser, $userData)
{
if ( $orgId = $type::where('name', '=', $userData[strtolower($type)])->only('id'))
return $orgId;
else
{
try {
$org = $type::create(array('name' => $userData[strtolower($type)]));
return $org->attributes['id'];
} catch( Exception $e ) {
dd($e);
}
}
}
Models
User model
class User extends Eloquent {
public function organization()
{
return $this->belongs_to('Organization');
}
public function school()
{
return $this->belongs_to('School');
}
}
Organization/School model
class Organization extends Eloquent {
public function user()
{
return $this->has_many('User');
}
}
Migrations
Users migration
....
$table->integer('organization_id')->unsigned()->nullable();
$table->foreign('organization_id')->references('id')->on('organizations');
$table->integer('school_id')->unsigned()->nullable();
$table->foreign('school_id')->references('id')->on('schools');
....
Organizations/Schools migration
....
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('count')->default(1)->unsigned();
....
Now, my questions are:
Is there any better way of generating the User -> School/Organization relationship, then the one used above? If so, how?
Any better way of retrieving the User's School/Organization name then by doing:
School::find($schoolId)->get()
Doing User::find(1)->school()
won't retrieve any data for school
, only:
[base:protected] => User Object
(
[attributes] => Array
(
[id] => 1
[nickname] => w0rldart
....
[organization_id] =>
[school_id] => 1
...
)
[relationships] => Array
(
)
[exists] => 1
[includes] => Array
(
)
)
[model] => School Object
(
[attributes] => Array
(
)
[original] => Array
(
)
[relationships] => Array
(
)
[exists] =>
[includes] => Array
(
)
)