send variable from route::post to route::get in laravel - php

I am new to laravel and actually never used it before
I have a showForm.blade.php where the form is present whose post request is transferred to route web.php
get route
Route::get('/', function () {
return view('showForm',['na'=>'']);
})->name("start");
post route
Route::post('/upload', function (Request $request) {
if($request->file("thing")=="")
{
// return back()->withInput();
return redirect()->route('start');
}
else
{
$name=$request->file("thing")->getClientOriginalName();
Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
$url=Storage::disk('google')->url($name);
$details=Storage::disk("google")->getMetadata($name);
$path=$details['path'];
DB::insert('insert into books (Title, Url, FileId) values (?,?,?)', [$name,$url,$path]);
return redirect()->route('start');
}
})->name("upload");
I want that in post route
when if condition becomes true then along with redirecting to get route, it sends a variable $msg="insert data"; and when else condition becomes true, it sends a variable $msg="success upload"; which the get route will receive and use it in
return view('showForm',['na'=>$msg]);
to return the msg to the showForm.blade.php
how can I do this?
I have read that we can send the parameters by
return redirect()->route('start',['varaiable'=>'value'])
but where to specify that variable in get route so that can use it inside for the message so that the user will receive a different message according to the situation.

I see. It seems like you want to flash the message insert data after redirecting to another route. In that case, you can use the with method.
return redirect()->route('start')->with('message', 'Insert Data!');
Now this message will be kept in the session. On the start route blade template, you can do something as follows -
#if (session('message'))
<h1>{{ session('message') }}</h1>
#endif
The message should show up. Once you refresh the page, it'll go away. Read the official docs for HTTP Session if you want to learn more.

try this:
<?php
namespace Emedico\Http\Controllers;
use Session;
use Redirect;
public function upload(Request $request)
{
return Redirect::route('start', [variable => val];
}

Related

url parameter - laravel

our users access our site with a unique parameter on the url. ie http://example.com/hire-agreement?u=unique_param
I've set up a route to a view -
Route::get('/hire-agreement', function () {
return view('hire-agreement');
});
I have 2 questions.
Do I need to add anything else to the Route to allow the parameter to be read in the view?
How do I read this parameter value in the View? Can I use $_GET["name"]) ?
thanks
Craig.
you don't need anything more in the url section. and to use or get url parameter use laravel request() helper.
$value = request('key');
in view you can print a key like
{{ request('name') }}
complete example for you using request helper
Route::get('/hire-agreement', function () {
$name = request('name'); //put the key in a variable
return view('hire-agreement', compact('name')); //send the variable to the view
});
and then in view you can use the variable as
{{ $name }}
if you don't want to use a variable you can use directly request helper in view
{{ request('name') }}
you can use Request class too.
Route::get('/hire-agreement', function (Request $request) {
$name = $request->name;
return view('hire-agreement', compact('name'));
});
however i would suggest you to use a controller. don't use closure in route file. u can't cache them when needed.
http://example.com/hire-agreement?u=unique_param
in laravel you can access both post and get can be access by Request class instance or request() helper so you can do
with helper request()
Route::get('/hire-agreement', function () {
dd(request('u')) // this getting from url ?u=unique_param this u param
return view('hire-agreement');
});
with Class Request
or
Route::get('/hire-agreement', function (Request $request) {
dd($request->u)) // this getting from url ?u=unique_param this u param
return view('hire-agreement');
});
here you can
You better pass the request to a controller and handle it there, it's easier and cleaner that way.however if you want to got straight from route to view, you better use the below method.
put this in your route file
Route::get('/hire-agreement/{param}', function ($param) {
return view('hire-agreement')->with($param);
});
in the view you can access the param like this
<p>{{$param}}</p>
now if user request "/hire-agreement/1234" your $param in the view will contain 1234, Also if you would like to access get parameters in the url you can do it like this
{{Request::input('q')}}

Laravel route when where condition is false

I have the next code:
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return view('users.list',compact("lang","class"));
})->where('class', '[a-z]+');
Route::get('/{lang}/user/{user}', function ($lang,$user) {
return view('users.user',compact("lang","user"));
});
When condition in where is false, how can I send it directly to 404 when sort-by- is for example a number? The problem is that it goes to secondary route as an user.
For example:
/en/user/sort-by-name is ok
/en/user/sort-by-4446 must show 404 page
I know that i can do another route just between them with
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return \Response::view('errors.404',array(),404);
})->where('class', '.*');
but this seems ugly, i would like in same sentence
Basically, you may do this
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
if (is_numeric($class)) {
abort(404, 'Your reason');
}
return view('heros.list',compact("lang","class"));
});
Though, using closures in routes is a bad practice because they cannot be serialized in production mode. That's why you should use a controller to return your view, and assign a middleware to this route which will check your class and abort the request if needed.

