I have trouble with Request validation in Laravel, when request data pass validation everything is ok but then data is invalid server response with 404
UserRequest
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'sometimes|required|unique:users,Name|min:5|max:30'
];
}
UserController
public function update(UserRequest $request, $id)
{
$token = JWTAuth::getToken();
$tokenData = JWTAuth::getPayload($token)->toArray();
if ($request->name != null) {
if (User::where('id', $tokenData['idUser'])->update(['Name' => $request->name])) {
$status = true;
} else {
$status = false;
}
}
return response()->json(['status' => $status]);
}
Try with this
public function update(UserRequest $request, $id)
{
$token = JWTAuth::getToken();
$tokenData = JWTAuth::getPayload($token)->toArray();
$validated = $request->validated();
if ($validated) {
if (User::where('id', $tokenData['idUser'])->update(['Name' => $request->name])) {
$status = true;
} else {
$status = false;
}
return response()->json(['status' => $status]);
}
else {
return redirect()->back()->withErrors($validated);
}
}
Hope this helps :)
Related
How to get id from url parameter to url function codeigniter4
public function show($id = null)
{
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
You can pass the value using post request.
and in controller function you can read like this
public function show( ) {
$id = $this->request->getVar('id');
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
I wonder how I can redirect a user after login?
Lets say that I am on the page "www.mysite.com/users/2"
Then I try to edit a blog post without being logged in and get sent to the login page, efter login I wish to return to "www.mysite.com/users/2"
I have tried this so far:
if (Auth::attempt($credentials,$remember)) {
return redirect()->back();
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
But return redirect()->back(); will only redirect me to "www.mysite.com/"
Update
I got it working using this:
public function showLoginForm()
{
$previous_url = Session::get('_previous.url');
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$ref = rtrim($ref, '/');
if ($previous_url != url('login')) {
Session::put('referrer', $ref);
if ($previous_url == $ref) {
Session::put('url.intended', $ref);
}
}
return view('auth.login');
}
public function loginUser(ApiAuthUserPassRequest $request)
{
if ($request->has('rememberme')) {
$remember = $request->input('rememberme');
} else {
$remember = false;
}
$credentials = ['email' => $request->input('email'), 'password' => $request->input('password')];
if (Auth::attempt($credentials,$remember)) {
if (Session::has('referrer')) {
return redirect()->intended(Session::pull('referrer'));
} else {
return redirect('/account');
}
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
}
Laravel 5.1 have trait Illuminate/Foundation/Validation/ValidatesRequests.php with method
protected function getRedirectUrl()
{
return app(UrlGenerator::class)->previous();
}
where UrlGenerator is Illuminate/Routing/UrlGenerator.php. You can try use previous() method.
On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}
i have a controller function that needs to be redirected to a route with a different function to avoid redundancy of codes. is it possible to put a redirect to a different function?
Here is the code:
public function index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
return // this is where i should redirect to page with function index()
}
Name the index route in routes definition like this
Route::get('home', ['uses' => 'YourController#index', 'as' => 'home']);
Then use redirect method to redirect to this route:
return redirect()->route('home');
For more info on redirects use official docs
http://laravel.com/docs/5.1/responses#redirects
I don't think is a perfect, but someone prefer this way:
private function _index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function index()
{
$this->_index();
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
$this->_index();
}
private function for repeated code.
I'm busy with a tutorial and I ended up getting an error that says
This webpage has a redirect loop
I know that the problem is here in my routes.php
Route::group(["before" => "guest"], function(){
$resources = Resource::where("secure", false)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
Route::group(["before" => "auth"], function(){
$resources = Resource::where("secure", true)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
UserController
class UserController extends \BaseController {
public function login()
{
if($this->isPostRequest())
{
$validator = $this->getLoginValidator();
if($validator->passes())
{
$credentials = $this->getLoginCredentials();
if(Auth::attempt($credentials)){
return Redirect::route("user/profile");
}
return Redirect::back()->withErrors([
"password" => ["Credentials invalid."]
]);
}else{
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return View::make("user/login");
}
protected function isPostRequest()
{
return Input::server("REQUEST_METHOD") == "POST";
}
protected function getLoginValidator()
{
return Validator::make(Input::all(), [
"username" => "required",
"password" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"username" => Input::get("username"),
"password" => Input::get("password")
];
}
public function profile()
{
return View::make("user/profile");
}
public function request()
{
if($this->isPostRequest()){
$response = $this->getPasswordRemindResponse();
if($this->isInvalidUser($response)){
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return Redirect::back()
->with("status", Lang::get($response));
}
return View::make("user/request");
}
protected function getPasswordRemindResponse()
{
return Password::remind(Input::only("email"));
}
protected function isInvalidUser($response)
{
return $response === Password::INVALID_USER;
}
public function reset($token)
{
if($this->isPostRequest()){
$credentials = Input::only(
"email",
"password",
"password_confirmation"
) + compact("token");
$response = $this->resetPassword($credentials);
if($response === Password::PASSWORD_RESET){
return Redirect::route("user/profile");
}
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return View::make("user/reset", compact("token"));
}
protected function resetPassword($credentials)
{
return Password::reset($credentials, function($user, $pass){
$user->password = Hash::make($pass);
$user->save();
});
}
public function logout()
{
Auth::logout();
return Redirect::route("user/login");
}
}
GroupController
class GroupController extends \BaseController {
public function indexAction()
{
return View::make("group/index", [
"groups" => Group::all()
]);
}
public function addAction()
{
$form = new GroupForm();
if($form->isPosted()){
if($form->isValidForAdd()){
Group::create([
"name" => Input::get("name")
]);
return Redirect::route("group/index");
}
return Redirect::route("group/add")->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors()
]);
}
return View::make("group/add", [
"form" => $form
]);
}
public function editAction()
{
$form = new GroupForm();
$group = Group::findOrFail(Input::get("id"));
$url = URL::full();
if($form->isPosted()){
if($form->isValidForEdit()){
$group->name = Input::get("name");
$group->save();
$group->users()->sync(Input::get("user_id", []));
$group->resources()->sync(Input::get("resource_id", []));
return Redirect::route("group/index");
}
return Redirect::to($url)->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors(),
"url" => $url
]);
}
return View::make("group/edit", [
"form" => $form,
"group" => $group,
"users" => User::all(),
"resources" => Resource::where("secure", true)->get()
]);
}
public function deleteAction()
{
$form = new GroupForm();
if($form->isValidForDelete()){
$group = Group::findOrFail(Input::get("id"));
$group->delete();
}
return Redirect::route("group/index");
}
}
but I'm not sure how to go about fixing it especially since I was following a tutorial.