Laravel 7: Cannot update record in users table - php

I've searched but couldn't find a working solution. I simply cannot update a specific field (status) in users table. I've added two additional fields in Laravel's auth users original table.
Here is the migration code:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->integer('status')->default(0);
$table->foreign('role_id')->references('id')->on('roles');
});
}
I've also added fillable:
protected $fillable = ['name', 'email', 'password', 'role_id', 'status'];
Now the issue is I cannot update "status" field and the operation doesn't return any issue. I already have tried it with different approaches. Have a look at the code and guide me. TIA.
public function update(Request $request, $id)
{
$validatedData = $request->validate([]);
// APPROACH # 1
$user = User::find($id);
$user->status = $request->status;
$user->save();
// APPROACH # 2
$user = User::find($id);
$user->update([
'status' => $request->status,
]);
// APPROACH # 3
User::findOrFail($id)->update($request->all());
}
Form:
<form action="{{ url('/admin/user') }}/{{ $editRecord[0]->id }}" method="POST" enctype="multipart/form-data">
#method('PUT')
#csrf
<select id="status" name="status" class="form-control">
<option value="1" #if($editRecord[0]->status == 1) selected #endif>Active</option>
<option value="0" #if($editRecord[0]->status == 0) selected #endif>In-Active</option>
</select>
</form>
Finally the route:
Route::put('/admin/user/{id}', 'Admin\PortalController#update');

Then code is working fine may be you forget to redirect back with success message. you should try below -
if($user->save()){
return redirect()->back()->with('message', 'updated successfully');
} else {
return redirect()->back()->with('error', 'something went wrong');
}
Then in blade file -
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(session()->has('error'))
<div class="alert alert-danger">
{{ session()->get('error') }}
</div>
#endif

Related

Need help in creating a user in Laravel with roles

I followed a nice tutorial on how to create roles and how to use gates with Laravel.
I can seed users with roles and edit them, but I would like to be able to create a user and give him/her one or more roles and I don't know where to start (I'm not a pro, but I need to finish this app).
Here's all the code I can show you so far :
Users Controller :
public function edit(User $user, $id)
{
$user = User::findOrFail($id);
$roles = Role::all();
return view('admin.users.edit',compact('user', 'roles'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user, $id)
{
$user = User::findOrFail($id);
$user->roles()->sync($request->roles);
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect()->route('admin.utilisateurs.index');
}
Roles Table :
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Pivot Table :
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->BigInteger('role_id')->unsigned()->onDelete('cascade');
$table->BigInteger('user_id')->unsigned()->onDelete('cascade');
$table->timestamps();
});
}
Edit blade file with checkboxes :
<div class="block-content">
<div class="form-group">
#foreach ($roles as $role)
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="roles[]"
value="{{ $role->id }}" id="{{ $role->id }}"
#if ($user->roles->pluck('id')->contains($role->id)) checked #endif>
<label class="" for="{{ $role->id }}">{{ $role->name }}</label>
</div>
#endforeach
</div>
</div>
The thing is that I don't really know how to write my code on the Create Blade File.
Here's the create method on the controller (not sure if it's correct or not) :
public function store(Request $request, User $user)
{
$user = new User();
$user->roles()->sync($request->roles);
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect()->route('admin.utilisateurs.index')->with('success','Utilisateur ajouté');
}
Thanks for reading this long message!
Peace
on create blade it's almost as same as edit blade. you just need not to check for existing roles.
//rest of the form first like user name and email
<div class="block-content">
<div class="form-group">
#foreach ($roles as $role)
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="roles[]" value="{{ $role->id }}" id="{{ $role->id }}">
<label class="" for="{{ $role->id }}">{{ $role->name }}</label>
</div>
#endforeach
</div>
</div>
and then in controller instead of sync just use attach
public function store(Request $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('admin.utilisateurs.index')->with('success','Utilisateurajouté');
}
look i have removed model binding in store function. it's not necessary in here. and attached roles after saving the user. docs on attach and sync in here.

Laravel Problem with Blade syntax and normal html-tags

im trying to do a little project with laravel 7 and have a question about creating and updating user roles.
Code in AdminUsersController.php:
public function create()
{
$roles = \App\Role::pluck('name', 'id')->all();
return view('admin.users.create', compact('roles'));
}
public function edit($id)
{
$user = User::findOrFail($id);
$roles = Role::pluck('name', 'id')->all();
return view('admin.users.edit', compact('user', 'roles'));
}
public function update(UpdateUsersRequest $request, $id)
{
$user = \App\User::findOrFail($id);
$user->update($input);
Session::flash('message', 'User successfully updated.');
return redirect(route('admin.users.index'));
}
Now if im using this blade-syntax in the view form for create and updating this works:
<div class="row">
<div class="col-sm-6">
<div class="form-group">
{!! Form::label('role_id', 'Role:') !!}
{!! Form::select('role_id', array('' => 'Choose Options') + $roles, null, ['class' => 'form-control']) !!}
</div>
</div>
</div>
But how can i do this without blade syntax? Is there a posibilty to pass the same array in the select tag?
i tried to loop through the $roles but didnt work:
<div class="form-group">
<select>
#foreach($roles as $role)
<option value="{{$role->id}}">{{role->name}}</option>
#endforeach
</select>
</div>
i mean i have a solution but i would like to if there is another option without blade syntax..
hope you can help me thank u :)

