Update User (Laravel 4) - php

I am new in laravel and I am trying to update users but I am stuck here. When I press the update button it does not do anything....
//HomeController.php
public function getUpdate($username) {
$user = array();
$users = User::where("username", "=", $username)->get();
foreach ($users as $key => $value) {
if (isset($value->username)) {
$user['username'] = $value->username;
$user['email'] = $value->email;
$user['password'] = $value->password;
}
}
$username = (object) $user;
return View::make('home.update', array('username' => $username));
}
public function postUpdate($username) {
$input = Input::all();
$rules = array('username' => 'required|unique:users',
'email' => 'required|unique:users|email',
'password' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->fails()) {
Redirect::to('home.update')
->withErrors($v)
->withInput(Input::except('password'));
} else {
$user = User::find($username);
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->save();
return Redirect::to('home.index')
->with('message', 'Successfully updated!');
}
}
//view
#extends('master')
#section('content')
<div class="span12 well" style="opacity: 0.9">
<h4>Update personal details:</h4>
{{ Form::open(array('url' => 'update/'.Auth::user()->username.'/update')) }}
#if($errors->any())
<div class="alert alert-error">
×
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</div>
#endif
<div class="form-group">
{{ Form::label('username', 'Username:') }}
{{ Form::text('username',$username->username, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'E-mail:') }}
{{ Form::text('email', $username->email, array('class' => 'form-control')) }}
</div>
<p>{{ Form::submit('Update', array('class' => 'btn btn-success'))}}</p>
{{ Form::close() }}
</div>
#stop
//routes
Route::get('update/{username}', 'HomeController#getUpdate');
Route::post('update/{username}/update', 'HomeController#postUpdate');

Try this:
Change this:
{{ Form::open(array('url' => 'update/'.Auth::user()->username.'/update')) }}
Into:
{{ Form::open(array('url' => 'update/'.Auth::user()->id.'/update')) }}
Your route must be:
Route::post('update/{id}/update', 'HomeController#postUpdate');
And your controller must be:
public function postUpdate($id) { //I change this to id based on the url of your route
$input = Input::all();
$rules = array('username' => 'required|unique:users',
'email' => 'required|unique:users|email',
'password' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->fails()) {
Redirect::to('home.update')
->withErrors($v)
->withInput(Input::except('password'));
} else {
$user = User::find($id); //User::find() only finds ID
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->save();
return Redirect::to('home.index')
->with('message', 'Successfully updated!');
}
}

Related

Field 'user_id' is empty

