laravel redirection to previous page after login - laravel

I have a view (URL: /equip-planner) with a form like this:
<form action="{{ url('equips') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<input type="text" id="name" name="name" class="form-control-sm">
<button type="submit" class="btn btn-primary btn-sm">
<i class="fa fa-btn fa-plus">Create</i>
</button>
</form>
Routes:
Route::get('/equip-planner', 'EquipmentController#ep')->name('equip-planner');
Route::resource('equips', 'EquipmentController');
Controller Constructor:
public function __construct(){
$this->middleware('auth', ['except' => ['index', 'show','create','home','ep']]);
}
When I submit my form, it will at first check if the user is logged in since the resource method "store" is not listed in the except list within the controller's constructor. So, if the user is not logged in, he will be redirected to the login page which is just fine.
BUT: After successful login, the user will be redirected to /equips instead of /equip-planner. I guess this is because of the form action ([...]action="{{ url('equips')}}[...]).
Does anyone have an idea how to change the redirection so the user will be sent back to /equip-planner? ...is it even possible? I think there must be another step back since the steps are: /equip-planner -> /equips -> login -> back to site before, which is /equips ?
EDIT:
My App/Http/Middleware/RedirectIfAuthenticated.php content:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/home');
}
return $next($request);
}

Use
return redirect()->back()
And if you want to send msg use with

I have a solution:
my form:
{{ Form::open( array('route' => 'equip-planner', 'files'=>true,'method'=>'post') ) }}
{{ csrf_field() }}
<input type="text" id="name" name="name" class="form-control-sm">
<button type="submit" class="btn btn-primary btn-sm">
<i class="fa fa-btn fa-plus">Create</i>
</button>
{{ Form::close() }}
Then I added a new route:
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => ['auth']], function () {
Route::post('/equip-planner', 'EquipmentController#store')->name('equip-planner');
});
});
This is working as intended.

Related

DELETE method is not supported for this route. Supported methods: GET, HEAD, POST

I'm using laravel 9.x
my route is
Route::middleware('verified')->group(function (){
Route::get('dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::resource('kullanicilar', UserController::class);
});
and my controller has destroy methods
public function destroy($id)
{
echo 'destroy'.$id;
//User::find($id)->delete();
//return redirect()->route('kullanicilar.index')
// ->with('success','Kullanıcı başarı ile silindi.');
}
and my user_index.blade.php
<form method="POST" aciton="{{ route('kullanicilar.destroy',$user->id) }}" style="display:inline">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-times"></i></button>
</form>
even though everything seems to comply with the rules, I'm getting this error.
You have a typo in the action element causing the form to be posted back to the same route as the original page;
<form method="POST" aciton="{{ route('kullanicilar.destroy',$user->id) }}"
note action is misspelled
Also, as you are using resource controller, you should accept the model in the destroy method.
Use Route::list to check what your controller should accept
action NOT aciton in Your Form Ex :
<form method="POST" action="{{ route('kullanicilar.destroy',$user->id) }}"
style="display:inline">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-times"></i></button>
</form>
I found the solution by overriding the destroy method with get on the web.php route. it's working for me for now.
such as
//this should be at the top
Route::get('kullanicilar/remove/{id}', [UserController::class,'destroy'])->name('kullanicilar.remove');
Route::resource('kullanicilar', UserController::class);
and change my user_index.blade.php
<i class="fa fa-times"></i>
it works.

Route is not defined after successful log in

little bit stuck with redirecting to other page after successful login for quite a long time. I believe that my understanding about sanctum auth is a bottleneck for this issue( Or maybe I am wrong ). However, after reading the docs still couldn't find the answer to my issue. Situation: I have declared few public routes and one private. I have created a user in my database and whenever I try successfully to log in it does not redirect to other page, and my credentials are 110% correct, but anyway after submit it only displays:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/dashboard] not defined.
However, I have that route, it's protected but after sign in I assign it. Maybe I am doing in a wrong way?
welcome.blade:
#section('content')
<div class="container-fluid">
<div class="container">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<form action="{{action('App\Http\Controllers\AuthController#login')}}" method="POST">
#csrf
<input type="text" class="form-control" placeholder="Email address" name="username" required>
<input type="password" class="form-control" placeholder="Password" name="password" required>
<div class="login-btn">
<button type="submit" class="btn btn-success">Sign in</button>
</div>
</form>
</div>
</div>
</div>
#endsection
AuthController:
public function login(Request $request)
{
$fields = $request->validate([
'username' => 'required',
'password' => 'required',
]);
$user = User::where('username', $fields['username'])->first();
if (!$user || !Hash::check($fields['password'], $user->password)) {
return Redirect::back()->withInput()->withErrors('Incorrect username or password');
} else {
$token = $user->createToken($request->username);
return redirect()->route('/dashboard')->with('token', $token);
}
}
web.php :
// Private routing
Route::group(['middleware' => ['auth:sanctum']], function () {
// Agents dashboard
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');
});
// Public routing
Route::get('/', function () {
return view('welcome');
});
Route::post('/login', [AuthController::class, 'login'])->name('login');
Dashboard -> main:
#extends('layouts.app')
#section('content')
<h1>Private</h1>
#endsection
change ->route('/dashboard') to ->route('dashboard'). This value references the name value on a route. eg:
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');

Laravel get route view without redirect

I am making a search in website.
public function search(Request $request)
{
$search_value = $request->search_txt;
$data_res = Data::Where('text', 'like', '%' . $search_value . '%')->get();
$navbar_search = Navbar::where('id','183')->first();
return redirect(route('response', $navbar_search->slug))->with('data_res',$data_res);
}
This is my controller function. I'm getting problem that i want to display data in the same page. I need to return view to this exact 'response' route and send slug. This redirect does not work, because $data_res after redirect is empty..
Routes:
Route::post('/search/search_res', 'SearchController#search')->name('search.srch');
Route::get('/{slug}', 'FrontEndPagesController#index')->name('response');
HTML:
<form class="form-horizontal" method="POST" action="{{ route('search.srch') }}">
{{ csrf_field() }}
<div class="main search_field">
<div class="input-group">
<input type="search" name="search_txt" class="form-control" value="{{ old('search_txt') }}" placeholder=" tekstas apie paieska ?" required maxlength="200" style="padding-left: 10px !important;">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</form>
#if(!empty($data_res))
#foreach($data_res as $data)
{{ $data->id }}
#endforeach
#endif
With my little experience, I think when you redirect to another route and includes 'with', it stores the data in session.
you may want to access in the function FrontEndPagesController#index by
$data_res = session()->get('data_res');
then, to make it available for blade file, put it in return response like
return view('your response view', compact('data_res')

How to use the same form for add and edit in laravel

I'm new to laravel,i want to use the same form for add and edit.I created an form and form insertion is ok but i need to use the same form edit based on the id selected.When click the edit icon i want to direct the same page displaying the contents to edit.So give me idea for implementing this.
<form method="POST" action="/categoryinsert">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="card-body">
<div class="form-group">
<div class="col-md-4">
<label for="exampleInputEmail1">Category</label>
<input type="text" class="form-control" name="category" id="category" placeholder="Enter Category">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Add/edit in view with the help of user model
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'create',
]);
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'edit',
'user' => $user
]);
}
<form action="{{ ( $view_type == 'edit' ? route('example', $id) : route('control.mentors.store')) }}" role="form" method="post" name="frmDetail">

