Laravel adding an alert to a view - php

I am trying to add an alert/warning to a view but displaying nothing. I can get my alerts to work with a redirect but wondering how to do it with a view that passes data. Is there a way to pass an alert to a view or is there a "Correct" way of doing this?
$form = new Form();
$form->storeRequest($request);
$form->saveJson();
$form->loadForm($request->cuid, $request->cubaseName);
return view('layouts.pages.form', ['form'=>$form])->with('success', 'Form has been saved.');
//return redirect()->back()->with('success', 'Saved!'); <--this would work if i wasn't passing data

All Framework use a special method to send message from controller known as Flash message
In your controller
$request->session()->flash('success', 'Form has been saved');
And to access it on view
#if($message = Session::get("success"))
<h3 class="text-center text-success">{{$message}}</h3>
#endif
Laravel -> Http Session -> Flash Data

If you are looking for a neat way of doing something like bootstrap alerts, you should consider the laracasts/flash package by Jeffrey Way.
Documentation can be found here

Related

Laravel redirect after update uses PUT request

I have Laravel app with Vue on front end, and Vue calls update method from controller using PUT request.
Request works, model gets updated, but I have issue with redirecting as it is redirecting also as a PUT instead of simple GET?
public function update(MomentsValidationRequest $request, Project $project, Task $task, Moment $moment)
{
foreach($request->materials as $material){
$material_id_array[$material['id']] = ['quantity' => $material['quantity']];
}
$moment->update($request->all());
if(isset($material_id_array))
$moment->materials()->sync($material_id_array);
return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Moment updated!']);
}
So naturally, I am getting a method not allowed exception because it is redirecting to a route which is supposed to get a previous view only.
Route itself is fine, request method isn't.
For non-believers :)
Also a route:
I know this is a bit late. But incase anyone stumbles across this.
You state that you're using Vue in the front end. This would suggest that the put request is being made through an axios call.
I can't see this call, so this is only an assumption. But I believe the solution would be to return a json object instead of a response in the controller, and then redirect trigger a redirect from the Vue component itself.
In the controller:
Session::flash('alert-type', 'success');
Session::flash('message', 'Moment updated!');
return response()->json(true);
In the component:
axios.post('/moments', this.moment).then(() => {
window.location.replace("moments");
});
I believe this is something to do with how axios handles patch requests, it seems to attempt to handle a redirect response automatically, I could be wrong though, so any reply is welcome to if there's a better explanation.
You can use:
redirect()->back(303)->with(...)
No, redirection is made always with GET but you don't have such route defined. So you should create GET route that will do something with this.
It's possible only to redirect to GET routes.

How to use Basic Routing methods in Laravel?

I have get some documents from Laravel Documentation.But i can't get details clearly from that. There are lot of routing methods and how to use that for my requirements? Commonly most people are using this, but what are the other routing methods?
Route::get()
Route::post()
How to pass the message or values through this Routing? Using Controller like this is a only way?
Route::get('/app', 'AppController#index');
Types of Routing in Laravel
There are some Routing methods in Laravel, There are
1. Basic GET Route
GET is the method which is used to retrieve a resource. In this example, we are simply getting the user route requirements then return the message to him.
Route::get('/home', function() { return 'This is Home'; });
2. Basic POST Route
To make a POST request, you can simply use the post(); method, that means when your are submitting a Form using action="myForm" method="POST", then you want to catch the POST response using this POST route.
Route::post('/myForm', function() {return 'Your Form has posted '; });
3. Registering A Route For Multiple Verbs
Here you can retrieve GET request and POST requests in one route. MATCH will get that request here,
Route::match(array('GET', 'POST'), '/home', function() { return 'GET & POST'; });
4. Any HTTP Verb
Registering A Route Responding To Any HTTP Verb. This will catch all the request from your URL according to the parameters.
Route::any('/home', function() { return 'Hello World'; });
Usage of Routing in Laravel
When your are Using the Route::, Here you can manage your controller functions and views as follows,
1. Simple Message Return
You can return a simple message which will display in the webpage when user request that URL.
Route::get('/home', function(){return 'You Are Requesting Home';});
2. Return a View
You can return a View which will display in the webpage when user request that URL
// show a static view for the home page (app/views/home.blade.php)
Route::get('/home', function()
{
return View::make('home');
});
3. Request a Controller Function
You can call a function from the Controller when user request that URL
// call a index function from HomeController (app/Http/Controllers)
Route::get('/home', 'HomeController#index');
4. Catch a value from URL
You can catch a value from requested URL then pass that value to a function from Controller. Example : If you call public/home/1452 then value 1452 will be cached and will pass to the controller
// call a show function from HomeController (app/Http/Controllers)
Route::get('/home/{id}', 'HomeController#show');
You can get help about routing from Laravel.
There are 4 methods ofform data sending that you must know --
Route::get for <form method="GET">
Route::post for <form method="POST">
Route::put for <form method="PUT"> -- This one is for updating your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'PUT']) !!}, but in your web browser you can find the method as POST only
Route::delete for <form method="DELETE"> -- This one is for deleteing a field in your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'DELETE']) !!}, but in your web browser you can find the method as POST only
There are many much you have to know about Laravel Routing, like CRUD, etc.

