data duplicating when use custom controller in laravel's voyager admin panel - php

I use laravel 5.4 and voyager admin panel. There's module I created called recipes. I created database table, model and CUSTOM controller and views for this module. I also created BREAD, and indicated there my custom controller. the problem is the when I fill form and submit it, data been duplicated in table, I have 2 identical rows in my table every time I create the item. I think the problem is that it sends 2 requests, one of requests is from my custom route and controller, and another one is from voyager itself. but don't know how to fix it.
print screen from my BREAD
my routes
Route::group(['prefix' => 'admin', 'middleware' => ['admin']], function () {
\Voyager::routes(); //voyager routes
// routes for my custom module
// I can comment this routes, but result is the same
Route::resource('/recipes', 'Admin\RecipesController');
});
my controller
public function store(Request $request)
{
$recipe = Recipe::create($request->except(['modules']));
return redirect()
->route("recipes.index")
->with([
'message' => __('voyager.generic.successfully_added_new')." recipe",
'alert-type' => 'success'
]);
}
any idea?

You should try this for check AJax Request:
public function store(Request $request)
{
if (!$request->ajax()) {
$recipe = Recipe::create($request->except(['modules']));
}
return redirect()
->route("recipes.index")
->with([
'message' => __('voyager.generic.successfully_added_new')." recipe",
'alert-type' => 'success'
]);
}

the issue was because of form element class form-edit-add, as it seems there was event bound to this class. I removed it and now it works fine

Related

Login with one parameter

