Saving related records in laravel - laravel

I have users, and users belong to a dealership.
Upon user registration, I'm trying to save a new user, and a new dealership.
User database has a dealership_id column, which I want to be populated with the ID of the newly created dealership.
This is my current code in the UserController store method.
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Trying to use $user->push(); User data gets updated, but dealership is not created or updated.

Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.
Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}
To save a User from the Dealership perspective, you do this:
$dealership->users()->save($user);
To associate a dealership with a user, you do this:
$user->dealership()->associate($dealership);
$user->save();

Please check this answer to see the difference of push() and save()
You will need to define correctly your models relationships as per documentation
If this is done correctly, it should work .
This is what push() does :
/**
* Save the model and all of its relationships.
*
* #return bool
*/
public function push()
{
if ( ! $this->save()) return false;
// To sync all of the relationships to the database, we will simply spin through
// the relationships and save each model via this "push" method, which allows
// us to recurse into all of these nested relations for the model instance.
foreach ($this->relations as $models)
{
foreach (Collection::make($models) as $model)
{
if ( ! $model->push()) return false;
}
}
return true;
}
In your case, you have a one (dealership) belongs to many (users)
In your Users model :
class Users extends Eloquent {
public function dealership()
{
return $this->belongsTo('Dealership');
}
}
In the example above, Eloquent will look for a dealership_id column on the users table.
In your Dealership Model :
class Dealership extends Eloquent {
public function users()
{
return $this->hasMany('User');
}
}
In your store function :
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->dealership = new Dealership();
$user->dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Learn here more about eloquent relationships
Also please take a look at my answer here

By using push on the User model, Laravel is basically recursively calling save on all the related models (which, in this case, is none, since you haven't associated any other models to it yet).
Therefore, in order to accomplish what you're trying to do, you can do first create the user then associate the dealership with it by doing the following:
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->dealerships()->save($dealership);
return "User Saved";
However, prior to doing this, you must ensure your User and Dealership models have their relationships set up correctly:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}

This is how I manage to do it.
In your controller: (Laravel 5)
use Auth;
$dealership->user = Auth::user()->ref_user->staff_id;

Related

Laravel associate relationships by model instance dynamically

In my Laravel 9 project, My User Model is belongs to 3 models (Distributor, Agency and Advertiser) like:
public function distributor()
{
return $this->belongsTo(Distributor::class);
}
public function agency()
{
return $this->belongsTo(Agency::class);
}
public function advertiser()
{
return $this->belongsTo(Advertiser::class);
}
And I use this function to associate in my DistributorRepository(and other 2 model's repositories):
public function associateUser($id, $user_id)
{
$user = $this->user->find($user_id);
$distributor = $this->find($id);
$result = $user->distributor()->associate($distributor)->save();
return $result;
}
Now, I want to modify to associate them by user's id and relation model instance (Distributor, Agency and Advertiser) in my UserRepository (or UserService) dynamically, like:
public function associate($id, $modelInstance)
{
// Something happens here
}
Is that possible and how to do? Thanks!
If I understand right, then you can do it with:
public function associate($user_id, $parentModelInstance)
{
$user = User::find($user_id); //or how ever you get user in repository
$reflect = new ReflectionClass($parentModelInstance);
$relationName = Str::lower($reflect->getShortName()); //magic for getting relation (if class name is relation name)
return $user->{$relationName}()->associate($parentModelInstance)->save();
}
And you can use it like this:
$distributor = Distributor::find(1);
$user_id = 1;
$this->associate($user_id, $distributor)

Model Relationships not finding the property

I'm trying to create a relationship between two models. My first model is the User Model, the second one is Company.
I tried adding in the User model the hasMany('App\Comapny') property, and in the Company one, belongsTo('App\User').
// In User Model
public function companies(){
return $this->hasMany('App\Company');
}
// In Company Model
public function user(){
return $this->belongsTo('App\User');
}
// And in the controller:
$user_id = auth()->user('id');
$user = User::find($user_id);
return view('devices.show')->with('companies', $user->companies);
It should return an array with all the companies that my User has when using "$user->comapnies", however, it returns this message instead:
Property [companies] does not exist on this collection instance.
Thanks, any help is welcome
Thanks for the quick response. I figured it out, the problem was this line:
$user_id = auth()->user('id');
It should be instead
$user_id = auth()->user()->id;
Try this,
$user_id = auth()->user->id;
$user = User::with('companies')->where('id', $user_id)->first();
return view('devices.show', compact('user'));
Then you can access the company relation with
$user->company[index]->
in the view.

Laravel: Retrieve data inputted by user

I'm quite new to Laravel and I'm confused with how I have to retrieve data inputted by certain users.
In my project, there is a user profile that should display all form submissions by the user.
Here is my controller function:
public function clientAccount(BookingRequest $bookings)
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = BookingRequest::with(Auth::id())->with('client')->first(); //unsure about here//
return view('client.account', compact('client','bookings'));
}
Here is my model:
public function client()
{
return $this->belongsTo('App\Client', 'client_id', 'user_id');
}
How do I fix this?
EDIT:
I tried using this but somehow I don't get any display
$bookings = BookingRequest::where('client_id',Auth::id());
If the relationship needs to be one to many meaning one Client has many Bookings, than in your Client model you should have the following function:
public function bookings()
{
return $this->hasMany(BookingRequest::class);
}
then you just need to find the client, and for him you just use
$client->bookings()
it will list all the bookings for that client.
Following on from nakov:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->bookings();
return view ('client.account')->with('bookings', $bookings)
}
And in your user profile view:
foreach($bookings as $booking){
// do something with each booking
// e.g. var_dump($booking) to see the data you're working with
}
Thanks for all your responses!
I'm now able to retrieve data by using this:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->booking()->with('client')->get();
return view('client.account', compact('client','bookings'));
}
and in my model, I used this instead
public function booking()
{
return $this->hasMany('App\BookingRequest', 'client_id', 'user_id');
}

