I'd like to improve this piece of code when updating a related model (1 to 1) on laravel and also know if this is right, wrong, right but not recommended, etc. Thanks all.
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->update();
$tenant = Tenant::where('user_id', $id)->first();
$tenant->suite_number = $request->input('suite_number');
$tenant->update();
First you have to define relationship of user and tenant in you user model:
// User.php
public function tenant()
{
return $this->hasOne('App\Tenant');
}
As this is an one to one model, you can update your related model like following. Make sure the relation model also exists.
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->tenant->suite_number = $request->input('suite_number');
$user->push();
i believe it could be
// you can omit the input() if u want to
$user = User::find($id);
$user->update([
'name' => $request->name;
'email' => $request->email;
]);
$tenant = Tenant::where('user_id', $id)->first();
$tenant->update([
'suite_number' => $request->suite_number;
]);
for eager loading it would be
$user = User::with('tenant')->find($id);
$user->update([
'name' => $request->name;
'email' => $request->email;
'tenant.suite_number' => $request->suite_number;
]);
or reverse relation
$tenant = Tenant::with('user')->where('user_id', $id)->first();
$tenant->update([
'suite_number' => $request->suite_number;
'user.name' => $request->name;
'user.email' => $request->email;
]);
Related
I have created a form where the admin can register accounts on the system. The problem is that the password is not hashed when the user is created on the admin side, and I think this is what stops the user from logging in on the system. Do you have any tips for me to make this work? I'm a total newbie at Laravel so.
I think the problem is in this code..
public function store(Request $request)
{
$this->validate(request(), [
'firstname' => 'required|string|max:255',
'lastname' => 'required|string|max:255',
'username' => 'required|string|max:25|unique:users',
'phone' => 'required|string|max:12|min:11|unique:users',
'address' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
'membership_term' => 'required|string|max:255',
'mode_of_payment' => 'required|string',
]);
$user = new User;
$user->firstname = $request->input('firstname');
$user->lastname = $request->input('lastname');
$user->username = $request->input('username');
$user->phone = $request->input('phone');
$user->address = $request->input('address');
$user->email = $request->input('email');
$user->password = $request->input('password');
$user->membership_term = $request->input('membership_term');
$user->mode_of_payment = $request->input('mode_of_payment');
$user->save();
return back()->with('success', 'Data Updated.')->with('users', $user);
}
Try This
use Illuminate\Support\Facades\Hash;
$user->password = Hash::make($request->input('password'));
You can use laravel helper function bcrypt()
$user->password = bcrypt($request->input('password'));
ref link https://laravel.com/docs/6.x/helpers#method-bcrypt
I got this error
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
when i'm trying to Register User API.
i dont know what 's wrong with it...
My AuthController
public function register(Request $request)
{
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|between:6,25',
]);
$user = User::all();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'registered' => true,
'token' => $user->createToken('token')->accessToken
]);
}
Any help? Thanks....
$user = User::all(); return a collection of all users in database, you should replace it with $user = new User;, which return a new User object.
Change code to
public function register(Request $request)
{
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|between:6,25',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'registered' => true,
'token' => $user->createToken('token')->accessToken
]);
}
I send data from client to server in application/json content type.
Then I try to take this information in server side like as:
public function register(Request $request)
{
$data = $request->json()->all();
var_dump($data); die();
}
It returns me empty array()
Also I tried to validate incoming POST using this:
$validator = Validator::make($request->json()->all(), []);
How to get and validate application/json data in Laravel?
I get POST data like as:
dd($_POST);
array:1 [▼
"application/json" => "{"id":6,"unique_code":null,"name":"О","secondname":"П","lastname":"Валерьевич","datebirth":"14/10/1991 00:00:00","taxcode":"4545","gender":"1","created_at":null,"file":"C:\\db\\tests\\22-07-2017\\MMM1.TXT","orders":{"profession":"Директор","pacient_id":null,"payment":"1","kind_work":"1,2","factory_name":"FALKO","factory_edrpou":"2020","factory_departament":"IT","status_pass":"1","office_address":"Kiev","unique_code":"0","enterprise_id":"12","status":null},"http_code":null}"
]
I have an api I post json to. I have an api end point where I post this json
{
"email":"youremail#triumworks.com",
"phone": "phone",
"name": "name",
"password": "password"
}
The corresponding controller that handles the request looks like
public function create_account(Request $request){
$data = json_decode(file_get_contents('php://input'));
$response = new Responseobject;
$array_data = (array)$data;
$validator = Validator::make($array_data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'phone' => 'required|string|min:12|max:12|unique:users',
]);
if($validator->fails()){
$response->status = $response::status_failed;
$response->code = $response::code_failed;
foreach ($validator->errors()->getMessages() as $item) {
array_push($response->messages, $item);
}
}
else{
$api_token = str_random(60);
$user = new User();
$user->api_token = $api_token;
$user->name = $data->name;
$user->email = $data->email;
$user->phone = $data->phone;
$user->password = bcrypt($data->password);
if($user->save()){
$response->status = $response::status_ok;
$response->code = $response::code_ok;
$response->result = $user;
}
}
return Response::json(
$response
);
}
This does the same thing as the one above.
public function create_account(Request $request){
$response = new Responseobject();
$validator = Validator::make($request->json()->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'phone' => 'required|string|min:12|max:12|unique:users',
]);
if($validator->fails()){
$response->status = $response::status_failed;
$response->code = $response::code_failed;
foreach ($validator->errors()->getMessages() as $item) {
array_push($response->messages, $item);
}
}
else{
$api_token = str_random(60);
$user = new User();
$user->api_token = $api_token;
$user->name = $data->name;
$user->email = $data->email;
$user->phone = $data->phone;
$user->password = bcrypt($data->password);
if($user->save()){
$response->status = $response::status_ok;
$response->code = $response::code_ok;
$response->result = $user;
}
}
return Response::json(
$response
);
}
The posted data will end up in the request body parameter bag. You get the data either via $request->all() or $request->request->all().
So the Validator looks like this:
$validator = Validator::make($request->all(), []);
Dive deeper:
Or you can use the validate() method in your controllers. Which look like this:
$this->validate($request->all(), []);
Read more about this in the Laravel docs.
To make things even more complicator, you don't even need to inject the Request instance to your controller. You can use the request() helper function. The register method then looks like this:
public function register()
{
$this->validate(request()->all(), [
'email' => 'required|email',
'password' => 'required|min:6|confirmed',
]);
}
Here's my store function. I've tried playing with it a few different ways. For some reason I thought maybe putting the $post->save(); inside the if would at least change the profile image, but no. Not even that works. I initially tried return redirect()->route('profile')->withUser($user); and that didn't work either. This is my latest attempt. And still no luck so I thought to post it here. Thanks in advance! Using: Laravel 5.4
public function store(Request $request)
{
$this->validate($request, array(
'description' => 'required|string',
'projects' => 'required|string',
'experience' => 'required|string',
'links' => 'required|string',
'status' => 'required|string',
));
$userInfo = new User_Info;
$user_id = Auth()->user()->id;
$user = User::find($user_id);
$userInfo->user_id = $user_id;
$userInfo->description = $request->input('description');
$userInfo->projects = $request->input('projects');
$userInfo->experience = $request->input('experience');
$userInfo->links = $request->input('links');
$userInfo->status = $request->input('status');
$userInfo->save();
return redirect()->route('profile')->withUser($user);
}
public function settings($id)
{
$user = User::find($id);
return view("profile.settings")->withUser($user);
}
public function update(Request $request, $id)
{
$user_id = Auth()->user()->id;
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'required|string',
'projects' => 'required|string',
'experience' => 'required|string',
'links' => 'required|string',
'status' => 'required|string'
));
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
}
$user = User::find($id);
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->type = $request->input('type');
$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
$user_info->description = $request->input('description');
$user_info->projects = $request->input('projects');
$user_info->expereince = $request->input('experience');
$user_info->status = $request->input('status');
$user->save();
$user_info->save();
return view('profile.profile')->withUser($user);
}
You don't get existing object, so change this:
$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
To something like this:
$user_info = UserInfo::where('user_id', $user->id)->first();
Ok so we can create a new user:
$user = new User;
$user->name = 'Megauser'
$user->save();
And then we can add some user items:
$item = new Item;
$item->user_id = $user->id; //id we got from a freshly created user
$item->quantity = '9000';
$item->save();
But what if we mass assign the user?
User::create([
'name' => 'Megauser'
)];
The create method will return the new object with its ID.
$user = User::create([
'name' => 'Megauser'
)];
$userId = $user->id
Or as Rob Gordijn pointed out below, if you are worried about key names, you can use the getKey() call.
$userId = $user->getKey();
This is necessary if someone overrides the column name in their Eloquent model. For example:
class Example extends Eloquent {
$primaryKey = 'uid';
}
$user = User::create([
'name' => 'Megauser'
)];
I would go for
<?php
$User = User::create([
'name' => 'Huzzah'
)];
$UserKey = $User->getKey();
to ensure your still works when someone decides to changes the column name ;)