Session Flash Messages not showing anywhere despite coding - validation

I am following strict practices as per 5.2 docs, yet the validation is driving me insane.
1) This is a code snippet that I have in the controller right after the $property->save(); function
Session::flash('success', 'property table filled');
Session::flash('errors', 'These are the errors');
etc
Second issue is that the Validate method, if there are errors, it reverts back to the Create Form Page, but instead of binding the existing data in the Fields, it wipes everything out, so that I have to start the Form from scratch. Besides, it does not display any error messages
public function store(Request $request){
$this->validate($request, array(
'country' => 'bail|required|max:100',
'region' => 'bail|required|max:100',
etc
According to the documentation, this alone should, in case of fail to pass, revert back to the Create method above (the one that shows the Form to Create the Post) and issue a set of errors.
Since I am using a Resource Controller, all of the Routes are included in one line, and also, all of the Controllers and stuff are inside the Web Middleware:
Route::group(['middleware' =>'web'], function(){
Route::auth();
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
Route::resource('property', 'PropertyController');
});
This is the flawless snippet I have in the partials which is included in the Layout, so that it will display messages (success or fail) for every page that has a session:
#if(Session::has('success'))
<div class="alert alert-success" role="success">
<strong>Success: </strong> {{Session::get('success')}}
</div>
#endif
<div class="row">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
If instead, the storing of the data in the table database was successful, it still won't echo out any success flash session message.
Question:
Were there any errors in the submitted data, why doesn't display anything and why does it empty me all of the fields. The effect of emptying the fields is the same thing that would happen not when you refresh the Page, (filled fields stay filled) but when you click and press in the URL box of the browser.

Well, this is one of the cases where you get the answer but you dont know exactly why it works.
While I already had the Resource Controller Method inside the Web Middleware in the routes file, it turns out that I did not have to place the (or rather it was not enough) this:
Session::flash('success', 'property table filled');
Session::flash('errors', 'Posting failed');
in the Property Controller (and then this controller inside the Web Middleware in the Routes File), but actually those two lines on their own right in there in th Routes File
Session::flash('success', 'property table filled');
Session::flash('errors', 'Posting failed');
This is so much so that if I remove them from the Controller, this still works, but if I remove them from the Routes File, it doesn't.

Related

laravel POST request not rendering

Below is the auth part of my routes.
I just added the Tags part (where I can add another tag to the DB).
the tag creation works but the creation of a new post doesn't work now (worked before).
When I "submit" a post, it doesn't redirect or submits anything and it refreshes me back to the post create form with empty fields like nothing was rendered.
I tried to play with the positions of the routing, I made the post creation work but than the same happened to the tag creation where the page was "submiting" but actually there was no submit and it didn't redirect afterwards.
Auth::routes();
Route::get('/posts', 'PostsController#index')->name('posts.index');
Route::middleware('can:isAdmin')->group(function () {
Route::get('/posts/create', 'PostsController#create')->name('posts.create');
Route::get('/posts/{post}/edit', 'PostsController#edit')->name('post.edit');
Route::put('/posts/{post}', 'PostsController#update');
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store');
});
Route::get('/posts/{post}', 'PostsController#show')->name('posts.show');
thanks in advance.
At first, in given configuration you have two routes for same method / URI combination, so one of them would be unreachable:
// here the first
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store'); // <-- here the second
Looks like your post form submit goes to the tags, than validation fails and it redirect you back to post create page. Do you display validation errors?
here is example - https://laravel.com/docs/5.8/validation#quick-displaying-the-validation-errors
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
If it refresh your page so probably it works but if it do not save your request to databse it means that your request not validate respect to table.
Use validation for understand the errors.

Laravel: How to log errors in form request input

I am using Laravel's form request to validate some complex input. If there is an error, Laravel returns the user to the previous page (which is fine), but I also want it to log the errors for me. How do I do that?
I attempted to use the form's withValidator method as follows, but got an error re 'maximum nesting level reached'.
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->fails()) {
foreach($validator->errors()->all() as $error) {
logger($error);
}
}
});
}
Calling $validator->fails() in the after callback will end in an endless loop as it calls $validator->after() in the process. It re-evaluates and does not use a previous result.
Use $validator->errors() instead and check if it is empty.
Best way to validate on laravel is to use Laravel Request
As mentioned in the Laravel Documentation,
If the incoming request parameters do not pass the given validation rules, Laravel will automatically redirect the user back to their previous location.
In addition, all of the validation errors will be present in the $error variable.
The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.
To view the errors, you can add the following snippet inside your view which is returned when the validation is failed:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Displaying Error or alert message in laravel

