Laravel 5 Multiple form validation rules - laravel-5

So i have three forms on one page. One is to change user's picture, another one is to update personal informations, and the last form is to set a new password.
My issue here is that i'm getting validation errors on the password and password confirmation fields even though i'm trying to update some information (second form).
I have created two requests:
UserEditRequest:
class UserEditRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required'
];
}
}
UserUpdatePasswordRequest:
class UserUpdatePasswordRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'password' => 'required|confirmed|min:6',
'password_confirmation' => 'required|min:6',
];
}
}
within UserController updatePassword:
public function updatePassword(UserUpdatePasswordRequest $request, $id)
{
$user = User::findOrFail($id);
$user->password = bcrypt($request->get('password'));
$user->save();
return redirect()->route('user.edit',$id)->with('success','Password changed.');
}
postEdit where I handle the personal details and avatar changes:
public function postEdit(UserEditRequest $request, $id)
{
dd($request->all());
$user = User::findOrFail($id);
if($request->get('avatar'))
{
$destinationPath = public_path() . '/avatars/' . $user->id . '/';
$fileName = $user->id . '.' . $request->file('avatar')->getClientOriginalExtension();
$request->file('avatar')->move($destinationPath, $fileName);
$user->avatar = 'avatars/' . $user->id . '/' . $fileName;
$user->save();
return redirect()->route('user.edit',$id)->with('success','User avatar modified.');
}
$user->fill($request->input())->save();
return redirect()->route('user.edit',$id)->with('success','User details modified.');
}
quicky my routes:
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#getEdit']);
Route::post('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#postEdit']);
Route::post('profile/{userid}', ['as' => 'updatepassword', 'uses' => 'UserController#updatePassword']);
});
});

