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.
Related
How do I tell my API to display a particular result based on another column?
e.g. localhost:8000/api/gadgets/{{id}}
Normally it returns the particular information of the specific gadget with that ID and localhost:8000/api/gadgets/{{imei_code}} does not return any value or an error whereas imei_code is a column that I needed to pass as a GET request...
I'm using the normal resource controller
public function show(Gadgets $gadget)
{
$response = ['data' => new GadgetResource($gadget), 'message' => 'specific gadget'];
return response($response, 200);
}
Also I need help on how I can create like a search function in the controller.
You can`t do two similar URLs. I think your route for URL
localhost:8000/api/gadgets/{{imei_code}}
isn`t work. Also the order of the routes is important and route that defined firstly will be have higer priority then route that defined secondly.
Because your routes /api/gadgets/{{id}} and /api/gadgets/{{imei_code}} is similar in this case only the one described earlier will be processed.
You can define another router and handler, for example:
localhost:8000/api/gadgets
That will return a list of gadgets by default and you can add filters for imei_code. For example:
localhost:8000/api/gadgets?imei_code=123
And your handler for the new route may be writed something like that:
public function showList(Request $request): GadgetResource
{
if ($imeiCode = $request->query('imei_code')) {
$list = Gadget::query()->where('imei_code', $imeiCode)->get();
} else {
$list = Gadget::query()->take(10)->get();
}
return GadgetResource::collection($list);
}
Or like alternative solution you can create diferent route for searching of gadgets exactly by imei_code to get rid of any route conflicts
localhost:8000/api/gadgets/by_imei/123
public function findByImei(Request $request): GadgetResource
{
$imeiCode = $request->route('imei_code');
$item = Gadget::query()->where('imei_code', $imeiCode)->first();
return new GadgetResource($item);
}
You can specify the model key by scoping - check docs
Route::resource('gadgets', GadgetController::class)->scoped([
'gadget' => 'imei_code'
]);
Than, when Laravel try to bind Gadget model in Controller - model will will be searched by key imei_code.
This code equvalent of
Route::get('/gadget/{gadget:imei_code}');
Try to change response
public function show(Gadgets $gadget)
{
$response = ['data' => new GadgetResource($gadget), 'message' => 'specific gadget'];
return response()->json($response);
}
I'm using Laravel 5.5.
My objective is to redirect to another method on the same controller to display a view with data.
class SeancesController extends Controller {
...
public function getRecommandations(Request $request) {
...
$data = [
'recommandationAutresActiviteMemeDateHeure' => $recommandationAutresActiviteMemeDateHeure,
'recommandationsMemeActiviteMemeHeure' => $recommandationsMemeActiviteMemeHeure,
'recommandationsMemeActiviteMemeDate' => $recommandationsMemeActiviteMemeDate
];
return redirect()->action('SeancesController#showRecommandations', $data);
}
public function showRecommandations(Request $request) {
return view('listeRecommandations', $request->data);
}
}
It is the right way to do this? Because I get this error :
InvalidArgumentException: Action App\Http\Controllers\SeancesController#showRecommandations not defined. in file /home/nicolas/public_html/M1_CSI/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 338
I need to use action because I use an ajax call to access at getRecommandations().
I used this doc : http://laraveldaily.com/all-about-redirects-in-laravel-5/.
I didn't add a route that points to showRecommendations on my routing file. It's a problem?
Thank's for help!
I didn't add a route that points to showRecommendations on my routing file. It's a problem?
yes , it is a problem. because the redirector checks the routes that are assigned to the action and redirects the user to the route.
When pressing my send button it's giving error like this-
Here is my routes web.php bellow-
Route::group(['prefix'=>'ajax', 'as'=>'ajax::'], function() {
Route::resource('message/send', 'MessageController#ajaxSendMessage')->name('message.new');
Route::delete('message/delete/{id}', 'MessageController#ajaxDeleteMessage')->name('message.delete');
});
Here is my controller MessageController.php bellow:
public function ajaxSendMessage(Request $request)
{
if ($request->ajax()) {
$rules = [
'message-data'=>'required',
'_id'=>'required'
];
$this->validate($request, $rules);
$body = $request->input('message-data');
$userId = $request->input('_id');
if ($message = Talk::sendMessageByUserId($userId, $body)) {
$html = view('ajax.newMessageHtml', compact('message'))->render();
return response()->json(['status'=>'success', 'html'=>$html], 200);
}
}
}
Resource routes should be named differently:
Route::prefix('ajax')->group(function () {
Route::resource('messages', 'MessageController', ['names' => [
'create' => 'message.new',
'destroy' => 'message.destroy',
]]);
});
Resource routes also point to a controller, instead of a specific method. In MessageController, you should add create and destroy methods.
More info at https://laravel.com/docs/5.4/controllers#restful-naming-resource-routes
You can't name a resource. Laravel by default name it, if you want to name all routes you must specify each one explicitly. It should be like this:
Route::group(['prefix'=>'ajax', 'as'=>'ajax::'], function() {
Route::get('message/send', 'MessageController#ajaxSendMessage')->name('message.new');
Route::delete('message/delete/{id}', 'MessageController#ajaxDeleteMessage')->name('message.delete');
});
Update
Another mistake of yours was trying to resource a single method. A Route::resource() is used to map all basic CRUD routes in Laravel by default. Therefore, you have to pass the base route and the class i.e:
<?php
Route::resource('message', 'MessageController');
Look at web.php line 28.
Whatever object you think has a name() method, hasn't been set, therefore you try and call a method on null.
Look before that line and see where it is (supposed to be) defined, and make sure it is set to what it should be!
So far all attempts to modify the routing methods have failed.
Been following some documentation on laravel restful controllers and have one set up to do basic editing and adding of items to a database. It was going well till I hit the snag on... well I'm not sure what precisely is triggering the problem, but basically, everything works till I hit submit on the form and then it's Game Over.
Normally I'd be able to diagnose this by checking to see if I'm using the right call, or made a spelling mistake or something. But this is a new request for me, so I can't quite debug where the problem is coming from.
This is the error those who know what to look for. In full here.
MethodNotAllowedHttpException in RouteCollection.php line 218:
My routes are pasted here.
A printout of the routes is here:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
use App\UserEdit;
use DB;
use App\Http\Requests;
class EditUserController extends Controller
{
public function index()
{
$array = UserEdit::all()->toArray();
return view('UserEntry', compact('array'));
}
public function create()
{
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
}
public function store(UserFormRequest $request)
{
//$user = new UserEdit([
// 'name'=>$request->get('First_Name'),
// 'email'=>$request->get('email'),
// 'username'=>$request->get('name')
//]);
//
//$user->save();
//return \Redirect::route('users')->with('message', 'Nice Work.');
}
public function show($id)
{
try {
$array = UserEdit::findorFail($id)->toArray();
return view('UserEdit')->with('array', $array);
} catch(\Exception $e) {
return \Redirect::route('users.index')
->withMessage('This user does not exist');
}
}
public function edit($id)
{
$user = UserEdit::findorFail($id);
return view('EditUser')->with('user',$user);
}
public function update($id, UserFormRequest $request)
{
$user = UserEdit::findorFail($id);
$user->update([
'name' => $request->get('name'),
'email' => $request->get('email')
]);
return \Redirect::route('users.edit', [$user->id])->with('message', 'Details Updated!');
}
public function destroy($id)
{
//
}
}
The Blade is here.
if you have a hard time finding the solution the easiest solution is using
Route::any('users/{user}', 'UserEntryController#update');
this allow you to access this action with any method type
OR
Route::match(array('get', 'put'), 'users/{user}', 'UserEntryController#update');
so you need 2 method which are
get -> view
put -> submit update
you can just indicate which method type you want to be accessible with in this action
i think you are using model in form.try this
{{ Form::open(['method' => 'put', 'route'=>['users.update', $user->id], 'class'=>'form']) }}
As per your route list and route put doesnt taking id so you get method not found exception
PUT users/{user} App\Http\Controllers\EditUserController#update
instead of using resouce just type each route for each method
Route::put('users/{user}', 'EditUserController #update');
It seems like after sorting out the routes, the issue fell to a bad capitalisation. $user->id should have been $user->ID.
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;
}