Today I have made a comments system, but isn't completed.In my database I have all fields filled by dates, but user_id isn't.How can I be able to save in column user_id, the id of authenticated user?Here is my code.
CommentsController:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'username' => 'required|max:255',
'mail' => 'required|mail|max:255',
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = $request->username;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
My view
<div class="row">
<div id="comment-form">
{{ Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST']) }}
<div class="row">
<div class="col-md-6">
{{ Form::label('username', "Username:") }}
{{ Form::text('username', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('email', "Email:") }}
{{ Form::text('email', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('comment', "Comment:") }}
{{ Form::text('comment', null, ['class' => 'form-control']) }}
</div>
{{ Form::submit('Add Comment', ['class' => 'btn btn-success btn-xs']) }}
</div>
{{ Form::close() }}
</div>
My route
Route::post('comments/{post_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
I tried to put Auth::user()->id inside my form, but I failed...
For you get the authenticated user you should only use the Auth facade. I show how to use it below.
use Illuminate\Support\Facades\Auth;
$user = Auth::user(); // Get the currently authenticated user...
$user_id = Auth::id(); // Get the currently authenticated user's ID...
Therefore, to save a user associated in a comment you have two options:
$user_id = Auth::id();
$comment->user_id = $user;
$comment->save();
Or
$user = Auth::user();
$comment->user = $user;
$comment->save();
If you have more questions about Laravel authentication take a look at https://laravel.com/docs/5.8/authentication#retrieving-the-authenticated-user.

updating of records in laravel 4.2

Hello im new in laravel 4.2 and i m making an application in the controllers, i made my own function called c_updateSystemUser($id) and here is the code
public function c_updateSystemUser($id)
{
//
session_start();
$getsCapt = $_SESSION["captcha"];
$rules = array(
'username' => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/|exists:dbo_systemusers,SystemUserName,$id',
'description' => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/',
'usertype' => 'required|numeric',
'capt' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the inputs given by the user
if ($validator->fails())
{
return Redirect::to('viewsu/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store the values into the database
$su = SystUser::find($id);
$su->SystemUserTypeID = Input::get('usertype');
$su->SystemUserName = Input::get('username');
$su->SystemUserDescription = Input::get('description');
$su->timestamps = false;
$su->save();
Session::flash('message', 'Successfully created system user!');
return Redirect::to('viewsu');
}
}
}
i wanted this function to be called when the user clicked the update button on my view file but when the button is clicked, it is redirecting to some other page (my create user page) i don't know why
here is the code of my form in my blade
{{ Form::model($su, array('route' =>array('csu.update',$su->SystemUserID),'method'=>'PUT'))}}
<div class="form-group">
{{ Form::label('usertype', 'User Type') }}
{{ Form::select('usertype', [null=>'Please Select user type'] + $sTyp , array('class'=>'form-control'))}}
{{ Form::label('current' , 'Current Type: (unedited) '.$su->SystemType , array('class' => 'label label-primary')) }}
</div>
<div class="form-group">
{{ Form::label('username', 'Username') }}
{{ Form::text('username', $su->SystemUserName, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', $su->SystemUserDescription, array('class' => 'form-control','rows' => '3')) }}
</div>
<div class="form-group">
{{ Form::label('captcha', 'CAPTCHA image: ') }}
</br>
{{ HTML::image('http://localhost:8080/laravel3/app/captcha.php', 'alt' , array( 'width' => 200, 'height' => 35 )) }} </br></br>
{{ Form::text('capt', Input::old('capt'), array('class' => 'form-control','placeholder' => 'enter generated captcha')) }}
</div>
{{ Form::submit('Edit System User', array('class' => 'btn btn-primary')) }}
{{ Form::close()}}
i don't know how to make the form call the function public function c_updateSystemUser($id) in my controller
my controller file is called systemUsers.php
any ideas? any help would be appreciated
If your view name is update and its in views->csu folder you can do it like following
{{ Form::model($su, array('route' =>array('csu.update.c_updateSystemUser',$su->SystemUserID),'method'=>'PUT'))}}
#yourentry
{{Form::close()}}
Your route should be like following:
Route::resource('csu','systemUsers');
In systemUsers.php add c_updateSystemUser($id){} method.

Laravel - the same validator works in one controller method but doesn't work in another

I have two simmilar forms, one for adding news to site, another to edit news:
{{ Form::open(array('action' => 'MyController#verifyAdminAddNews', 'files' => true)) }}
{{ Form::text('title', Form::old('title'), ['required' => 'required']) }}<br><br>
{{ Form::textarea('subtitle', Form::old('subtitle'), ['required' => 'required', 'style' => 'height:60px;']) }} <br><br>
{{ Form::textarea('text', Form::old('text'), ['required' => 'required']) }} <br><br>
{{ Form::file('image', '') }}
#if(isset($errormessage))
<div class="error-message"> {{ $errormessage }} </div>
#endif
{{ Form::submit('Pridať novinku', ['class' => 'form-control']) }}
{{ Form::close() }}
and:
{{ Form::open(array('action' => 'MyController#verifyAdminEditNews', 'class'=>'bg-grey width')) }}
{{ Form::text('title',$item->title, ['required' => 'required']) }}<br><br>
{{ Form::textarea('subtitle', $item->subtitle, ['required' => 'required', 'style' => 'height:60px;']) }}
{{ Form::textarea('text', $item->text, ['required' => 'required']) }} <br><br>
{{ Form::file('image', '') }}
#if(isset($errormessage))
<div class="error-message"> {{ $errormessage }}</div>
#endif
{{ Form::submit('Upraviť novinku', ['class' => 'form-control']) }}
{{ Form::close() }}
and in Controller are two methods for adding and editting news:
public function verifyAdminAddNews(){
if (is_object(DB::table('news')->orderBy('id', 'DESC')->first())) {
$newid = DB::table('news')->orderBy('id', 'DESC')->first()->id + 1; }
else { $newid = 0; }
// validate if file is image
$input = array('image' => Input::file('image'));
$rules = array('image' => 'image');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
Input::flash();
return View::make('adminnadd', ['errormessage' => 'Chyba! Vybratý súbor nie je obrázok.'] );
} else {
if (Input::file('image')==null) {
DB::insert('INSERT INTO news (id, title, subtitle, text, imageurl) VALUES (?, ?, ?, ?, ?)',
array($newid, Input::get('title'), Input::get('subtitle'), Input::get('text'), 'none'));
} else {
$destination = 'uploadedimages';
$filename = 'image'.$newid;
Input::file('image')->move($destination, $filename);
DB::insert('INSERT INTO news (id, title, subtitle, text, imageurl) VALUES (?, ?, ?, ?, ?)',
array($newid, Input::get('title'), Input::get('subtitle'), Input::get('text'), $filename));
}
return View::make('adminnall',['items'=>DB::table('news')->get()]);
}
}
public function verifyAdminEditNews() {
$id = Session::get('editnewsid');
// validate if file is image
$input = array('image' => Input::file('image'));
$rules = array('image' => 'image');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
Input::flash();
return View::make('adminnedit', ['errormessage' => 'Chyba! Vybratý súbor nie je obrázok.'] );
} else {
if (Input::file('image')==null) {
DB::table('news')->where('id', $id)->update(array('title' => Input::get('title'), 'subtitle' => Input::get('subtitle'), 'text'=>Input::get('text')));
} else {
$destination = 'uploadedimages';
$filename = 'image'.$id;
Input::file('image')->move($destination, $filename);
DB::table('news')->where('id', $id)->update(array('title' => Input::get('title'), 'subtitle' => Input::get('subtitle'), 'text'=>Input::get('text'), 'imageurl' => $filename ));
}
return View::make('adminnall',['items'=>DB::table('news')->get()]);
}
}
These methods have exactly the same Validator for validating if selected file is image. In verifyAdminAddNews it works right, returning error message back to view with form, when file is not image. But in verifyAdminEditNews validator will NOT fails when file is not image and will not return error message. How is this possible?
Oh, I forgot to add 'files' => 'true' to second form.

Laravel Authentication system- Tables do not match

I get an error that I am trying to understand: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' (SQL: select * from users where username = hi#hi.hi limit 1) when trying to login
My 'users' table:
id email password name admin created_at updated_at
1 go#go.go $2y$10$1R/21A3C32nwkjtEgDFcyuMc2D4AtgeFnTh1ygLEcQl... go 1 2014-11-01 21:04:33 2014-11-01 21:04:33
2 hi#hi.hi $2y$10$Akb9BoLWrOcQT0KFee7vvujtrzkbeRQnUDcuCXepeAd... hi 0 2014-11-02 16:15:47 2014-11-02 16:15:47
My form in views (displays correctly)
#extends('login_c')
#section('loginform')
<?= '<span style="color:red">' .
Session::get('login_error') . '</span>' ?>
{{ Form::open() }}
{{ Form::label('email', 'Email address: ') }}
{{ Form::text('email', Input::old('email')) }}
<br>
{{ Form::label('password', 'Password: ') }}
{{ Form::password('password') }}
<br>
{{ Form::submit('Login!') }}
{{ Form::close() }}
#stop
The problem is that I specified my password before in the registration and I do not understand why I either get "Could not login" or the SQL injection error.
oute::get('registration', function()
{
return View::make('registration');
});
Route::post('registration', array('before' => 'csrf',
function()
{
$rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|same:password_confirm',
'name' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
return Redirect::to('registration')->withErrors
($validation)->withInput();
}
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->name = Input::get('name');
$user->admin = Input::get('admin') ? 1 : 0;
if ($user->save())
{
Auth::loginUsingId($user->id);
return Redirect::to('profile');
}
return Redirect::to('registration')->withInput();
}));
Route::get('profile', function()
{
if (Auth::check())
{
return 'Welcome! You have been authorized!';
}
else
{
return 'Please Login';
}
});
Route::get('login', function()
{
return View::make('login');
});
Route::post('login', function()
{
$user = array(
'name' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($user))
{
return Redirect::to('profile');
}
return Redirect::to('login')->with('login_error',
'Could not log in.');
});
Route::get('secured', array('before' => 'auth', function()
{
return 'This is a secured page!';
}));
My register form: (Sorry, I am not posting my full view, as it is not relevant, I am sure that the error is in the form and/or usermodel.
{{ Form::open() }}
{{ Form::label('email', 'Email address: ') }}
{{ Form::text('email', Input::old('email')) }}
<br>
{{ Form::label('password', 'Password: ') }}
{{ Form::password('password') }}
<br>
{{ Form::label('password_confirm',
'Retype Password: ') }}
{{ Form::password('password_confirm') }}
<br>
{{ Form::label('name', 'Name: ') }}
{{ Form::text('name', Input::old('name')) }}
<br>
{{ Form::label('admin', 'Admin?: ') }}
{{ Form::checkbox('admin','true',
Input::old('admin')) }}
<br>
{{ Form::submit('Register!') }}
{{ Form::close() }}
#stop
How should I change my user model? Why does it save the wrong password?
Try to change
$user = array(
'name' => Input::get('email'),
'password' => Input::get('password')
);
to
$user = array(
'email' => Input::get('email'), // You're using email to log in users, not name in your form
'password' => Input::get('password')
);

Can't upload photo in Laravel 4

I'm trying to add some products to my database and I have to upload photo of this product. I've made a controller and view but when I click Create I don't have any errors but I don't have photo too. I want to upload only jpg,jpeg,gif,png files how can I do it? Here is my code:
Controller:
public function postAddProduct(){
$destinationPath = '';
$filename = '';
$newId = Product::max('id')+1;
$validator = Validator::make(Input::all(), array(
'name' => 'required',
'description' => 'required',
'partner_link' => 'required',
'image' => 'required'
));
if (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path().'/uploads/products/';
$filename = $newId.'.'.$file->getClientOriginalExtension();
$uploadSuccess = $file->move($destinationPath, $filename);
}
if($validator->passes()){
$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->category_id = Input::get('category');
$product->partner_link = Input::get('partner_link');
$product->photo = $filename;
$product->save();
return Redirect::back();
}else{
return Redirect::back()->withErrors($validator)->withInput();
}
}
View:
{{ Form::open(array('url'=>'user/admin/products/addd', 'class'=>'col-md-4', 'style'=> 'float:none; margin: 0 auto', 'id'=>'register-form')) }}
<h2 class="form-signin-heading">Add Product</h2>
{{ Form::text('name', null, array('class'=>'form-control', 'placeholder'=>'Name')) }}
{{ Form::text('description', null, array('class'=>'form-control', 'placeholder'=>'Description')) }}
{{ Form::text('partner_link', null, array('class'=>'form-control', 'placeholder'=>'Partner link')) }}
{{Form::label('category', 'Category: ', array('class' => 'field-name'))}}
<select name="category">
<?php $i = 0; ?>
#foreach($categories as $category)
<optgroup label="{{$category['name']}}">
#foreach($category['subcategories'] as $sub)
<option value="{{$sub->id}}">{{$sub->name}}</option>
#endforeach
</optgroup>
#endforeach
</select>
<div class="clearfix"></div>
{{Form::file('image', array('style' => 'margin-bottom: 10px'))}}
{{ Form::submit('Save', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
You form should have option 'files' set to 'true':
{{ Form::open(array('url' => 'foo/bar', 'files' => true)) }}

Categories