I am developing a booking form that has data that will fill two tables, users and booking table. In the controller I am getting the input fields and inserting the user fields first, then I do the insert for the booking but I need the id of the user I've just inserted, I have tried many methods without success, this is what I have done in my controller:
$User = new User;
User::create(array(
'lastname'=>Input::get('lastname'),
'name'=>Input::get('name'),
'address'=>Input::get('address'),
'cell_phone'=>Input::get('cell_phone'),
'email'=>Input::get('email')
));
// I try to get the inserted user id here
$userInserted=$User->id;
// And here I insert the booking with the user_id
$Booking = new Booking;
Booking::create(array(
'apartment_id'=>Input::get('apartment_id'),
'user_id'=>$userInserted,
'date_ini'=>Input::get('date_from'),
'date_fin'=>Input::get('date_to'),
'stay_cost'=>Input::get('stay_cost'),
'stay_days'=>Input::get('stay_days')
));
The problem is I am not getting the user Id. Any idea way?
thanks in advance
You are assignin it wrong.
$newUser = User::create(...);
$insertedUserId = $newUser->id;
Your $User = new User; makes no sense, because it just initializes emty User Object, but User::create sends query to DB to store data and returns inserted Object.
Related
In my application, I have two types of users "title" & "notary".
I have connected some users to these roles by many to many relationship [there is a table 'role_user', which is pivot table and contains 'user_id' from users table and 'roles_id' from roles table].
I have made seeds to give the users, specific roles. till this point my application is fine.
Now, I want to set a users role, when he registers [the idea is to select a radio button before registration].
When someone registers, he will be given selected role. How to do this in many to many relationship?
When user selects radio button then you will get that value and call a relationship on user to assign role.
$role = $request->role //get this value from radio
Since this is registration method so you will first create user and call a relationship to attach role.
$user = User::create($request->only('required fields ...'));
Now attach role to created user.
$user->roles()->attach($role); //this line is actual answer to your question
This will fill your pivot table with user role
Make sure you have defined roles() method in User.php model
public function register (Request $request){
$role = $request->role; //this is not necessary to save role value in variable you can get it directly from request object
$user = User::create($request->only('required fields'));
$user->roles()->attach($role or $request->role); // you can get role value directly from $request object.
}
I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.
If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;
Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.
I need to display all the vehicle records belonging to properties of the currenty logged on user.
Before I pass the data to the view I need to filter out all the properties except those owned by the current user id.
I have a relationship in the Vehicle model that performs the foreign key constraint.
public function propiedad(){
return $this->belongsTo('App\Property', 'propiedad_id','id' );
}
My Controller is using this filter before passing the data to the view. I assume I have to acquire the property ids that belong to the user before I filter the vehicles that belong to those properties. This is where I am having trouble.
$user_properties = array(?????);
$Vehiculo = Vehiculo::where('propiedad_id', $user_properties);
If your properties table has a user_id column then on your user model define a vehicles hasManyThrough relationship like
public function vehicles()
{
return $this->hasManyThrough(Vehicle::class, Property::class);
}
Then in your controller you can do:
$users = User::with('vehicles')->get();
Or for a single user
$vehicles= User::find($id)->vehicles;
What is the difference between save() and update() method in Laravel.
I have used save() method in case of update query but in few cases it acts as update and in few case it act as insert query function. Please let me know what exactly the difference between them.
These methods both allow you to save data to a database.
The save() method performs an INSERT when you create a new model which is currently is not present in your database table:
$flight = new Flight;
$flight->name = $request->name;
$flight->save(); // it will INSERT a new record
Also it can act like an UPDATE, when your model already exists in the database. So you can get the model, modify some properties and then save() it, actually performing db's UDPATE:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save(); //this will UPDATE the record with id=1
Theupdate() method allows you to update your models in more convenient way:
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]); // this will also update the record
So you don't even need to assign the retrieved model to any variable. Updated properties are passed as arguments.
Examples and more info in the Laravel's docs.
There is only one thing left unsaid in what #ginopane told about the difference and it's that if you use update method on a query builder result then laravel will ignore $fillable or $guard array of your model. This is especially important if you want to use Input::all() as an argument to update:
Post::where('id', $id)->update(Input::all());
So in this case if you use App\Flight::where('active', 1)->update(Input::all()); everything in your database will be updated even if you put it in $fillable. So make sure to use save and update methods on Eloquent instance and not Query builder one. The following code will be fine even if the user submit fields that you don't want to insert or update in your databse table:
// User model
protected $fillable = ['email', 'name'];
// controller
public function update($id)
{
$user = User::findOrFail($id);
// validate the input here, use Request to do the job or whatever you like
$user->update(Input::all());
return view('some_view')->with('notice', 'user updated');
}
Now, no matter what with the FORM being passed here, only name and email will be updated.
Hope this complete #ginopane answer
save() : you can look to it as the equivalent of the INSERT in sql, it will create a new model (and insert it in the database)
To create a new record in the database, create a new model instance, set attributes on the model, then call the save method
update() : you can look to it as the equivalent of the UPDATE in sql, it will create a new model (and insert it in the database)
The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value
code
$flight = App\Flight::find(1);
if (empty($flight)) {// you can do this condition to check if is empty
$flight= new Flight;//then create new object
}
$flight->name = 'New Flight Name';
$flight->save(); //this will UPDATE the record with id=1
for more detail doc
Im at a bit of a loss. I have an api that will create a user upon a request. This is done no problem.
I also want to create another controller action or add to my current action the ability to create an address for the same user.
Is there an easy way to do this? Or should I stick to the
$user = new User(Input::all());
$user->save();
$address = new Address(Input::all());
$address->save();
You should set up relationships between your User and Address model - http://laravel.com/docs/eloquent#relationships and use associate/sync() to connect the dots.
This is a relationship problem. An address to a user will most likely be One-to-One (i.e., each Userhas a unique Address). A User might have an Address, but an Address must have a User. So in essence, the Address belongs to User.
Create two tables users and addresss, and add user_id to the address table as a column.
Then you define your relationships:
// In your User.php model
public function address()
{
return $this->hasOne('Address');
}
// In your Address.php model
public function user()
{
return $this->belongsTo('User');
}
Note when you use the correct notation, you can just define the model name, and not specify the pivot column. That is why I have defined the class addresss with an extra 's' to make it plural. I personally don't care about the spelling and rather Laravel take care of everything. Otherwise read the documentation on how to define the pivot column
Then you can use associate easily:
$user = new User();
// Fill $user however you want
$address = new Address();
// Fill $address however you want
$user->associate($address);
$user->save();
I was able to figure it out!
I wound up utilizing the Ardent package to help me validate my models before they hit the save method.
if my models didnt validate i will return all the errors to the user.
If they did validate my models would be created.
As for the association I am using the has many relation ship on the User and belongs to on the Address.
I used the following to save the address to the user
$address = $user->address()->save($address);
however I could only preform this after the initial user object was saved.
Thanks for all the responses guys they lead me in the right direction!