Laravel does not return data to the view

My Laravel-5.4 project was working fine. but now it's driving me crazy when trying to return data from controller to the view:
Requested url is :
Route::middleware(['web'])->group(function () {
Route::prefix('service')->group( function () {
Route::get('{service_slug}', 'ServiceController#findBySlug')->name('service.find_by_slug');
});
});
Controller action is as below:
function findBySlug ($slug)
{
return back()->withMessage('test message');
}
Here in the blade view i can not catch $message variable, in fact there is no $message variable in the view.
#php
if (isset($message))
dd($message);
#endphp
How can i fix it?...thanks.
You are redirecting. You are 'flashing' data to the session when you redirect 'with` data like that. You have to get it from the session.
Also there is nothing related to passing something from the controller to a view in your post.
Docs 5.4 - Responses - Redirecting with flashed session data

How to redirect different page from same controller function in laravel 5.2

I want to redirect 2 different page from this controller function along with value.Here is my code. It works but both of time url become same.what shuld I do?
//in routes.php
Route::post('/','mycontroller#check');
// in controller.php
public function check(Request $request)
{
$c_email = $request->email;
$c_pass=$request->pass;
$c_type=$request->select;
$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
if ($var) {
return view('farmer')->with('user',$var);
// return redirect('farmer')->with('user',$var);
}
else {
$msg="Invalid login";
return view('index')->with('show',$msg);
}
}
If you want to actually redirect u can use the redirect() helper as statet in the official docs https://laravel.com/docs/5.3/redirects
You can also pass data
redirect('/my-route')->with(['user' => $var]);
The passed data can then be accesses through the session helper
$var = session('user')
HOWEVER, it seems like you have major issues in your code. Your password does not seem to be encrypted. Also there's no reason to use plain sql instead of eloquent here.
The route that is shown in the browser is defined in your
Route::post('/','mycontroller#check');
If you just return different views, the route does not change. You need to redirect to other views.
If you redirect to other routes you will ofcourse need to add / define them.
Route::get('/my-route', function() {}); // or post etc.

Error when trying to return Redirect in Laravel

When I submit a form in Laravel, the following controller method handles it:
public function update($id)
{
//handle input
return View::make('generic.success', ["message" => 'Data submitted successfully!']);
}
This works fine. However, instead of returning a view like above I'd like to return a redirect, because when I return the view directly, reloading the page resubmits the form.
So I tried to do this:
public function update($id)
{
//handle input
return Redirect::to('/success', ['message' => 'Data submitted successfully!']);
}
In my routes file I defined the success route:
Route::get('success', 'NotificationsController#success');
And set up a notification controller to display the view:
class NotificationsController extends BaseController {
public function success($message)
{
return View::make('generic.success', ["message" => $message]);
}
When I run the above code, I get the following error from Laravel:
InvalidArgumentException
The HTTP status code "1" is not valid.
I have no idea what this is supposed to tell me, and neither does Google apparently.
Can someone shed some light on this issue?
P.S.
Incidentally, being new to Laravel, I've noticed so far that Laravel's error reporting is very user-unfriendly, in that instead of telling me I have an issue with my router, or controller, or permissions, it displays these generic errors with no humane explanation of their cause. Is there a better way to troubleshoot problems in Laravel than relying on this?
For example, in the above incident, the error report points to this line of code...
public function setStatusCode($code, $text = null)
{
$this->statusCode = $code = (int) $code;
if ($this->isInvalid()) {
throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
}
...which is completely useless, as all it does is show me the code that printed the error itself.
The second parameter of the redirector's to() method is the HTTP status code that will be returned by the response, not data that will be passed along. Passing data when redirecting to GET routes can be done either via the query string or the session. The recommended solution here is to pass data via the current session using the with() method which passes that data for the next request. So in your case this would be the approach needed:
public function update($id)
{
return Redirect::to('/success')->with('message', 'Data submitted successfully!');
}
Then in your success method you can have this:
public function success($message)
{
return View::make('generic.success', ["message" => Session::get('message')]);
}
When in doubt always try checking the documentation first. The solution to this is explicitly stated in the Laravel Response Redirects Documentation.
Thanks a lot -Bogdan I found in the documentation that you post answer to my problem. In my case the solution was redirect to an action in a controller, like this...
return
\Redirect::action(
'PqrController#solicitud',
array($id)
)
->with(
'message',
'¡El estado de la solicitud ha sido actualizado correctamente!'
)
;
I redirect to a method in a controller, with one parameter array($id) and I put too in the session a message using ->with('message','Mensaje')

Categories