Grabbing userID and field upon user creation - php

I currently have a function that simply creates a user record in the database
$user->name;
$user->address;
$user->save();
Once this is done, I've created an id for them in my users table.
I know I can return $user, but specifically how can I grab the id and name from that to be used in a call like so:
$user->save();
//return $user id and $user name
$update = new UpdateTable($id,$name);

When you call $user->save(), the id (or primary key if it is not id) becomes available via $user->id. So, you'd simply pass the following to your UpdateTable() method:
$user = new User();
$user->name = "Test";
$user->address = "123 Somewhere";
$user->save();
$update = new UpdateTable($user->id, $user->name);
...

Try this code
$user = User::create(['name' => 'name', 'address' => 'Some address']);
$update = new UpdateTable($user->id, $user->name);
or
$update = new UpdateTable($user->getPrimaryKey(), $user->name);

Related

Can not retrieve the id of a foreign key [Laravel]

I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.
When the User completes the form, I put the User & demands information inside those 2 tables.
But I do not know how to have the User id to put it inside the demands table.
Here is the function inside my Controller:
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user ->numStudent= $request->NumStudent;
$user ->role_id = "3";
$user ->Lastname = $request->LastName;
$user ->FirstName= $request->FirstName;
$user ->numero_etudiant = "12345678";
$user ->email = $request->Email;
$user ->password = bcrypt('idk');
$user ->adress= $request->Adress;
$user ->phone = $request->Phone;
$user ->parcours = $request->Parcours;
$demand->status_id= "3";
//problem below
$demand->User_id= $User;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$user ->save();
$demand->save();
return redirect('/demands_list');
}
But it says "Can't use method return value in write context".
Cordially
You have to save first the instance of your user before using its properties. Your code should look like this.
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user->numStudent= $request->NumStudent;
$user->role_id = "3";
$user->Lastname = $request->LastName;
$user->FirstName= $request->FirstName;
$user->numero_etudiant = "12345678";
$user->email = $request->Email;
$user->password = bcrypt('idk');
$user->adress= $request->Adress;
$user->phone = $request->Phone;
$user->parcours = $request->Parcours;
$user->save();
$demand->status_id= "3";
//problem below
$demand->User_id= $user->id;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$demand->save();
return redirect('/demands_list');
}
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.
The short answer: use route model binding and keep your controller methods organized and single-focused.
As already answered, your User needs to be saved first. I would recommend you do this step in its own controller:
// UsersController.php
public function store(Request $request) {
$attributes = $request->validate([
// validation rules
]);
$user = User::create($attributes);
return redirect('/users/' . $user->id);
}
Now that you have a User created, you can then attach related models. Create a separate set of routes pointing to a separate controller for handling the relationship:
// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController#index');
Route::post('/user/{user}/demands', 'UserDemandsController#store');
// ^^^^^^
// used with route model binding
Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):
// UserDemandsController.php
public function store(Request $request, User $user) { // <-- ROUTE MODEL BINDING
$attributes = $request->validate([
// validation rules
]);
$user->demands()->create($attributes);
}
The result is very clean, simple code.

Laravel Indirect modification of overloaded property error when saving to database

I'm trying to save my eloquent model with its relationship.
According to documentation, this is how you save it.
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
This is my initial code:
$user = new User;
$user->name = request()->name;
$user->username = request()->username;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->profile->account_number = request()->account_number;
$user->push();
and it throws me the "Indirect modification of overloaded property" error.
My fix is:
$user = new User;
$user->name = request()->name;
$user->username = request()->username;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->save();
$profile = new Profile;
$profile->user_id = $user->id;
$profile->account_number = request()->account_number;
$profile->save();
What is missing in my first code for it to work? I really think it will work like that with the push() method.
In the first example, the profile does not exist yet. You are trying to modify a property of null.
$user->profile
// null
$user->profile->account_number
// Indirect modification of overloaded property
However, you can use the relationship like this after the user is saved.
// ...
$user->save();
$user->profile()->save(new Profile([
'account_number' => request()->account_number
]));
And once both models exist, you can use the relationship like this.
$user->profile->account_number = request()->account_number;
$user->push();

Laravel 5.2 - Login user after create post

i'm doing a project where ALL user can create a post and pubblic it!
if user not logged blade enable a section with email and password to create account and post.
I would like do:
Creation user
Log user in session auth ( HERE IS MY PROBLEM, HOW CAN I DO THIS? )
Create Post (last point because i need user_id)
CONTROLLER
// if user NOT registered my form will enable email and password field --
if(!null($request->input('email') && request->input('password'))) {
// create user
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('name'));
$user->save();
// login user after create user
HOW CAN I LOG USER AFTER CREATED ACCOUNT ???
Thank you for your help!
// Get ID of user created
$get_user_id = User::where('email', '=', $request('email'))->first();
// create post
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $get_user_id->id;
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
// IF USER LOGGED
}else{
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $request->input('user_id');
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
}
The answer is:
Auth::login($user);
Check out the doc.
Is not so clear what you want to do here, the way you get the user id is insecure.
I'll recommend you to use $user = Auth::user(); instead to get the user id, ($user->id).
to check the login manually use
if (Auth::attempt(['email' => $email, 'password' => $password])) {}
so in your example I'll do something like:
if (!Auth::attempt(['email' => $email, 'password' => $password])) {
// create User
} else {
// $userId = Auth::user()->id;
}
// finally create post
Add a __construct() method to your class, and add following code:
public function __construct() {
$this->middleware('auth', ['except' => ['index', 'show']]);
}
And it must actually work

Getting Objects from database in Symfony2

I had read somewhere some day that symfony2/Doctrine2 has a method(i don't remember the method name now) that fetches all "like" objects that we specify..
For example, I have User entity that has userName , password, name, state and city as properties.. For getting all Users who has name = "vinay" and state = "karnataka", the steps goes like this,,
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$query = $em->dontKnowTheMethod($user);
$usersList = $query->getResult();
$usersList should contain all the users whose name = "vinay" and state = "karnataka"
I searched for hours but Im not getting that method.. Im sure I had read about that method long back but I cannot recall now..
Thanks in advance..
You should start studying doctrine and symfony.
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$repo = $this->getDoctrine()->getRepository('YourWhateverBundle:User');
$userResult = $repo->findAll(['name' => 'vinay', 'state' => 'karnataka'])
if (!$userResult instanceof User) {
echo 'No result found';
} else {
// Do whatever you want with $userResult
}

Yii Framework $model->save() work for one model only

I try to take the facebook information of a user in my databade. I'm in the UserIdentity to control the athentification of the user and i created this method.
<?php
public function insertFbUser()
{
$user = new User();
$user->fbId = $this->username['id'];
$user->username = $this->username['username'];
$user->email = $this->username['email'];
$user->password = $this->password;
$profile = new Profile();
$profile->first_name = $this->username['first_name'];
$profile->last_name = $this->username['last_name'];
$profile->birthday = strtotime($this->username['birthday']);
$profile->sex = $this->username['gender'];
$profile->fb_updated_time = strtotime($this->username['updated_time']);
$profile->fb_verified = $this->username['verified'];
$profile->fb_educationJson = json_encode($this->username['education']);
$profile->fb_workJson = json_encode($this->username['work']);
var_dump($user->save());
var_dump($profile->save());
}
the var_dump() show me this
boolean true
boolean false
Both models were created with the GII module. I try to only put one prile attribute at a time and it doesn't work too...
There is my DB : http://pastebin.com/u5CNKj9M
Thank you for your help!
print_r($profile->getErrors());
(Update)To get user id after saving:
$user->save();
$user_id = $user->id

Categories