Unable to POST data to another controller then STORE in Laravel

I am using Laravel 5.2 and trying to submit a form on dropdown selection. Even though i can do it. But it always redirect to store function which is registered as a resource route.
My routes.php file have routes define like this:
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function () {
return view('dashboard.dashboard');
});
Route::get('getcurrency', 'QuoteController#getCurrency'); <!--------This is where i have problem--------->
Route::resource('quotes','QuoteController');
});
});
I tried naming route as well. But it always take me towards the store function
here is how my dropdown looks like:
<form method="post" action={{ action('QuoteController#getCurrency') }}>
<div class="form-group">
<label class="control-label col-md-1">Name</label>
<div class="col-md-5">
<select class="form-control select2me selectCurrency" name="user_id" onchange="this.form.submit()">
#foreach($users as $user)
<option value="{{$user->id}}">{{ $user->name }}
#if(!empty($user->companyname))
({{$user->companyname }})
#else
({{$user->email}})
#endif
</option>
#endforeach
</select>
</div>
</div>
</form>
I am not able to understand why its always force send the value to store function only, when i have even try to mentioned route, method, url and action. Non of the system working for me.
Is laravel have predefined tendency to take SUBMIT BUTTON to a specific function only?
Here is what my URL is when i have my form :
http://localhost/laravel/public/quotes
Does anyone know why this happens? And how can i fix it?
Thank you!
Route.php
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function () {
return view('dashboard.dashboard');
});
Route::post('getcurrency', 'QuoteController#getCurrency'); // make it post instead of get
Route::resource('quotes','QuoteController');
});
});
blade file
<form method="post" action={{ url('getcurrency') }}>
<input type="hidden" name="_token" value={{ csrf_token() }}/>
<div class="form-group">
<label class="control-label col-md-1">Name</label>
<div class="col-md-5">
<select class="form-control select2me selectCurrency" name="user_id" onchange="this.form.submit()">
#foreach($users as $user)
<option value="{{$user->id}}">{{ $user->name }}
#if(!empty($user->companyname))
({{$user->companyname }})
#else
({{$user->email}})
#endif
</option>
#endforeach
</select>
</div>
</div>
</form>
If you use route resource your post will go automatically in store method for more https://laravel.com/docs/5.2/controllers#restful-resource-controllers
If you want to change the method then change the action,like
<form method="post" action='quotes'>
Then need to write a route for this url before resource route
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function () {
return view('dashboard.dashboard');
});
Route::get('getcurrency', 'QuoteController#getCurrency'); <!--------This is where i have problem--------->
Route::post('quotes','QuoteController#customMethod');
Route::resource('quotes','QuoteController');
});
});

Resources