Parsing data from Controller -> Controller -> View - laravel

I have a form that will post data to ControllerONE store it in a database and redirects the user to /list. The route /list then uses the ControllerTwo to generate a view. However if I:
return redirect('/list)->withSuccess('DONE!');
I can't retrieve $success in the view, it's gone. Where is the issue?
web.php
Route::get('/acp/nodes', 'NodeController#index');
Route::post('/acp/nodes/category/save', 'CategoriesController#save');
NodeController#index
return view('admin.nodes.edit')->with('categories', $categories);
CategoriesController#save
return redirect('acp/nodes')->withSuccess('true');
With that I can't get either $success or session('success').

you can't retrieve it cause it's not a variable passed to the view, it's a value stored on the flash array that you can retrieve using session('success'), and to test if it exists, you should use session()->has('success').

After a few hours of fiddling around I noticed that I've got
\Illuminate\Session\Middleware\StartSession::class
in both $middleware & $middleWareGroups
Removing the duplicate entry fixed the issue entirely.

Related

Passing data from blade to blade in Laravel

I have a page where you can create your workout plan. Second page contains "pre-saved" workouts and I want them to load by passing parameters from second page to first. If you directly access first page, you create your workout plan from scratch.
// first page = https://prnt.sc/y4q77z
// second page = https://prnt.sc/y4qfem ; where you can check which one you want to pass to first page
// final step looks like this: https://prnt.sc/y4qh2q - but my URL looks like this:
www.example.com/training/plan?sabloni%5B%5D=84&sabloni%5B%5D=85&sabloni%5B%5D=86
this 84,85,86 are IDS
Can I pass params without changing URL ? Like having only /training/plan without anything after ?
public function plan(Request $request){
$workout = false;
if($request->workout){
$workout = $request->workout;
$workout = SablonTrening::find($sabloni); // $workout = array [1,3,4,5,6]
}
return view('trener.dodaj_trening', compact('workout'));
}
If you are getting to the /training/plan page with GET request, you could simply change it to POST. That way the parameters would be hidden in the URL but would be present in the request body. You would need a new post route:
Route::post('/training/plan', 'YourController#plan')->name('training.plan');
And then, in the form where you are selecting these plans, change the method on submit:
<form action="{{route('training.plan')}}">
//Your inputs
</form>
Your method should still work if your inputs stay the same.
Note: Not sure you would still keep the functionalities that you need, since I can't see all the logic you have.
If you have any questions, let me know.
To pass data from on blade to another blade.
At the end of first post before redirect()-route('myroute') add $request->session()->put('data', $mydata);
At the begining of the route 'myroute', just get back your data with $data = $request->old('data');

Laravel Pagination on POST request

Im using Laravel v7 and i have a question about pagination.
So far im using 2 routes, 1rst to return a view with all rows from database, and 2nd receives an input and returns that view with the rows filtered by that input value.
But im using pagination, and on the 2nd route, when i try to go to 2nd page it gives me an error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
I've tried to change my form method to GET but i need that the token doesn't appear on the page URL and beside that, when i go to 2nd page, it returns all the rows again.
Thats my code so far:
Routes:
Route::get('concessions', 'ConcessionController#index')->name('concessions.index');
Route::post('concessions/search', 'ConcessionController#search')->name('concessions.search');
Controller
class ConcessionController extends Controller
{
public function index()
{
$concessions = DB::table('concessions')->paginate(12);
return view('admin.concessions.index', compact('concessions'));
}
public function search(Request $request)
{
$name = $request->name;
$concessions = Concession::where('name', 'like', '%' . $name . '%')->paginate(12);
return view('admin.concessions.index', compact('concessions', 'name'));
}
}
Any way to do that?
Laravel pagination only works with get parameters.
You should use GET method for your search page. POST requests aren't meant for the purpose of displaying data. Why? There are many reasons, but to be short I will give you three examples :
1. When you access the first page, you get the data by GET request,
not POST request. So if you want to use POST request, you
need to access the page as POST request by sending data with
POST method.
2. With GET parameters, let's say you are on 5th page - you can
copy the link and paste it to friend and he will be able to view
the same content as you. With POST this is impossible.
3. You can not use back button with POST requests, if you manage to
get pagination to work.
POST requests are useful when you need to submit data to the server, in order to create new record, for example.
So I suggest you to change your route type to GET.
From my perspective, if you change your route code similar to below code, it will work properly with both methods of GET and POST.
Route::any('concessions/search', 'ConcessionController#search')->name('concessions.search');

How do I pass data from my controller to a view in Laravel 5.5?

I have a function that I'm trying to pass some data to a view. I can't get the Route to recognize the data, it just keeps saying my variables are undefined. Here's what I'm trying to do:
return redirect('confirm')->with([
'name'=>$name,
'service'=>$service,
'$email_address'=>$email_address
]);
Then in my web.php file, I have:
Route::get ('confirm', function($name,$service,$email_address){
return view('confirm',compact('name','service','email_address'));
})->name('confirm');
Laravel just throws an error "Missing argument 1 for Illuminate\Routing\Router::{closure}()"
I'm at a complete loss, I've tried this a bunch of different ways. If I call the view right from my controller, it works fine, but then URL isn't what I want it to be, so it seems like I have to return the redirect and reference the data in my route definition. Can anyone enlighten me?
If it's ok to show the email in the route then you can correct the problem like this :
Route::get ('confirm/{name}/{service}/{email_address}', function($name,$service,$email_address){
return view('confirm',compact('name','service','email_address'));
})->name('confirm');
And in the controller :
return \Redirect::route('confirm', [
'name'=>$name,
'service'=>$service,
'email_address'=>$email_address
]);
Ps : this is not recommended i just answer you problem but there is a better way to do it, passing just an id for exsample then find the user by id then take his email and other stuff.

Pass variable from middleware to view via controller in Laravel 5.2

Hi I am trying to do the following in Laravel 5.2.
Summary: Pass some variables from middleware to view, via controller
Detailed: When a client is logged in, no matter what route they want, we need to check if they have completed all "setup steps" (each step refers to a different route, e.g. one could be company info, another could be product settings, etc). If they have completed all setup steps, then let them proceed to their chosen route, otherwise we redirect to the appropriate "setup steps" route, whichever one they haven't completed yet.
All client controllers run the same middleware, called NonSuperAdmin. I would like to put the checking of "setup steps" in this middleware, and redirect from there as appropriate. If client is redirected to a setup route by this middleware, we need the "incompleteSetupTasks" collection to be passed on to the relevant view, via the appropriate setup steps controller method.
Is this possible? Any help is much appreciated.
In the middleware use session handler
if($condition === true){
$data = [ //your content ];
Session::flash('your_key', $data);
}
next($request);
This data will also be available in your controller and in view
This is how you can access data in controller
public function yourControllerAction($request)
{
$somevariable = Session::get('your_key');
$viewdata = [
'content' => $somevariable
]
return view('yourview', $viewdata);
}
Or directly access the session data in view
//inblade
<p>
Your html content
#foreach(Session::get('your_key' as $data)
//your stuff
#endif
</p>
May be use Laravel Session to store and read values?
You can pass your setup steps to get or post parameters and check in routes with middleware if these parameters are empty:
Route::get('post/{setup1?}/{setup2?}', ['middleware' => 'role:admin', function ($setup1, $setup2) {
if(empty($setup1) and empty($setup2)){
// do smth
} else {
// redirect
}
}]);
Question marks mean, that they are optional parameters. Hope it was helpful.

My data only shows if I debug it. What's going on?

I'm working with Stripe's API and am trying to retrieve data. I have the code below:
$data = \Stripe_Invoice::all(array(
"customer" => $user->customer_id
));
If I set the AJAX response equal to $data, the response is shown as empty ( {} ). If I debug it in the backend, I get a huge list of all kinds of awesome properties to use. All I do is this:
debug($data); // returns huge data set
The trouble is that I can't access the variable in the frontend. I want to use:
console.log(response);
html += response.url;
And things to that effect, but the data is completely empty when the front end interprets it, for some reason.
In the same effect, I can't set it as a session either (I used to set session logs to debug instead of using the debug feature).
$data // can be accessed on the frontend if we use just php to set a variable
$_SESSION['log'] = $data; // empty
What's going on? I'm using the PHP framework CakePHP 3 (latest version of Beta). I think it has something to do with returning the data as serialized (maybe?) but that wouldn't explain the session logging. This happens right before we send the data back:
$this->set(compact('data', $data));
$this->set('_serialize', 'data');
If $data is not empty than you should just use the set method in the controller
$this->set(compact('data', $data));
Than you should have the corresponding view at /src/Template/ControllerName/json/methodName.ctp (Change ControllerName and methodName to what you have)
This file should be this.
<?php
print json_encode($data);
?>
That is all. You should have your data on your client side as a json object.
Turns out the answer was that the values could not be displayed while the array was protected. Calling Stripe's method __toArray() on the Stripe object made the data accessible, and setting worked past this point.
$data = \Stripe_Invoice::all(array(
"customer" => $user->customer_id
));
$data = $data->__toArray();
$this->set(compact('data', $data));
$this->set('_serialize', 'data');

Resources