I am new to Laravel. I want to display alert message. But i cannot display alert message once i hit url with localhost/social/alert. Please help me
Just a quick observation, which url do you intend to visit?
Is it localhost/social/alert or localhost/alert?
Also, try this
#if (session('info'))
<div class="alert alert-danger">
{{ session('info') }}
</div>
#endif
Let me know how that works out for you.
So in laravel 5.2, the errors, cookies, csrf tokens and so on are handled in the web middleware.
There are two ways to go about it.
Move your code into the web middleware
Route::group(['middleware' => 'web'], function () {
//code goes here
});
Move the classes from the web middleware in the $middlewareGroups variable in app/http/Kernel to $middleware
I prefer the first one

message with redirection in laravel

I have application where I show list of all items from specified table. Then I have in this page link to create new record in database, where it redirect me to form page. After submit the form I want to redirect back to list of items with success message like f.e."Record was inserted". How to do it in laravel? I tried something like this , but this doesnt work:
Redirect::to("Homepage#list")->to('message', 'Record was inserted')
also I tried (but also it doesnt work):
Session::flash('message', 'Record was inserted')
and in blade:
Session::get('message')
You need to update your code to
Redirect::to("Homepage#list")->with('message', 'Record was inserted');
and add the code for the flash message in your View
#if(Session::has('message'))
<div class="alert alert-success"><em> {!! session('message') !!}</em></div>
#endif

Laravel Sub-menu Within View