Multi-step form in Laravel

I am trying to create a multi-step form for a user to fill after logging in. I created separate pages with forms that will be a part of the common form.
The data will be saved in the "users" table.
I am new to Laravel and I followed this: https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
In my FormController I have these methods:
public function index(Request $request)
{
$request->session()->forget('user');
$user = User::all();
return view('form.index',compact('user',$user));
}
public function updateStep1(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step1',compact('user', $user));
}
public function postupdateStep1(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/update-step2');
}
public function updateStep2(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step2',compact('user', $user));
}
public function postupdateStep2(Request $request)
{
$validatedData = $request->validate([
'address' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/store');
}
public function store(Request $request)
{
$user = User::where('id',auth()->user()->id)->first();
$user = $request->session()->get('user');
$user->save();
return redirect('/form');
}
And these are the Routes:
Route::get('/form', 'FormController#index');
Route::get('/form/update-step1', 'FormController#updateStep1');
Route::post('/form/update-step1', 'FormController#postupdateStep1');
Route::get('/form/update-step2', 'FormController#updateStep2');
Route::post('/form/update-step2', 'FormController#postupdateStep2');
Route::post('/form/store', 'FormController#store');
This is the first part of the form:
#extends('layouts.app')
#section('content')
<h1>update - Step 1</h1>
<form action="/form/update-step1" method="post">
#csrf
<div class="form-group">
<label for="name">First Name</label>
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="name">
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">Continue</button>
</form>
#endsection
I get an error when I try to submit, saying that the fields are required. So even if I do enter a name etc., it doesn't work. If I delete the validations, it seems like everything works but no data is added to the database.
Any suggestions?
You should use the input name is first_name because you have used first_name in the validation.
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="first_name">
OR
If want to change name value in the user table:
FormController
$validatedData = $request->validate([
'name' => 'required',
]);
first part of the form:
<input type="text" value="{{ old('name', $user->name ?? null) }}" class="form-control" name="name">

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Laravel "if else" check if exist in other table

I want to use this if else statement like this:
#foreach ($comments as $comment)
<tr>
<td>
#if (is_null($ourcar))
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our cars</button>
</form>
#else
<p>saved</p>
#endif
</td>
</tr>
#endforeach
This is my controller:
public function browse(Request $request, CommentFilters $filters)
{
$lot_id = Comment::where('lot_id')->get();
$ourcar = OurCar::where('lot_id', '=', $lot_id)->first();
$comments = Comment::filter($filters)->orderBy('lot_date', 'desc')->paginate(30)->appends($request->all());
return view('comments.browse', compact(
'comments',
'ourcar'
));
}
My database structure is:
comments table: id, lot_id,
ourcars table: id, lot_id
My models:
Comment:
public function OurCar()
{
return $this->hasMany(OurCar::class);
}
OurCars:
public function Comment()
{
return $this->belongsTo(Comment::class);
}
OurCars migration:
Schema::create('ourcars', function (Blueprint $table) {
$table->engine = 'MyISAM';
$table->increments('id');
$table->integer('lot_id')->unsigned();
and it same for comments
What im trying to do is check if the lot_id already exist in "ourcars" table. If exist than return that message that this car is already saved. If not, than echo form.
With my code i have this error:
SQLSTATE[HY000]: General error: 2031 (SQL: select * from ourcars
where lot_id = ? limit 1)
Can some one recommend me a better solution?
The reason you are getting this message is because the get method will return an array , in this case it will bring all the lines of table commentplus it need 1 more argument at least to function.
$lot_id = Comment::where('lot_id')->get(); //
Also change your models to this
public function OurCar()
{
return $this->hasMany('App\Comment');
}
And this
public function Comment()
{
return $this->belongsTo('App\OurCar');
}
Here an example on how can you do it based on your code.
Pass the lot_id on the request
public function browse(Request $request, CommentFilters $filters)
{
$ourcar = OurCar::where('lot_id',$request->lot_id)->first();
$comments = Comment::filter($filters)->orderBy('lot_date', 'desc')->paginate(30)->appends($request->all());
return view('comments.browse')->with('ourcar',$ourcar)->with('comments',$comments);
}
Here the view
#foreach ($comments as $comment)
<tr>
<td>
#if ($ourcar->lot_id != $comment->lot_id)
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our cars</button>
</form>
#else
<p>saved</p>
#endif
</td>
</tr>
#endforeach

Categories