Update single field in a Profile Update Form in Laravel 5 - laravel

I am trying to update a single field in my user profile form section in the Laravel app.
I can save fields correctly in DB but input values and placeholders are taking wrong values. In every hit Save, the values doesn' change, and they are taken from the last listed user profile details. In my case this is user#3. The problem is when I log in with the user's #1 credentials, value and placeholder are taken from user #3. When I log in with user #2, again from user #3. Only values of user#3 are correct and I can manipulate it with no issues for both fields.
When i update the profile fields with user#1 it saves the entered one filed, but because the 2nd filed inherits the user#3 input details it saves it in field 2 of user#1 which makes a wrong entry. I can't leave null in those fields by default. My mass assignment is guarded.
How can save/update just a single field in the blade template without affecting the other fields in the form?
My routes:
Route::get( '/profile', 'userController\\profileEdit#profileEdit')->name('profileEdit');
Route::post('/profile', 'userController\\profileEdit#update')->name('update');
My controller:
namespace App\Http\Controllers\userController;
use App\Model\Hause_users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class profileEdit extends Controller
{
function profileEdit (Request $request){
$user = Hause_users::all();
$name = $request->session()->get('name');
$request->session()->keep([request('username', 'email')]);
return view('frontview.layouts.profile',['user'=>$user])->with('username' , $name );
}
function update (Request $request){
$user = Hause_users::where('username', $request->session()->get('name'))->first();
$user->fill(['email' => request('Email')]) ;
$user->save();
$user->phone;
//dd($user->phone->phone);
if ($user->phone === null) {
$user->phone->phone->create(['phone' => request('tel')]);
}
else{
$user->phone->update(['phone' => request('tel')]);
}
return back()->withInput();
}
Blade file: `
#extends('frontview.layouts.userView')
#extends('frontview.layouts.default')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#section('title')
#endsection
#section('content')
#foreach($user as $v )
#endforeach
<h2 class="form-group col-md-6">Здравей, {{$username }} </h2>
<form class = "pb2" method="POST" name = 'profile' action='profile' >
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="email" class="form-control" name = "Email" id="inputEmail4"
value="{{$v['Email']}}"
placeholder="{{$v->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$v->phone['phone']}}"
placeholder="{{$v->phone['phone']}}"
id="example-tel-input" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity">Град</label><input type="text" class="form-control" id="inputCity">
<label for="inputCity">Квартал</label><input type="text" class="form-control" id="inputCity">
</div>
{{--<div class="col-md-6" >--}}
{{--<label for="image">Качи снимка</label>--}}
{{--<input type="file" name = "image">--}}
{{--<div>{{$errors->first('image') }}</div>--}}
{{--</div>--}}
</div>
{{--<div ><img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg"--}}
{{--class="rounded-circle z-depth-1-half avatar-pic" alt="example placeholder avatar">--}}
{{--</div>--}}
{{--<div class="d-flex justify-content-center">--}}
{{--<div class="btn btn-mdb-color btn-rounded float-left">--}}
{{--<span>Add photo</span>--}}
{{--<input type="file">--}}
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Запомни ме!
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Запази</button>
</form>
#endsection
#section('name')
{{ $username }}
#endsection
Output summary:
On img#1 are the correct entry details . This is other section not the Profile edit one. Currently loged user is U#1 but as you can see on image 2, values and placeholder of both fields are for the U#3. When i hit the blue button U#1 saves the untouched filed input of U#3. Same is when i log in with U#2.

Actually the answer here is quite simple. What i am doing wrong is that i am not passing the value of the currently logged user to the view correctly. On my profileEdit method i was using $user = Hause_users::all(); and then looping trough all id's into the view and then fetching every field. But because the view doesn know which user passes the data, the foreach always returns the last user id from the array with its input, no matter which user is currently logged in. Then the data was overridden with wrong inputs.
The solution is also simple.
Instead of $user = Hause_users::all();
i have used
$user = Hause_users::where('username', $request->session()->get('name'))->first();
and then into view i was objecting the $user variable without any loops like this:
<form class = "pb2" method="POST" name = 'profile' action='profile' >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{{--<input type="hidden" name="_method" value="PATCH">--}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="Email" class="form-control" name = "Email" id="inputEmail4"
value="{{$user->Email}}"
placeholder="{{$user->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$user->phone['phone']}}"
placeholder="{{$user->phone['phone']}}"
id="example-tel-input" >
Basically this is a detailed explanation to all that not using the built in Auth system of Laravel

Related

Laravel 7- Pass database value or a value stored in a variable, to Laravel Blade

I am trying to obtain value from database and pass it to blade. If there is no value in database, a random number is generated and passed from the controller. However, I am unable to fetch the value even if it exists. I am getting 1 for every value available in database
Here are my codes
Controller
public function new_user2(Request $request){
if(!Auth::check()){
$reference = $request->refno;
if((is_null($reference))){
$ref1 = mt_rand(10,1000);
$ref2 = mt_rand();
$reference = $ref1."-".$ref2;
} else{
$tuser = DB::table('temp_users')->where('referenceno',$reference)->first();
if(is_null($tuser)){
return redirect()->back()->with('error',"Invalid Reference No. Please enter a valid one");
}else{
// return view('multipage1',compact('tuser'));
return view('multipage1',compact('tuser'));
}
}
return view('multipage1')->with('ref',$reference);
}else{
Auth::login();
}
}
Blade
<div class="body1">
<div class="container container2">
<div class="row">
<div class="col-md-8 offset-md-2">
<h1 class="text-white text-center display-2">Step 1</h1>
<div class="login-form">
<form id="newuser2_step1" action="{{url('mpage2')}}" method="post" autocomplete="off">
#csrf
<div class="form-group">
<label for="RefNo">Reference Number: </label>
<input type="text" class="form-control" id="refno" name="refno" value="{{$tuser->referenceno or $ref}}" readonly><br>
</div>
<div class="form-group">
<!-- Alert Message -->
<div class="alert alert-danger " role="alert" id="alerts">
<strong id="emailtaken"></strong>
</div>
<label for="exampleInputEmail1">Email address</label>
<input type="text" class="form-control" id="email" name="email" placeholder="Enter email" value="{{$tuser->temp_email or ''}}">
<div class="error text-danger" ></div>
</div>
<button type="submit" class="btn btn2 btn-primary" id="mstep1">Get Started</button>
</form>
</div>
</div>
</div>
</div>
</div>
Database table
Data exists in referenceno and temp_email columns
Output in Browser
According to this article, the Laravel or operator that you used, is discontinued. So, use null coalesce operator instead.
value="{{$tuser->referenceno ?? $ref}}"
Similarly, replace the email value with similar coede
You have change this type of statements {{$tuser->referenceno or $ref}}
It is basically checking true/false that why you are getting 1.
Do something like this {{ isset($tuser->referenceno) ? $tuser->referenceno : $ref}}

cannot show data from model object

I want to change the data absent but an error appears 'Trying to get the property' id 'of non-object' I do not understand why even though I have done it before and it's fine. and my relationship table is in apache MySql so my model is blank.
I've tried to match my other edit method but nothing is wrong
this my edit()
public function edit($id)
{
$absensi = absensi::find($id);
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
return view('absensi.edit', ['absensi'=> $dataSiswa]);
}
and then this is my blade
<div class="card-header">
<h1>Edit Data Absensi </h1>
</div>
<div class="card-body">
<form action="/absensi/{{$absensi->id}}" method="POST" name="form1" >
{{ csrf_field() }}
<div class="form-group">
<label for="usr">Nama :</label>
<input type="text" value="{{$dataSiswa->nama}}">
</div>
<div class="form-group">
<label for="usr">Semester :</label>
<select name="semester" class="form-control" id="sel1">
<option value="genap"#if ($dataSiswa->semester=="ganjil") selected #endif>ganjil</option>
<option value="ganjil"#if ($dataSiswa->semester=="genap") selected #endif>genap</option>
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" name="kelas" value="{{$dataSiswa->kelas}}">
</div>
<div class="form-group">
<label for="comment">izin:</label>
<input type="number" class="form-control" name="izin" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Sakit :</label>
<input type="number" class="form-control" name="sakit" value="{{$dataSiswa->izin}}">
</div>
<div class="form-group">
<label for="comment">Tanpa Keterangan :</label>
<input type="number" class="form-control" name="tanpaKeterangan" value="{{$dataSiswa->izin}}">
</div>
<button type="submit" class="btn btn-primary" id="Submit" name="Submit">simpan perubahan</button>
</form>
</div>
</div>
</div>
change
$absensi = absensi::find($id);
to
$absensi = absensi::findOrFail($id);
i think the problem is that the model cannot find the record with that id
and if thats not the case then
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
to
$dataSiswa = DB::table('absensis')
->join('siswas', 'siswas.id', '=', 'absensis.idSiswa')
->select('absensis.*', 'siswas.nama')
->where([
['siswas.id', $absensi->idSiswa],
])->first();
if(!$dataSiswa) {
// throw new notfound exception here or return back
}
return view('absensi.edit', ['absensi'=> $dataSiswa]);
In other words you are trying to access a property of a null object because the queries you made are returning a null object, and on your blade you are tying to access a null object property
You should probably look into defining your relationships with eloquent instead as per the docs.
Once that's done you can use Eloquent to query your table like so:
$abensis = abensis::findOrFail($id);
$dataSiswa = $abensis->siswa;
return view('absensi.edit', ['absensi'=> $dataSiswa]);

How to autofill Edit form with old Information from two different tables?

I have this form "Edit tache". Editing one "tache" affects two tables user and technicien, when i choose to edit tache the edit form is autofilled with information from the technicien table but the fields related to the table user are not autofilled. How could i autofill the form with information from the two tables? Thank you.
controller
public function edit($id)
{
$technicien=technicien::find($id);
$user = user::orderBy('id', 'asc')->get();
return view('technicien.edit',['moyenne_avis'=>$technicien],['actif'=>$technicien],['user_id'=>$technicien])->with('users', $user );
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
return redirect('technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Tache</h1>
<form action="{{ route('technicien.update', $actif->id , $moyenne_avis->id ) }}" method="post">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="">Nom</label>
<input id="nom" type="text" class="form-control" name="nom" value="{{ old('nom') ? old('nom') : $actif->nom }}" required autofocus>
</div>
<div class="form-group">
<label for="">Prenom</label>
<input id="nom" type="text" class="form-control" name="nom" value="{{ old('nom') ? old('nom') : $actif->nom }}" required autofocus>
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name ="moyenne_avis" class="form-control"value ="{{$moyenne_avis->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name ="actif" class="form-control"value ="{{$actif->actif}}" >
</div>
<div class="form-group">
<input type="submit" value = "enregistrer" class="form-control btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
route
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::put('/technicien/{id}', 'TechnicienController#update')-
>name('technicien.update');
$user = user::find($id);
if they are retrieved using one id on the controller, else please tell the relation between them.
and in your view, i don't see a reason to check old since its not updated yet! use
{{$user->nom)}}

Laravel :error when updating the database after editing data

I have two tables table "technician" and table "user" with a connection one to one and I have a form through which I edit the technician information. When I save the changes I get an error and the update doesn't work.Here is my form my code and a screenshot of the error Thank you in advance.
route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')-
>name('technicien.update');
edit.php
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $moyenne_avis->id , $actif->id , $user->nom , $user->prenom ,$user->email ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$moyenne_avis->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$moyenne_avis->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
controller1.php
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['moyenne_avis'=>$technicien],
['actif'=>$technicien],['user_id'=>$technicien])->with('user',$user);
}
controller2.php
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
return redirect('technicien');
}
You are passing too many param and in your route you only take one param!
I think you only need one param in your view which is technician ID and which will find the record in your controller query!
You can try follow code with removing unusable params from form:
<form action="{{ route('technicien.update', $moyenne_avis->id ) }}" method="POST">
And your route looks like:
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::post('/technicien/{id}', 'TechnicienController#update')->name('technicien.update');
Hope this helps you!

how can I add columns for App\User and store the data to in users table in laravel 5.1?

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->integer('mobile');
$table->integer('status')->default(0);
$table->integer('team_id');
$table->string('created_by');
$table->string('updated_by');
$table->rememberToken();
$table->timestamps();
});
}
The above method creates user table with few additional columns.I then added fillable content in my User model as:
protected $fillable = ['name', 'email', 'password','mobile','team_id'];
My create.blade.php view is:
#extends('master')
#section('title','Creating.. User')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/register') }}">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" value="{{ old('name') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Mobile</label>
<div class="col-md-6">
<input type="number" class="form-control" name="mobile">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Team</label>
<div class="col-md-6">
<input type="number" class="form-control" name="team_id">
</div>
</div>
<!--
<div class="form-group">
<label class="col-md-4 control-label">Role</label>
<div class="col-md-6">
<input type="text" class="form-control" name="role">
</div>
</div>
-->
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Then,I filled all the fields in the form and when I submit I get username,password,email.I am not getting other fields "mobile number" and "team_id".(Team Id is what I enter in the form)
fields- username,password is saved but mobile and team aren't
I can create this with controller,defining my own routes and do it manually.But,I don't want to do that.I want to use the same User model that comes default for authentication in laravel 5.1.
What I need is ::: Is there any way to create and store these columns in the database with the users table that exists in migration by default.
I changed the mobile from integer to string and tried but couldn't get the values into the database.I wan't the values that I enter to get stored in my users table. Can anyone help me to solve my problem.
I am using bestmomo/scaffold package.
public function up(){//} is like schema builder, it will only add columns to your table with default values if specified but not actual data.
If you want to add data to your database./auth/register route maps to AuthController in App\Http\Controllers\Auth
You have to overrride the method postRegister in AuthController
Here is how it might look like
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\User;
use Illuminate\Http\Request;
use Hash;
class AuthController extends Controller {
public function postRegister(Request $request){
$user = new User();
$user->name = ucwords($request->input('name'));
$user->email = strtolower($request->input('email'));
$user->phone = $request->input('phone');
$user->address = $request->input('address');
$user->password = Hash::make($request->input('password'));
$user->save();
return redirect('/donner');
}
}
and in your routes.php
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);

Resources