Hi I am very new to Laravel and MVC frameworks in general and am looking to create a list of links (in a view within a template) that links to some content. I am using this to display a list of nine people and to display their profile description when the link is clicked on. I have created a model of what the page looks like at http://i.imgur.com/8XhI2Ba.png. The portion that I am concerned with is in blue. Is there a way to route these links to something like /about/link2 or /about?link2 while maintaining the same exact page structure but modifying the ‘link content’ section (on the right of the link menu) to show the specific link's content? I would greatly appreciate it if someone could point me in the right direction, as I have literally no clue where to go with this!
There are a couple ways you can go about doing this.
Templates
Create your route.
Im assuming a lot about your app here but hopefully you get the picture. If you need help with anything in particular, be sure to update your question with the code youve tried so it will be easier to help you.
Route::get('about/{page}', function($page)
{
$profile = Profile::where('name', $page)->first();
return View::make('about')->with('profile', $profile);
});
Modify Template.blade.php
Put this line where you wish for About.blade.php to appear.
#yield('content')
Create your view which will extend your template
#extends('Template')
#section('content')
<h2>User Profile</h2>
<ul>
<li>Name: {{ $profile->name }}</li>
<li>Last Updated: {{ $profile->updated_at }}</li>
</ul>
#stop
AJAX
This solution will utilize AJAX to grab the data from the server and output it on the page.
Route for initial page view
Route::get('about', function($page)
{
$profiles = Profile::all();
return View::make('about')->with('profiles', $profiles);
});
Feel free to follow the same templating structure as before but this time we need to add some javascript into the template to handle the AJAX. Will also need to id everything which needs to be dynamically set so we can easily set it with jquery.
#extends('Template')
#section('content')
<h2>Links</h2>
#foreach($profiles as $profile)
{{ $profile->name }}
#endforeach
<h2>User Profile</h2>
<ul>
<li>Name: <span id="profile_name">{{ $profile->name }}</span></li>
<li>Last Updated: <span id="profile_updated_at">{{ $profile->updated_at }}</span></li>
</ul>
<script>
function setProfile(a)
{
$.ajax({
method: 'get',
url: 'getProfile',
dataType: 'json',
data: {
profile: $(a).data('id')
},
success: function(profile) {
$('#profile_name').html(profile.name);
$('#profile_updated_at').html(profile.updated_at);
},
error: function() {
alert('Error loading data.');
}
});
}
</script>
#stop
Route to handle the AJAX request
Route::get('getProfile', function()
{
$profile_id = Input::get('profile');
$profile = Profile::find($profile_id);
return $profile->toJson();
});
Now, the page should not have to reload and only the profile information should be updated.
Making some assumptions here as no code posted and assuming you're using the latest version of Laravel, Laravel 5.
Lets say you have a table in your database named users and you have a Model named Users (Laravel 5 comes with the Users model as default, see app/Users.php). The users will be the base of our data for the links.
Firstly, you want to register a route so you can access the page to view some information. You can do this in the routes file. The routes file can be found here: app/Http/routes.php.
To register a route add the following code:
Route::get('users', ['uses' => 'UserController#index']);
Now what this route does is whenever we hit the URL http://your-app-name/public/users (URL might be different depending on how you have your app set up, i.e. you may not have to include public) in our web browser it will respond by running the index method on the UserController.
To respond to that route you can set up your UserController as so:
<?php namespace App\Http\Controllers;
class UserController extends Controller {
public function index()
{
}
}
Controllers should be stored in app/Http/Controllers/.
Now lets flesh out the index method:
public function index()
{
// grab our users
$users = App\Users::all();
// return a view with the users data
return view('users.index')->with('users');
}
This grabs the users from the database and loads up a view passing the users data.
Here's what your view could look like:
<!DOCTYPE html>
<html>
<head>
<title>Users Page</title>
</head>
<body>
#foreach($users as $user)
<a href="{{ URL::route('user', ['id' => $user->id]) }}">
{{ $user->username }}
</a>
#endforeach
</body>
</html>
The view code will loop through each user from the $users data we passed to the view and create a link to their user page which is different for each user based on their id (their unique identifier in the DB)
Due to the way I've named it, this would be found in app/views/users/index.blade.php - if you save files ending in blade.php you can use Laravel's templating language, blade.
Now you need to finally set up another route to respond to a user page, for example http://your-app-name/public/user/22.
Route::get('user/{id}', ['uses' => 'UserController#show']);
Then add the show method to UserController
public function show($id)
{
// this will dump out the user information
return \App\User::find($id);
}
Hope that helps a little! Wrote most of it off the top of my head so let me know if you get any errors via comment.
This question is very bare, and it is difficult to actually help your situation without you showing any code. Just to point you in the right direction though, here is what you would need.
A Model called People, this is how you will access your data.
A controller. In this controller you will do the following
Get the ID of the profile you want from the functions parameters
Find that persons information e.g. People::find($person_id);
return the profile view with that persons data e.g. return view('profile')->with('person', $person);
In your view you can then use that data on that page e.g. {{ $person->name }}
For the page that needs to display the links to the people you would have a method in your controller which..
Get all the people data e.g. People::all();
Return a view with that data return view('all-people')->with('people', $people);
You will then need a route to access an individual person. The route will need to pass the persons ID into a controller method e.g.
Route::get('get-person/{id}',
[ 'as' => 'get-person',
'uses' => 'PeopleController#getPerson' ]);
You can then use this route in your view to get the links to each person
#foreach($people as $person)
{{$person->name}}
#endforeach
This would produce the list of links you want.

Resources