How to retrieve only those object and its related model which passes the required criteria in laravel4?

I have three tables: users, departments and designations
I have created corresponding model for 'users', 'designations' and 'departments' table.
Relationship between table is:
User model
public function department(){
return $this->belongsTo('Department');
}
public function designation(){
return $this->belongsTo('Designation');
}
--
Department model
public function users(){
return $this->hasMany('User');
}
--
Designation model
public function users(){
return $this->hasMany('User');
}
Now, how would I query (in an eloquent way) to retrieve all the users that belongs to only specified department (say, 'account' department only).
I tried eager loading as well, but since there were two models that have to be fed with, it was more confusing.
I have a code as below, but now working. Help me to find the mistake
$users = new User;
$users = $users->department()->where('dept_code', '=', 'account')->get();
return View::make('staffs', compact('users'));
Here are two ways to do it:
1. From the Department side
$department = Department::where('dept_code', 'account')->first();
$users = $department->users;
2. From the User side using whereHas
$users = User::whereHas('department', function($q){
$q->where('dept_code', 'account');
})->get();
(Of course you can also use them like $users = new User; $users->where(, but I prefer the static call syntax so I use them in my examples)
You define a relationship with the constant. Like this:
User model
public function department(){
return $this->belongsTo('Department');
}
public function accounts_department(){
return $this->belongsTo('Department')->where('dept_code', 'account');
}
Then you use it like this
$all_users = new User;
$all_users = $all_users->department()->get();
$account_only_users = new User;
$account_only_users = $account_only_users ->accounts_department()->get();

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...
this is my controller
class DeskController extends BaseController{
public function getDeskUsers($deskId){
$user = DeskUserList::where(function($query) use ($deskId){
$query->where('deskId', $deskId);
})->with('userName')->get(array('deskId'));
if (!$user->isEmpty())
return $user;
return 'fail';
}
this is the model
class DeskUserList extends Eloquent {
protected $table = 'desk_user_lists';
public function userName(){
return $this->belongsTo('User', 'userId')->select(array('id','userName'));
}
}
the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).
practically I want each record returned is composed of:
DeskUserList.deskId
User.userName
eg. [{"deskId":"1","user_name":antonio}]
What i get is
[{"deskId":"1","user_name":null}]
As you can see the user name is a null value...
BUT
if I edit my controller code:
->with('userName')->get(array('userId')); //using userId rather than deskId
then i get
[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]
By this way I still have two problem:
the userId field is twice repeated
I miss the deskId field (that I need...)
hope be clear, thanks for your time!
You need belongsToMany, no need for a model representing that pivot table.
I assume your models are Desk and User:
// Desk model
public function users()
{
return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}
// User model
public function desks()
{
return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}
Then:
$desks = Desk::with('users')->get(); // collection of desks with related users
foreach ($desks as $desk)
{
$desk->users; // collection of users for particular desk
}
// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Resources