Try to differentiate your routes for the postEdit and the updatePassword controller actions
Route::post('profile/{userid}', ['as'=>'edit', 'uses'=>'UserController#postEdit']);
Route::post('profile/password/{userid}', ['as'=>updatepassword', 'uses'=>'UserController#updatePassword']);
Using the same route for two different controller actions won't work. What I mean is how do you expect the router to determine which controller action to invoke when the form action='/profile/id' method='post' ? Hence you need to differentiate the routes.
Hope you got it.

Related

User Redirection based on Roles | Laravel

I want to redirect user to other view based on their roles.
for admin i want to redirect it to /home view and for normal user redirect it to emDashboard view. can anyone help me with this?
Thank you guys.
this is my Login Controller
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except([
'logout',
]);
}
public function login()
{
return view('auth.login');
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
$dt = Carbon::now();
$todayDate = $dt->toDayDateTimeString();
$activityLog = [
'name' => $email,
'email' => $email,
'description' => 'has log in',
'date_time' => $todayDate,
];
if (Auth::attempt(['email'=>$email,'password'=>$password,'status'=>'Active'])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}elseif (Auth::attempt(['email'=>$email,'password'=>$password,'status'=> null])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}else{
Toastr::error('fail, Wrong Username or Password','Error');
return redirect('login');
}
}
Route for Login and Home Dashboard
Route::controller(LoginController::class)->group(function (){
Route::get('/login', 'login')->name('login');
Route::post('/login', 'Authenticate');
Route::get('/logout', 'logout')->name('logout');
Route::controller(HomeController::class)->group(function () {
Route::get('/home', 'index')->name('home');
Route::get('em/dashboard', 'emDashboard')->name('em/dashboard');
this is the users Model
protected $table = 'users';
protected $fillable = [
'name',
'rec_id',
'email',
'join_date',
'phone_number',
'status',
'role_name',
'avatar',
'password',
];
Add a if check before return redirect()->intended('home'); in your authenticate method... something like this
if(Auth()->user()->role_name == "admin"){
return redirect()->intended('home');
} else {
return redirect()->intended('em/dashboard');
}

Laravel 9: Auth::user() / auth()->user() null after successfull login

I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.

api route laravel always return error 400

I have route api.php like so
Route::group(['middleware' => ['jwt.verify']], function() {
Route::get('logout', [ApiController::class, 'logout']);
Route::get('pengguna', [ApiController::class, 'getAuthenticatedUser']);
Route::get('get_kabupaten/{provid}', [KabupatenController::class, 'get_kabupaten']);
Route::get('get_kecamatan/{kabid}', [KecamatanController::class, 'get_kecamatan']);
Route::get('get_kelurahan/{kecid}', [DesaController::class, 'get_kelurahan']);
Route::get('get_bencana', [JenisbencanaController::class, 'get_bencana']);
Route::get('saport', [ReportController::class, 'get_laporan']);
Route::post('saport/create', [ReportController::class, 'store']);
Route::get('saport/{id}', [ReportController::class, 'show']);
// Route::get('laporan', [LaporanController::class, 'get_laporan']);
// Route::post('laporan/create', [LaporanController::class, 'store']);
// Route::get('laporan/{id}', [LaporanController::class, 'show']);
// Route::put('update/{product}', [LaporanController::class, 'update']);
// Route::delete('delete/{product}', [LaporanController::class, 'destroy']);
});
all everything else work except
Route::get('pengguna', [ApiController::class, 'getAuthenticatedUser']);
Route::get('saport', [ReportController::class, 'get_laporan']);
Route::post('saport/create', [ReportController::class, 'store']);
Route::get('saport/{id}', [ReportController::class, 'show']);
and this my reportcontroller
<?php
namespace App\Http\Controllers;
use App\Models\Laporan;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Validator;
use Auth;
class ReportController extends Controller
{
public function get_laporan()
{
$laporan=Laporan::where('user_id', Auth::id())->get();;
return response()->json(compact('laporan'));
}
public function store(Request $request)
{
$data = $request->only( 'desa_id','bencana_id','koordinat','korban_kk','korban_orang','sebab_bencana');
$validator = Validator::make($data, [
'desa_id' => 'required',
'bencana_id' => 'required',
'koordinat' => 'required',
'korban_kk' => 'required',
'korban_orang' => 'required',
'sebab_bencana' => 'required',
]);
//Send failed response if request is not valid
if ($validator->fails()) {
return response()->json(['error' => $validator->messages()], 200);
}
$laporan = new Laporan;
$laporan->bencana_id = $request->bencana_id;
$laporan->desa_id= $request->desa_id;
$laporan->koordinat= $request->koordinat;
$laporan->user_id= Auth::id();
$laporan->korban_kk= $request->korban_kk;
$laporan->korban_orang= $request->korban_orang;
$laporan->sebab_bencana= $request->sebab_bencana;
$laporan->bantuan_diperlukan= $request->bantuan_diperlukan;
$laporan->respon_instansi= $request->respon_instansi;
$laporan->lokasi_pengungsian= $request->lokasi_pengungsian;
$laporan->pengungsi_kk= $request->pengungsi_kk;
$laporan->pengungsi_orang= $request->pengungsi_orang;
$laporan->permintaan_bantuan= $request->permintaan_bantuan;
$laporan->save();
return response()->json([
'success' => true,
'message' => 'laporan telah di input',
'data' => $laporan
], Response::HTTP_OK);
}
public function show($id)
{
$laporan=Laporan::where('user_id', Auth::id())->find($id);;
if (!$laporan) {
return response()->json([
'success' => false,
'message' => 'Sorry, Laporan not found.'
], 400);
}
return response()->json(compact('laporan'));
}
}
i have rename int from laporan to report to saport, create new controller, and make it HTTPS for saport always return 400.
as far as i know the structure of controler the same with other controller, couse i use meke:controller, and why it return 400 400 Bad Request.
and i make new basic route, and it return 400
Route::get('saport', function () {
return 'Hello World';
});
cahche:clear
route:clear
dumptautoload
trying remove saport from outside jwt,verify
all return 400
i have try all.
btw in local it run like charm, it case only in sharehosting.
i think it postman issue, not laravel. but if any solve for it issue please tell me

Class Controller does not exist

I'm trying to make a CRUD (which was working fine in a simple blade) in a new template but it is not showing any page of crud and says not found. If I type: php artisan route:list then it says:
Class App\Http\Controllers\PostsController does not exist
I'm following this tutorial and my folder structure is https://ibb.co/db4WQ8R
Controller
class CrudsController extends Controller
{
public function index()
{
$data = Post::latest()->paginate(5);
return view('adminhome', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'image' => 'required|image'
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'name' => $request->name,
'image' => $new_name
);
Crud::create($form_data);
return redirect('post')->with('success', 'Data Added successfully.');
}
}
Routes
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', function () {
if (Auth::user()->admin === 0) {
return view('home');
}
return view('adminhome');
});
Route::resource('post', 'PostsController');
});
How can I solve it?
In your controller rename Cruds
class PostsController extends Controller
{

Laravel 302 redirect issue

I am trying to get info from action, but when click, just page refresh and in console I get code 302 and stay on current page.
I read a lot of similar topics here but found nothing.
I am trying to execute http://laravel2.lo/getUserChannels?user_id=2
Laravel 5.7.16
route:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
Route::view('createUser', 'createuser');
Route::view('createChannel', 'createchannel');
Route::view('joinChannel', 'joinchannel');
Route::get('profile', 'UserController#profile');
Route::get('users', 'UserController#users');
Route::get('getChannelUsers', 'UserController#getChannelUsers');
Route::get('getUserChannels', 'ChannelController#getUserChannels');
});
ChannelController:
class ChannelController extends Controller
{
public function getUserChannels(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
]);
/** #var User $user */
$user = User::find($request->user_id);
return view('singleuser', ['channels' => $user->channels, 'username' => $user->name]);
}
}
In the log file no errors.
Thanks for any help and advise.
I don't think you'll receive query params as anything other than strings, so your integer validation fails.
To improve your error handling you could customize your App\Exceptions\Handler, catch your ValidationException errors with something like get_class() or instanceOf and do some neat stuff there
And of course you could not use query params at all by using Route::get('getUserChannels/{id}', 'controller#show'); and access it /getUserChannels/2 - then you could probably validate it as an integer
You could go with
Route::get('getUserChannels/{id}', ...
public function getUserChannels($id)
{
$user = User::findOrFail($id);
return view('singleuser', [
'channels' => $user->channels,
'username' => $user->name
]);
}
Then it would just throw a 404 if string, not found etc...
class ChannelController extends Controller
{
public function getUserChannels(Request $request)
{
$validator = \Validator::make($request->all(), ['user_id' => 'required|integer']);
if($validator->fails())
{
$error = $validator->errors()->first();
dd($error);
}
/** #var User $user */
$user = User::find($request->user_id);
return view('singleuser', ['channels' => $user->channels, 'username' => $user->name]);
}
}

Resources