I have a custom middleware that edits requests like this:
public function handle($request, Closure $next)
{
$profileLocal = ProfileLocal::where(
'id', JWTHelper::tokenExtractProfileLocalID($request->token)
)->with('status')->first();
if (empty($profileLocal) || $profileLocal->status->email_verified == 0 || $profileLocal->status->blocked == 1) {
return $this->respondError('You dont have access to this store', 336);
}
$request->profileLocal = $profileLocal;
return $next($request);
}
However, when i try to access $request->profileLocal In my controller:
public function deviceSet(DeviceRequest $request)
{
dd($request->profileLocal);
}
I get null returned even though in my DeviceRequest if i try to dd(request()->profileLocal) it works fine?
Does anyone know what i may be doing wrong here?
I have noticed that if i use request()->profileLocal in my controller it works as expected
If you want to add add a value to the request and be able to access it as a property you can add it to the underlying request property:
$request->request->add([
'profileLocal' => $profileLocal
]);
// or $request->request->add(compact('profileLocal'))
Then you'll be able to access the value in your controller with:
$request->profileLocal
This value will also be included when you call methods like all() or input().
I was told that if I use:
$request->attributes->add(['profileLocal' => $profileLocal]);
In my middleware and then access it using:
$request->attributes->get('profileLocal')
It works, I dont know if this is the correct way though.
Related
im using laravel 7
and im using gates and policies
i have api controller called Journal_entries_controller
and i have index function
public function index()
{
$journal_entries = Journal_entry::with('get_journal_entry_lines')->get();
return response()->json($journal_entries,200);
}
like this everything working so good ..
to check gate i did this ..
public function index()
{
$auth = auth('api')->user();
if(!Gate::allows('journal_entries.view',$auth))
return 'not auth';
$journal_entries = Journal_entry::with('get_journal_entry_lines')->get();
return response()->json($journal_entries,200);
}
like that i get not auth the code stop there
and if i dd($auth) i gat the logged user like this ..
public function index()
{
$auth = auth('api')->user();
dd($auth);
}
any help here thanks ..
In the if statement:
if(!Gate::allows('journal_entries.view',$auth))
return 'not auth';
The Gate::allows is returning false by adding the ! we make the response true which is why the not auth code is returning.
The first thing to do is make sure the journal_entries.view is a gate in the App\Providers\AuthServiceProvider.
If it is a valid gate please post the contents of the gate so we know the intended functionality.
In the mean time you may want to try changing
if(!Gate::allows('journal_entries.view',$auth)) to if(Gate::denies('journal_entries.view',$auth)) or
if(Gate::allows('journal_entries.view',$auth))
The docs for gates can be found here https://laravel.com/docs/7.x/authorization#authorizing-actions-via-gates
I wrote localisation helper in laravel which checks whether en, fr or another local is in the URI.
If no locale is supplied config("app.locale") should be prepended to the original URI and a redirect should be made to this new URI. I.e. /user should be redirected too /en/user.
I am currently trying to resolve this problem by using:
public function handle($request, Closure $next, $guard = null)
{
$langSegment = $request->segment(1);
// if first segment is language parameter then go on
if (strlen($langSegment) == 2 && ($langSegment == 'en' || $langSegment == 'fr')) {
App::setLocale($langSegment);
return $next($request);
} else {
$newURL=url(config("app.locale") . "/" . implode("/",$request->segments()));
return redirect($newURL);
}
}
This works fine for most request unless the method is POST and there is no $language set. When this is the case the user is redirect but the method is changed to a POST request.
I also tried changing my redirect to
return redirect()->route('routeName', $request->all(), 302, ['method','POST'])
But this also doesn't work.
So I did some testing with regards to the HTTP status code 307.
Let me first describe my test setup, I created the following routes:
Route::get("/help", 'HelpController#index');
Route::post("/post", 'HelpController#post');
Route::post("/redirected", 'HelpController#redirected');
The HelpController contained the following code:
<?php
namespace App\Http\Controllers;
class HelpController extends Controller
{
public function index(){
return view('help');
}
public function post(){
return redirect('/redirected', 307);
}
public function redirected(){
echo "Success";
}
}
and help.blade.php was a very basic form namely:
<form method="post" action="/post">
#csrf
<button>Go</button>
</form>
I am glad to report that a 307 return code does successfully keep the POST method.
I.e. when I went to the /help url and pressed the "Go" button I saw the "Success" message as expected.
What does this mean for me you might ask?
Well we can solve your problems with a very simple change:
return redirect($newURL);
becomes
return redirect($newURL, 307);
Wasn't that easy in the end?
Furthermore as you can see in my test setup this also keeps the crsf protection which is a definite plus from a security standpoint.
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 have a url www.mywebsite.com/store/123456
where store is my controller class and I have a index function in it where Im getting the value after after store ,ie 123456.But im not able to achieve it.
As found online,I have tried adding this to routes $route['store/(:any)'] = 'store/index'; also tried
$route['store/(:any)'] = 'store/index/$1';
but doesn't seem to work.Please help me out.
In controller index function is
public function index()
{
echo $this->uri->segment(1);
}
But its not working.Pleae help
You are invoking 123456() method instead of index() method therefore you get CI's 404.
The simplest way is to use this kind of route
$route['store/(:any)'] = 'store/index/$1';
AND in top of it add parameter to index function in your case
public function index($parameter)
{
echo $this->uri->segment(2);
}
note that I changed segment parameter please see documentation.
using _remap()
function _remap($parameter){
$this->index($parameter);
}
function index($p)
{
echo $p; //shows 123456
}
If I remember correctly:
segment(n) gives you the segments of your uri before the routing takes place
rsegment(n) gives you the segments of your uri after routing (if routing occurred or the same as segment if it didn't)
so for /store/123456 getting rerouted to /store/index/123456
segment(1) == rsegment(1) == 'store'
rsegment(2) == 'index'
segment(2) == rsegment(3) == '123456'
Route:
$route['terms_and_conditions'] = 'SO_front/page/1';
controller :
public function page($id)
{
echo $id;
}
Output :
1
Here my solution for CI3...i would prefer laravel for advanced routing, orm,restapi, build in vuejs.
$route['store/(:any)'] = 'store/index/';
public function your index(){
$parameter=$this->uri->segment(2);
//use parameter for sql query.
}
Let say your route $route[store/product/update/(:any)] , then $parameter=$this->uri->segment(4)
Problem?. You will need to change entire file code if you plan to change the route name include view, controller, and custom route.
Am not able to call a controller function from my view
This is my view code
echo "<a href='".$base_url."/qst/d/".$row['id']."' class='btn linkcolor'>DENY</a>";
which calls a controller qst and a function deny in it
here is my controller code
public function _remap($method, $params = array()) {
if ($method == 'd') {
$this->deny();
}
}
public function deny($id){
}
am getting the error undefined varaible id.
also am getting Missing argument 1 for qst::d
can anyone tell me what's missing in the code so that it works?
Why not just use routes? In application/config/routes.php, add:
$route['qst/d/(:num)']= 'qst/deny/$1';
Your link only has /d/ for the method name, shouldn't this be /qst/deny/?
EDIT: Also, perhaps you should set a default for the ID and then check to see if the ID is default. (Perhaps null and an is_null check?) Have you var_dump'ed something within the deny method to verify that is the method running?