How to pass a variable($test) from store to index? because I would like to display a variable in my index.blade
public function index()
{
return view('users.index', [
'users' => User::all()
]);
}
public function store(Request $request)
{
$user = new User($request->all());
$user->save();
$test = "test";
return redirect('users');
}
To resolve your problem you may edit your code like below:
index function:
public function index($test=null)
{
return view('users.index', [
'users' => User::all(),
'test' => $test
]);
}
store function:
public function store(Request $request)
{
$user = new User($request->all());
$user->save();
$test = "test";
return redirect(route('users.index', compact('test')));
}
N.B: for storing your user I don't recommend to you mass assignment (new User($request->all())) when you create a new user especially if you have a password or token to store there.
Related
This is how I would make such a function
Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
You have two options:
Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.
Hey guys so I made a route:
Route::get('/dashboard/{user}', [DashboardController::class, 'show'])->name('dashboard.show');
My controller is
public function show($id)
{
return view('dashboard.profile')->with('name',User::where($id));
}
How do pass it into the view? so I get only data from the current user / userid
You can simplify it to this by using route model binding:
public function show(User $user)
{
return view('dashboard.profile', [ 'user' => $user ]);
}
You Can Do This:
public function show(User $user)
{
return view('dashboard.profile', [ 'user' => $user ]);
}
Or :
public function show($id)
{
$user = User::findOrFail($id);
return view('dashboard.profile', [ 'user' => $user ]);
}
Or :
public function show($id)
{
$user = User::where("id",$id)->first();
return view('dashboard.profile', [ 'user' => $user ]);
}
If You Need Authenticated user use :
auth()->user
In my first controller, I guess, I use the most basic way of creating a user password
EmployeeController
public function store(Request $request){
$user = User::create(array(
'username' => $request->username,
'password' => Hash::make($tempPassword = Str::random(8)))
);
$employee->user()->associate($user);
$employee->save();
}
Shen it comes to checking the password with Hash::check() in the second controller it always fails
ResetPasswordController
public function index(ResetPasswordRequest $request){
$request->validated();
$emp = Student::find($request->id);
if ($emp->user->checkCredentials($request->password)) { //always false
}
}
However, if update password in the same controller (just for testing) it works just fine
ResetPasswordController
public function index(ResetPasswordRequest $request){
$request->validated();
$emp = Student::find($request->id);
$emp->user->update(['password' => Hash::make('abc')]);
if ($emp->user->checkCredentials('abc')) { //...true
}
}
User
public function checkCredentials($password){
return (Hash::check($password, $this->password)) ? true : false;
}
I don't change the app key between creating and checking the user passwords. Any ideas where else should I look?
I currently have two tables namely storing users and clients. A client is related to a User in a one-to-one relationship.
I am currently storing and updating the models like so but it feels rather clunky...
public function store(Request $request)
{
$requestData = $request->all();
$user = new User();
$user->fill($requestData);
$user->save();
$client = new Client;
$client->fill($requestData);
$client->user()->associate($user);
$client->save();
return response()->json($client->toArray(), 201, ['id' => $client->id]);
}
public function update(Request $request, $id)
{
try {
$client = Client::findOrFail($id);
$user = User::findOrFail($client->fk_user);
} catch (ModelNotFoundException $e) {
return response()->json([
'error' => [
'message' => 'Client not found',
]
], 404);
}
$requestData = $request->all();
$user->fill($requestData);
$user->save();
$client->fill($requestData);
$client->user()->associate($user);
$client->save();
return response()->json($client->toArray(), 200);
}
Is there a way to refactor this to avoid having to work with both users and clients as separate models. Is there a way to perhaps fill a client and in turn fill the parent user model?
Just wondering, thanks!
I´ve made some refactoring inspiration for you. This is not necessarily the "right" way, but maybe you can pick up something you like.
Note! I haven't actually tested the code, its probably full of syntax errors. I just hacked it down to show some ideas. Some of the logic, like associating the user, I've imaginary placed in the client model. The error handling happens in app/Exceptions/Handler.php.
Hope you can have some use of it :)
private function saveUser($args, $user = null) {
$user = $user ?: new User();
$user->fill($args);
$user->save();
return $user;
}
private function saveClient($args, $client= null) {
$client = $client ?: new Client;
$client->fill($args);
$client->save();
return $client;
}
private function respondCreated($data = []) {
return $this->respond($data, 201, "created");
}
private function respond($data = [], $statusCode = 200, $message = "ok") {
$response = [
"message" => $message,
"data" => $data
];
return response()->json($response, $statusCode);
}
public function store(Request $request)
{
$user = $this->saveUser($request->all());
$client = $this->saveClient($request->all());
$client->saveUser($user);
return $this->respondCreated($client);
}
public function update(Request $request, $id)
{
$client = $this->saveClient($request->all(), $client::findOrFail($id));
$this->saveUser($request->all(), $client->fk_user);
return $this->respond($client);
}
I want to update a data in the database
i have controller
public function update(Identity $identity, Request $request)
{
$data = new Identity();
$data->date = $request['date'];
$data->code = $request['code'];
$data->name = $request['name'];
$request->user()->identity()->update($data);
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
Model Identity
public function user()
{
// Each data is owned by only one user
return $this->belongsTo('App\User');
}
Model User
public function identity()
{
// Each user will have a lot of data
return $this->hasMany('App\Identity');
}
And i found an error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::update() must be of the type array, object given.
You already have the Identity model with the route model binding. You can do one of the below.
public function update(Identity $identity, Request $request)
{
$identity->date = $request['date'];
$identity->code = $request['code'];
$identity->name = $request['name'];
$identity->save();
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
Or (Make sure you set the $fillable property in the model for this to work)
public function update(Identity $identity, Request $request)
{
$identity->update([
'date' => $request['date'],
'code' => $request['code'],
'name' => $request['name'],
]);
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
This line
$data = new Identity();
creates an object. Below that you are setting its properties. Instead, it looks like you can pass your properties directly into the function:
public function update(Identity $identity, Request $request)
{
$request->user()->identity()->update(array($request));
...
}
Of course you might also want to restrict your request to just what's needed:
public function update(Identity $identity, Request $request)
{
$params = array_intersect_key(array($request), array_flip(['date', 'code', 'name']))
$request->user()->identity()->update($params);
...
}