Unable to POST data to another controller then STORE in Laravel - 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');
});
});

Related

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');

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">

laravel redirection to previous page after login

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.

Laravel 5.5 Update Post not working

edit.blade.php :
{!! Form::model($post, array('method'=>'PATCH','url'=>'/posts/{post}'.$post->id)) !!}
{{ method_field('PATCH') }}
{{csrf_field()}}
<label for="title">Titolo</label>
<input type="text" class="form-control" id="title" name="title" value="{{$post->title}}">
<label for="body">Corpo</label>
<textarea id="body" name="body" class="form-control" value="{{$post->body}}">
</textarea>
routes/web.php:
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/tags/{tag}', 'TagsController#index');
Route::post('/posts/{post}/comments','CommentsController#store');
Route::get('/posts/{id}/edit', 'PostsController#edit');
Route::get('/edit/{post}', 'PostsController#update');
Route::patch('/post/{post}', 'PostsController#update');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
Route::get('/login', 'SessionsController#create');
Route::post('/login', 'SessionsController#store');
Route::get('/logout', 'SessionsController#destroy');
postController:
public function edit( Post $post )
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
Post::where('id', $post)->update($request->all());
return redirect('/home');
}
You're using model binding here, so change it to:
public function update(Request $request, Post $post){
$post->update($request->all());
return redirect('/home');
}
Also, change URL to:
'url' => '/posts/' . $post->id
Also, remove these fields, because {!! Form::model() !!} automatically insert those for you:
{{ method_field('PATCH') }}
{{ csrf_field() }}
Change:
Post::where('id', $post)->update($request->all());
To:
Post::where('id', $post->id)->update($request->all());
new route:
Route::patch('/posts/{id}/edit/{post}', 'UpdateController#update');
{!! Form::model($post, array('method'=>'POST','url'=>'/posts/{id}/edit'. $post->id)) !!}
I think /posts/{id}/edit not working

Laravel wrong method

Laravel basics:
I have the following routes:
Route::group(['prefix' => 'pps', 'as' => 'pps.', 'middleware' => ['auth']], function (){
Route::get('/index', 'PPS\PPSController#index')->name('index');
/**
* Templates
*/
Route::group(['prefix' => 'templates', 'as' => 'templates.', 'middleware' => ['auth']], function (){
Route::get('/', 'PPS\Template\TemplateController#index')->name('index');
/**
* Sequence group
*/
Route::group(['prefix' => 'sequenceGroup', 'as' => 'sequenceGroup.', 'middleware' => ['auth']], function (){
Route::get('/', 'PPS\Template\SequenceGroupController#index')->name('index');
Route::get('/create', 'PPS\Template\SequenceGroupController#create')->name('create');
Route::post('/store', 'PPS\Template\SequenceGroupController#store')->name('store');
Route::get('/edit/{sequenceGroup}', 'PPS\Template\SequenceGroupController#edit')->name('edit');
Route::put('/update/{sequenceGroup}', 'PPS\Template\SequenceGroupController#update')->name('update');
Route::delete('/delete/{sequenceGroup}', 'PPS\Template\SequenceGroupController#delete')->name('delete');
});
/**
* Sequence template
*/
Route::group(['prefix' => 'sequenceTemplates', 'as' => 'sequenceTemplates.', 'middleware' => ['auth']], function (){
Route::get('/{sequenceGroup}', 'PPS\Template\SequenceTemplateController#index')->name('index');
Route::get('/create/{sequenceGroup}', 'PPS\Template\SequenceTemplateController#create')->name('create');
Route::post('/store', 'PPS\Template\SequenceTemplateController#store')->name('store');
Route::get('/edit/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#edit')->name('edit');
Route::put('/update/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#update')->name('update');
Route::delete('/delete/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#delete')->name('delete');
});
});
});
When i update the sequence group, everything works well.
But when i will update the sequence template, laravel goes allways to edit method and not to the update method.
Here my form:
<form action="{{ route('pps.templates.sequenceTemplates.update', $sequenceTemplate->id) }}" method="post">
{{ csrf_field() }}
{{ method_field('put') }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="control-label">#lang('pps.name')</label>
<input type="text" name="name" id="name" class="form-control" value="{{ old('name', $sequenceTemplate->name) }}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description" class="control-label">#lang('pps.description')</label>
<input type="text" name="description" id="description" class="form-control" value="{{ old('description', $sequenceTemplate->description) }}">
#if ($errors->has('description'))
<span class="help-block">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
<button type="submit" class="btn btn-primary">#lang('pps.save')</button>
</form>
The controller:
public function edit(SequenceTemplate $sequenceTemplate)
{
return view('pps.template.sequenceTemplate.edit', compact('sequenceTemplate'));
}
public function update(UpdateSequenceTemplateRequest $request, SequenceTemplate $sequenceTemplate)
{
$sequenceTemplate->update($request->except('_token', '_method'));
return redirect()->route('pps.templates.sequenceTemplate.index')->withSuccess(__('sequenceTemplateUpdated'));
}
The request:
<?php
namespace App\Http\Requests\PPS\Template;
use Illuminate\Foundation\Http\FormRequest;
class UpdateSequenceTemplateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'sequence_group_id' => 'required|integer',
'name' => 'required|string|min:3',
];
}
}
What is wrong? i do not find the bug.
When you fill the form and press submit button, Laravel validates the data and redirects you back because there is no sequence_group_id in the form and the field is required:
'sequence_group_id' => 'required|integer',
And you don't see any error message because you're not trying to display it for sequence_group_id. To test it put this to the top of the form:
Errors: {{ dump($errors->all()) }}
And try to submit the form.

Resources