Laravel Passing variable not working

Hello People here is my code i have used in controller...
public function bulk()
{
return View::make('bulk')->with('message','hii there');
}
my route file contains...
Route::get('bulk',array('uses'=>'HomeController#bulk'))->before('auth');
In my view Iam testing it by ...
#if(Session::has('message'))
Present
#else
not Present
#endif
The page is making a view with the message 'not Present' why is it??
I even tried
return Redirect::to('bulk')->with('message','hii there');
I get an erro mesage on Console
mypro/public/bulk net::ERR_TOO_MANY_REDIRECTS
What could be the problem?? is there any issues with name?? I tried this method earlier which worked fine for me.... :(
Iam using Blade Template..
You are confusing Redirect and View. You use Session::get to access variables passed to redirects. For views (as in your case), with will pass an simple PHP variable into your view. So your check should be:
#if(isset($message))
{{{ $message }}}
#else
No message!
#endif
Read more here
As per the docs, you need to access the "with" value in the view using a PHP variable, it's not passed via the session. In your case, that would be $message. If you want to use the session, you should use Session::flash() or Session::put().

Password reset routing laravel

The user receives the password reset url in the email which is of format http://example.com/reset/passwordresetcode. I have a route defined for this link as
Route::get('reset/{code}', function(){
return View::make('users.reset_password');
});
On clicking the link in the email, a view containing a form is rendered to reset the password. This form consists of email, password and password confirm fields and I plan to grab the passwordresetcode directly from the url. I have been able to get this passwordresetcode in my view.
Now to process the form post, I have the route defined as:
Route::post('reset', 'UserController#passwordReset');
How can I get the passwordresetcode in this controller action passwordReset? I know I can have a hidden field in my form to receive it on post, but it does not quite look the laravel way and surely there must be a better way. Kind of new to laravel :). Thanks
You could use a hidden input where you pass the code from your controller method to the view and this way the code will be posted with the rest of your form data to passwordReset on submit.
{{ Form::hidden('passwordresetcode', $passwordresetcode) }}
Or you could use a flash variable to temporarily store it in the session:
Session::flash('passwordresetcode', 'value');
And in your next controller method (passwordReset), simply retrieve it:
Session::get('passwordresetcode');
You can read more about flash variables in the official documentation.
Modifying the route defined for the post to
Route::post('reset/{code}', 'UserController#passwordReset');
did the trick. And in the controller, I can get the passwordresetcode by doing
public function passwordReset($code)
{
echo $code;
}
However if the validation fails, trying to redirect like
return Redirect::route('reset/'.$code)->withInput()
->withErrors($validation)
->with('title', 'resetrequestfailure')
->with('message', 'Seems like you made some errors.');
seems not to work. I tried using the named routes as well, that too did not work.

Laravel 4: What is the correct way to display data in a view?

Let me explain myself better.
For example, I have a page that does only one thing: it displays the username in a big nice font.
What is the correct way, and by "correct way" I mean the way that respects MVC, to implement that?
I thought that directly calling a method inside a model wouldn't respect MVC pattern, but calling a method of a controller through a new GET/POST request to the server would be kind of a waste because on more complex pages I should make too many calls.
I also read about the Laravel's View Composer but even after reading its documentation I'm still quite unsure about how that should be implemented.
If possible, in addition to my previous question, can I a have a simple example to help me understand better?
Basically this is the way you send information from your controller to your view:
Let's say you have a route that expects the user id via GET (HTTP REQUEST method):
Route::get('user/{id}', 'PagesController#showUserName');
It points to an action in your CONTROLLER (app/controllers/PagesController.php) that gets information from a repository (MODEL?) and sends to your VIEW:
class PagesController extends Controller {
public function showUserName($id)
{
$user = $this->userRepository->getUserById($user_id);
return View::make('userNamePage')->with('userName', $user->name);
}
}
And your VIEW (app/views/userNamePage.blade.php) just showing a big user name:
#extends('layouts.main')
#section('content')
<h1>{{$userName}}</h1>
#stop
The way you get the information to send to your view is entirely up to you, but you should not put too much login in your controller nor in the view, that's why I am using a repository, but you will see a lot of people taking information directly from the MODEL, which is acceptable for small applications:
$user = User::find($id);
Which is the same as doing:
$user = User::where('id', $id)->first();
or
$user = DB::table('users')->where('id', $id)->first();

Categories