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.
Related
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];
}
I'm trying to make a button appear when a user log in. If the user isn't log in, the button wouldn't appear on the page. So the first thing i need is to determine if the user has log in or not. The problem is, The Auth::check() keeps returning null. I've done research that we should put the route inside the Auth middleware, but in doing so, users would have to log in to see the page and i don't want that. I want the users to be able to see the page without login and when they do login, a button will appear on the same page.
Component
<button v-if="showBtnDelete==true" class="btn btn-danger">Delete</button>
<script>
getUserType(){
axios.get('api/gallery/getUserType').then(res=>{
this.showBtnDelete = res.data;});
},
</script>
Controller
public function getUserType()
{
if(Auth::check()){
return 'true';
}else{
return 'false';
}
}
Web.php
Route::group(['middleware' => ['auth']],function(){
Route::get('/add-image', function () {return view('layouts.master');});
});
Auth::routes();
Route::get('/logout','Auth\LoginController#logout');
Route::get('/', function () {
return view('home');
});
Route::get('{path?}', function () {
return view('layouts.master');
})->where('path', '[\/\w\.-]*');
guard API or web
Auth::guard('api')->check();
Auth::guard('web')->check()
You're returning 'true' and 'false' as strings which both returns true when non strictly compared and false when strictly compared
echo 'false' == true; // true
echo 'false' === true; // false (not same data type)
And vice versa...
Now Auth::check() naturally returns a boolean so the if, else statement is redundant all together...
You can use the helper method to use each guard when needed
public function getUserType()
{
return auth()->check();
}
If anyone has the same problem. The problem is that your route is not protected by the middleware group web.
That means it will not be able to retrieve the session of the current user so the Auth facade will always return null.
Add middleware('web') to the route accessing the method (code) and you will be able to retrieve the current user if logged in.
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')
I am learning laravel 4.
The code of my route file:
Route::post('user/admin', 'UserController#admin');
Route::get('user/login', 'UserController#login');
Route::resource('user', 'UserController');
Route::get('/', function()
{
return View::make('home');
});
The code of my controller:
public function admin() {
$msg = Usr::get_data();
if ($msg == "pass") {
return View::make('user.admin');
} else {
return Redirect::to('user/login');
}
}
There is no problem when i use Redirect::to, but if i change to Redirect::route, it said route [user/login] is not defined. But I already defined it in the routes.php. Why Redirect::() does not work, and what is the difference between them?
Redirect::route is for a named route whereas Redirect::to is for any internal redirect. None of the routes you've added are named, so you cannot use Redirect::route to refer to them.
Redirect::to retrurns a redirect with the flash data
An example from the documentation
return Redirect::to('user/login')->with('message', 'Login Failed');
While Redirect::route Returnns A Redirect To A Named Route.
return Redirect::route('profile', array(1));
Check the documentation.It will make you understand better.
Edit:
Redirect::route() can redirect with a flash data too.
I know that to handle 404 errors with laravel 4 is to write at app/start/global.php :
App::missing(function($exception)
{
return Redirect::route('404_Error');
});
But actually I want to use this route:
Route::get('error', array(
'as' => '404_Error',
'uses' => 'ErrorController#get404Error'
));
But to stay at the same URL.
Example:
My URL right now is localhost:8000/users/blat (404 Error). I don't want redirect to error page. I want to see ErrorController#get404Error at this URL.
Thanks so much.
You may try something like this:
App::missing(function($exception)
{
return App::make('ErrorController')->get404Error($exception);
});
Your ErrorController:
class ErrorController extends BaseController {
//...
public function get404Error($exception)
{
//...
$data = ...;
return View::make('error_view')->with('data', $data);
}
}
If you use a different route it will redirect to that route, you probably will need to render your view right away, IMO it's the only way to stay where you are and not have your url changed:
App::missing(function($exception)
{
return View::make('404_Error');
});
You can just create an instance of the ErrorController class and call its get404Error method. That way you will have the variables from your BaseController class too and the route will stay the same.
App::missing(function($exception)
{
$errorController = new ErrorController();
return $errorController->get404Error();
});