I want to make a login in Laravel that receives only one parameter, i.e. has a simple form that receives one input, and based on that input, the user is authenticated. If user is admin, it will redirect to /adminpage, else if the user is a regular user it redirects to /homepage.
I want to use a custom table, model, and controller. I searched the internet but could not find a solution.
EDIT
I have form like this:
<form action="someroute" method="POST">
<input type="text" name="rf_id">
<input type="submit" value="login">
</form>
My migration is:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('lastname');
$table->string('workid');
$table->boolean('isAdmin')->default(False);
$table->string('rf_id');//
$table->timestamps();
});
Now i need controller that handle this.
So base on rf_id, controller needs to fin user and thec check his role.
I try this but don't work:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public function index(){
return view('singin');
}
public function login(Request $request){
$credentials = $request->only('rf_id');
if(Auth::attempt($credentials)){
//we need to know who is logging in
return $this->filterAndRedirect(Auth::user());
}
return "there is no user with that rfid";
}
private function filterAndRedirect(User $user){
//the function to take care of the routing
if($user->isAdmin){
# return redirect('/homepage');
return "This is admin";
}
else{
# return redirect('/adminpage');
return "This is worker";
}
}
}
Here is how I would do it;
First of all you have to add the table column in your migration file for the user-type and the login parameter.Check below for migration docs
Next is the page where you have the form, I don't know what your parameter is so I'll just call it 'param'. I am assuming you know how to create and submit forms with laravel so I won't put the code here.
Now the interesting part, the controllers:
This is how my user creation in the RegisterController would look;
Note that I'm using the standard laravel auth controllers
public function createStandardUser(Request $request){
//function to add the Standard user
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'param' => $request['login-param'],
'user-type' => 'standard'//the user type
]);
Auth::login($user);//Explicitly starts a new session for the user
return redirect('/homepage');
}
If you are gonna have a different form for the Admin registration the function to add the admin user will roughly be the same;
public function createAdminUser(Request $request){
//function to add the Admin user
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'param' => $request['login-param'],
'user-type' => 'admin'//the user type
]);
Auth::login($user);//Explicitly starts a new session for the user
return redirect('/adminpage');
}
The last part would be the LoginController where you can use the attempt() function to authenticate the user and start a new session for them using your single parameter.
You will have these functions
public function login(Request $request){
if(Auth::attempt(['login-param' => $request->get('login-param'])){
//we need to know who is logging in
return $this->filterAndRedirect(Auth::user());
}
}
private function filterAndRedirect(User $user){
//the function to take care of the routing
if($user->user-type == 'standard'){
return redirect('/homepage');
}else if($user->user-type == 'admin'){
return redirect('/adminpage');
}
}
The Relevant Documentation:Database Migration Docs, Laravel Authentication Docs
Suggestion:If I were you I would use Roles/Permissions as opposed to using a table row in your DB, I think its more robust. Check out this library it is well documented and gets updated ->Laravel Permission By Spatie
EDIT:This answer assumes you are using the standard User model and Authentication Controllers because thats the whole point of using a framework isn't it?

automatically redirects to index page instead of desired page

I have a taskController controller in my laravel application.Inside my resource folder i have have three pages under resource/views/taksController/
1.index.blade
2.store.blade
3.create.blade..
in my create.blade i have a form which on submit will go through a validation and if succeeded i want it to be redirected to store.blade ,otherwise it will redirect to create.blade again to fill up the form again.But here in my program ,on success it doesn't redirect me to store.blade file, rather it redirect me to index.blade.Why is this happening?How i can solve this?
i am using laravel 5.2
In my route.php i added the controller like
Route::resource('taskController','taskController');
in taskController the validation logic inside controller is like the following:
public function index()
{
//
return View::make('taskController.index');
}
public function create()
{
//
return View::make('taskController.create');
}
public function store(Request $request)
{
$rules = array(
'email' => 'required|email', // required and must be unique in the ducks table
'comment' => 'required',
'agree' => 'required|accepted' // required and has to match the password field
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
echo 'bal';
// redirect our user back to the form with the errors from the validator
return Redirect::route('taskController.create');
}else{
return Redirect::route('taskController.store');
}
}
The URL used for the index route and the store route are the same. The difference is the HTTP verb that is used on that URL. GET requests to the URL will take you to the index, whereas POST requests to the URL will take you to the store.
In your store() method, when you return Redirect::route('taskController.store');, the route() method converts the parameter to the URL, and then makes a GET request to it. This is why you are redirected to index.
Generally, your store, update, and destroy routes don't have views associated with them. They are meant to perform an action and then redirect to the route that contains the view.
For example, the general workflow for creating a new resource is:
create route shows create view which has the form,
form POSTs to store route,
store route attempts to create new resource,
if validation fails, store route redirects back to create route with errors,
if resource is created successfully, store route redirects to the show route, with the id of the newly created resource.
The workflow for editing a resource is similar:
edit route shows edit view which has the form,
form PUTs to update route,
update route attempts to edit the resource,
if validation fails, update route redirects back to edit route with errors,
if resource is modified successfully, update route redirects to the show route, with the id of the modified resource.
i think you should have this:
public function index(){
return view('taksController.index');
}
public function create(){
return view('taksController.create');
}
public function store(Request $request)
{
//
$rules = array(
'email' => 'required|email', // required and must be unique in the ducks table
'comment' => 'required',
'agree' => 'required|accepted' // required and has to match the password field
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
//echo 'bal';
// redirect our user back to the form with the errors from the validator
return Redirect::route('taskController.create');
}else{
return view('taksController.store');// redirects me to index.blade instead of store.blade
}
}

Passing argument from controller to controller not working

Aloha, I'm making a workout manager in which you have a dashboard displaying your 5 last workouts. I have set a form for each one workout for allowing the user to delete any of them. Here the form in the dashboard:
{!! Form::open(['route' => ['dashboard.workout.destroy', $workout->id], 'style' =>'display:inline-block;', 'method' => 'DELETE']) !!}
This route will call this method in WorkoutController.php
public function destroy($id, Request $request)
{
$workout = Workout::findOrFail($id);
$workout->delete();
$message = "Workout deleted successfully!";
return redirect()->route('dashboard.index', ['message' => $message]);
}
And this route will call this method in DashboardController.php
public function index($message = null)
{
$user = Auth::user();
// Workouts
...
// Inbodies
...
// Measures
...
return view('dashboard.index', compact('user','workoutsDesc','workouts','lastInbody','inbodies','measures','lastMeasure','message'));
}
The question is that I'm trying to pass the variable $message from WorkoutController to DashboardController for displaying a successfull alert after deleting a workout, but I don't know how to do it. I have tried with:
return redirect()->action('Dashboard\DashboardController#index', [$message]);
return redirect()->action('Dashboard\DashboardController#index')->with('message', $message);
return redirect()->route('dashboard.index', $message);
But I still trying to find the way for doing it.
First of all, from Laravel 5.1 Documentation:
If your route has parameters, you may pass them as the second argument to the route method
As the message is not a parameter to your route, so you can't pass that. A possible solution can be Flashing data. Check the next controller if the session has that key and contain a value, then add it to a variable and pass to the view.
Hope this works.

Storing data in laravel happens once

Hi there best colleagues i've the following strange issue when i want to store data in my database but accomplish this task just once, when i want to store another data i get the following problem:
"Whoops something went wrong".
i've the following code in my controller
public function store()
{
$user = new User();
$user->username = Input::get('username');
$user->save();
return Response::json(array(
'error' => false,
'succes' => $user->toArray()),
200
);
}
and this is my routes.php
Route::group(array('prefix' => 'api/v1'), function() {
Route::resource('users', 'UserController',
array('except' => array('create', 'edit')));
});
I'm trying to post trough Postmen extension in Chrome and when i request a post to my uri:
http://www.bla.com/testLaravel/api/v1/users
(bla.com = localhost)
it just stores once my data and after that i get an error , i seriously can't figure out what the problem is. It would be great if someone can help me with it.
tnx

Symfony2 - How to render a view from another controller

I have two controllers, homepage and Security.
In the homepage, I am displaying one view and in the security, I am doing some things, and one of them is the email address validation.
What I would like is that when the email validation code is not valid, display the homepage with a flash message. For that, I will have to render the indexAction of the HomepageController, from the Security controller, by giving him as parameter the flash message.
How can this be done? Can I render a route or an action from another controleller?
Thank you in advance.
I believe the checking should not be done in the Security controller. Right place in my opinion is a separate validator service or right in the entity which uses the email address.
But to your question, you can call another controller's action with $this->forward() method:
public function indexAction($name)
{
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
'name' => $name,
'color' => 'green',
));
return $response;
}
The sample comes from symfony2 documentation on: http://symfony.com/doc/2.0/book/controller.html#forwarding
I have found the solution, simply use the forward function by specifying the controller and the action nanme:
return $this->forward('MerrinMainBundle:Homepage:Index', array('flash_message'=>$flash_message));
redirectToRoute : Just a recap with current symfony versions (as of 2016/11/25 with v2.3+)
public function genericAction(Request $request)
{
if ($this->evalSomething())
{
$request->getSession()->getFlashBag()
->add('warning', 'some.flash.message');
$response = $this->redirectToRoute('app_index', [
'flash_message' => $request->getSession()->getFlashBag(),
]);
} else {
//... other logic
}
return $response;
}

Categories