view does not seems to see $error variable in laravel middlegroup "auth" - laravel

I'm having problem on my view not seeing any $Message variable, which is working on my login controller.
public function index()
{
$data = somedataFromModel::find(1);
return View::make('SomeView',compact(['sampleData' => $data]);
}
public function postOrStoreData(CustomFormRequest $request)
{
/* where update or insert or store occurs */
//after all my updating codes or inserting codes
return back()->with('Message','test');
}
with these codes I am not able to run my view correctly, it does not see $Message
it has the same implementation as my login controller and views.
right now my view needs to be authenticated to be used, so it is under the Middleware Group of 'auth', I also see the MiddleWareGroups, web and api. help me I'm lost.
My only objective is after I post any data, without using AJAX, just standard Form Action and Submit Method, I will display an alertClass with bootstrap.

redirect()->with() stores it in the session.
Per the docs, you thus access it via session('Message') in the view, not $Message.
The syntax may appear similar to view()->with(), but the functionality is not identical.

Related

refresh page after updated model - Laravel

I want to refresh current page after any user update
I'm trying to do something like that in User Model :
public static function boot()
{
self::updated(function ($model) {
return back(); //or redirect(Request::url())
});
}
but it wasn't working.
How can I refresh the page if any user updated
In general, the model event functions creating/created/updating/updating/saved/saving should only ever return false or nothing (void). Returning false in for instance updating (that is: before the model is persisted in the database) cancels the model update (this works for all propagating events, see https://laravel.com/docs/9.x/events#stopping-the-propagation-of-an-event).
To "refresh" the current page after a user update, you have to be more specific about what you require. The back() function that you use (or the aliases redirect()->back() or even app('redirect')->back()) is (to my knowledge) to be used in controllers and it uses the Referer header or a property in the user's session to determine to which page to send the client to. This is most often used with validation errors, so that you can send the user back to the page they came from along with any possible validation error messages.
Using back() (or any other request completions like return response()->json('mydata')) inside events is wrong and it doesn't even work since the result of such events is not being used to complete the request. The only valid thing you "could" do is to try validation inside an event, which in turn could throw ValidationExceptions and is therefore automatically handled.
What you should do is use the controller method that actually handles the request that updates the user:
// UserController.php
/** (PUT) Update a user */
public function update(Request $request, User $user)
{
if($user->update($this->validate($request, [/* validations */])) {
return redirect()->back();
// or even be explicit and use `return redirect()->route('users.show', $user);`
}
// `update()` returned false, meaning one of the model events returned `false`
// (there is no exception thrown here).
session()->flash('alert-info', 'Something went wrong');
return redirect()->back();
}

How to properly forward parameters from a POST result and avoid refresh (re-submit), with Laravel 5?

This is a basic issue, when submitting and performing a post, you normally want to avoid giving the user the chance to re-iterate the submit by refreshing or going back and forth with browser history.
(Backend re-submit, controls and checking is not questioned here. Of course they should be in place for security)
My solution was to have in Laravel web routes defined a post and a get route.
Like:
Route::post('/action', 'ActionController#doAction')->name('do.action');
Route::get('/action', 'ActionController#doActionConfirm')->name('do.action.confirm');
In ActionController something like:
public function doAction(Request $request)
{
....
return redirect()->route('do.action.confirm', [ 'data' =>
base64_encode(json_encode([
'action_id'=> $action_id,
'sent_to'=> $email,
'sent_success'=> $sent_success,
'sent_errors'=> $sent_errors,
]))]);
}
....
public function doActionConfirm(Request $request)
{
return view('confirmation')->with('data',$request->input('data'));
}
Then in my confirmation.blade.php get that $data decoded and displayed.
Is this the correct way to do it with Laravel?
What I don't like here:
is there's a better and more elegant way to forward data from the redirect()
is there a better way to manage get parameters to the GET route just to avoid people understanding and trying to inject unwanted data to the confirmation blade? (even if they will obtain nothing but no-sense views..because the page is doing nothing, it's simply displaying data in HTML blade)

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.

Laravel - Use Class like Auth

I have a Class Post. Created the Model, Restfull Resource Controller.
Now i implemented the show function in my Resource Controller.
So if someone routes to /post/234234 he will automatically see the post.
But now I want to create a new static function on myself. Let's call it myFunction(). I don't like to hand over the id all the time. Isn't there a possibilty to create a object or something like that, so I can use this like that Post::myFunction(), without hand over the id all the time.
It's similar to the Auth Class. I mean I can check if the user is logged in just like that Auth::check().
Update
Let's describe it more clearly. This is my PostController#show:
public function show($id)
{
//Get board information
$post = Post::find($id);
//Return view
return view('post')->with(array(
'posts' => $post
));
}
It shows just the post. In my view I have a button called Follow up. I only want to show it, if he didn't follow up the post yet. Now i thought about to edit the Model Post.php and add a static function followed() so i can just do this in the view:
#if(Post::followed())
<button>Follow up</button>
#endif
Yes. You can simply create a static function:
public static function myFunction(){
}
Just note that this function will be called in static context so you there's no $this available.
Alternatively you can create a Facade (Auth is a Facade). The process is described pretty well in the documentation about facades
As for your specific case I don't even think a static method is needed. Since you pass $post to the view you can just add a regular public method:
public function isFollowing(){
}
And then do this in your view:
#if(!$post->isFollowing())
<button>Follow up</button>
#endif

CakePHP validation error messages - how to pass them around?

Please note: I'm not trying to do this anymore, because I found an alternative, but it may be useful in the future to know the answer.
I have a form that is in a view (index.ctp) associated with the index() action on a controller. That form should post data to another action, contact(), in the same controller. This second action doesn't have a view, it's just to process the information and redirect the user according to the outcome. This action is doing the validation and redirecting the user to the referer (index in this case) in case of an error, and then the error should be displayed in index. Note that the model doesn't use a database table, but it's used only to define validation rules.
The validation is taking place correctly and reporting the expected errors. In order to retrieve the errors after the redirect, it writes the $this->ModelName->invalidFields() array to a session variable that is retrieved on the index() action after the redirection.
This array is passed on to the $errors variable to the view. Now comes the problem. The errors, although being passed correctly between redirects, aren't getting attached to the respective forms. How can I accomplish this? The form has all the conventional names, so it should be automatic, but it isn't.
Here's part of the relevant code:
Index view:
echo $this->Form->create('Contact', array('url' => '/contacts/contact'));
echo (rest of form) ...
echo $this->Form->end(__('send message', true));
Contacts controller:
function index() {
if ($this->Session->check('Contact.errors')) {
$this->set('errors', $this->Session->read('Contact.errors'));
}
}
function contact() {
if (!empty($this->data)) {
$this->Contact->set($this->data);
if ($this->Contact->validates()) {
(send the email)
}
else {
$this->Session->write('Contact.errors', $this->Contact->invalidFields());
$this->redirect($this->referer);
}
}
}
I don't think it's a good idea to write the validation errors in a session variable. I'm no CakePHP expert, but I don't think that's the way you are supposed to do it. All your forms should point to the same url you are on, so the data that the user has entered will not be lost.
Could you add some code to your question?

Resources