I want to make boot function for my app preview, for that I have plan to add new variable to .env file and let's name it APP_Mode so I want to say:
If APP_Mode=preview prevent all actions and redirect back with
xxxxxx text as flash session message.
The point
The point of this boot action that I try to achieve is to not let users change any of my preview site settings like store/delete/update etc.
Question
Is that possible? How?
First off, might be worth considering if Laravel's maintenance mode might work for you - you can whitelist the IP addresses that are able to access the site, and it will appear down for everyone else.
If that's not going to do the trick, you'll probably be best to create your own middleware - it will likely be similar to the CheckForMaintenanceMode middleware that Laravel ships with. In the handle method you can check for the configuration option to see if you're in preview mode or not, and then decide how to handle the request.
If you're using "RESTful" routing like Laravel recommends - that is, GET requests are idempotent and don't change anything, and only POST/PUT/DELETE requests make changes - your middleware can simply return a HTTP 403 response (forbidden) if your preview mode is enabled and the request method isn't GET.
A very simple implementation (you'll likely need to tweak) to get you started would be something like this:
public function handle($request, Closure $next) {
if (config('app.mode') === 'preview' && $request->method() !== 'GET') {
abort(403);
}
return $next($request);
}
Just in regard to using config('app.mode') instead of something env('APP_MODE') is that you shouldn't be using the env helper outside of the configuration files - otherwise you can't take advantage of Laravel's config caching. So add another config option in the config/app.php file that you can use to check the mode the app is in.
Related
I have been working on a simple Laravel Inertia Vue3 application. It has one resource route.
Route::resource('contact', \App\Http\Controllers\ContactController::class);
This provides the named routes contact.index .store .create .show .update .destroy and .edit
Nice and simple so far.
I have a useForm form variable in my Vue component with some assigned variables
let form = useForm({ ... });
I have a submit method in the same component
let submit = () => {
if(props.edit) {
form.patch(`/contact/${props.contact.id}`);
} else {
form.post(`/contact`);
}
}
Again nothing complex. The post method fires off correctly and redirects
Contact::query()->create($request->all());
return redirect()->to(route('contact.index'));
For full disclosure of the update method, please see below:
public function update(Request $request, Contact $contact): \Illuminate\Http\RedirectResponse
{
$contact->fill($request->all())->save();
return redirect()->to(route('contact.show', ['contact' => $contact]));
}
This works in the same way as store. Simple and then redirects... but it doesn't.
What happens is that it runs the patch and then calls redirect
The redirect carries the patch method through ending up with a 405 if I use the index route (declared as get). If I use back() I get the same thing. If I use the show route, it redirects in a loop because the patch route uses the same URL /contact/{contact}
I have built Laravel applications for the last 5 years and have not had an issue like this before when using a named route. Have I missed something basic? If not its possibly a configuration issue although I am not sure what.
I am running Laravel 9.19 with webpack manually installed as its been changed to Vite on the current release. I have no Vue errors or warnings and no Laravel logs.
there is a difference between PUT and PATCH requests on laravel-level.
Please run php artisan route:list - and see which one is used in your case, There is a big chance that you using PUT, not patch :)
So good ol' Laravel got me again.
Alexander Dyriavin got me on the right course with his answer about put and patch, however, it wasn't really the solution.
The solution:
form.transform((data) => ({
...data,
_method: 'PUT' //spoof added to request
})).post(`/contact/${props.contact.id}`); //sent as a post instead
The Laravel docs allow you to spoof methods https://laravel.com/docs/5.0/routing#method-spoofing by posting them with a _method field.
Simply put, a patch or put request would have always failed with a redirect from Laravel. In the past I would have used them with Axios and handled a JSON response directly.
This time I really am answering my own question.
I was a total idiot and missed a step when setting up inertia js. I was attempting to retrieve errors with the useform method and what happened was I received nothing.
So I though I would double check the docs.
Turns out I missed adding this middleware to the web middleware group in the kernel!
\App\Http\Middleware\HandleInertiaRequests::class,
I can now use the .patch method I had before and no need for any additional code
First question was solved with findOrFail method
Is there any way to prevent users from checking non-existing routes?
Example
I've got route to http://127.0.0.1:8000/event/9
but event with id 8 does not exist, if user would go to that id there is a massage:
Attempt to read property "photo_patch" on null (View: C:\xampp\htdocs\Laravel1\resources\views\frontend\eventView.blade.php)
Or any other error from db that record does not exist.
Second question
How to turn on preety URLs in laravel
So my page with display http://127.0.0.1:8000 not http://127.0.0.1:8000/events something...
I know that its somewere in config files but I cant find it.
Example class and route that uses it:
-----------------------------Class----------------
public function eventView($id)
{
$notDisplay = Auth::user();
$eventView = Event::findOrFail($id);
if(!$notDisplay){
$eventView->displayed = $eventView->displayed +1;
$eventView->save();
}
return view('frontend/eventView', ['eventView' => $eventView]);
}
----------------Route-----------------
Route::get('event/' . '{id}', [App\Http\Controllers\FrontendController::class, 'eventView'])->name('eventView');
First off, use the container!
Laravel's service container is very powerful and your controller resolve use-case is one of the most common places you should be using it. The url argument and controller argument MUST match for this to work.
Your route:
Route::get('event/' . '{event}', [App\Http\Controllers\FrontendController::class, 'eventView'])->name('eventView');
Your Controller:
public function eventView(Event $event)
{
return view('frontend/eventView', ['event' => $event]);
}
When leveraging Laravel's dependency injection and container, you get your findOrFail() for free. You should also remove your auth check, and handle that with route middleware.
In terms of "prettifying" urls, Laravel's route model binding feature allows you to control what property of a model is used to for container resolution. For example, let's imagine your event has a unique slug you'd like to use instead of the auto-increment id:
Route::get('event/' . '{event:slug}', [App\Http\Controllers\FrontendController::class, 'eventView'])->name('eventView');
Laravel's routing functionality offers a fallback feature that would allow you to fine-tune where the user is redirected if the route model binding failed.
https://laravel.com/docs/8.x/routing#fallback-routes
With regard to preventing an unauthorized individual from editing someone else's event. The first place I would put protections in place would be at the time of persistence (when saving to the database). While you can do this in every place in your codebase where persistence occurs, Laravel's Observer feature could be a great fit. That way, you can be confident that no matter what code is added to your app, the ownership check will always be run before making any changes to events.
https://laravel.com/docs/8.x/eloquent#observers
The second place that I would put protections in place would be with a route middleware on any routes that can mutate the event. That way, you can redirect the user away from an event they don't own before they even have a chance to attempt to edit it.
https://laravel.com/docs/8.x/middleware#assigning-middleware-to-routes
I am trying to make the configuration for Pusher in my Laravel app (SaaS) dynamic.
Basically I want to store different Pusher configs for different accounts. And call the corresponding config based on the user.
I have tries to change the config in runtime using config()->set('services.pusher.xxx', 'yyyy'), but this doesn't work at any level of the framework, event in a custom ServiceProvider.
I found Laravel's BroadcastManager and tried to override the createPusherDriver() so that I could create a custom instance of PusherBroadcaster with the user's config, but I am not sure how to do that or where to put it!
What is the best-practice/standard way to do that?
I've been using a setup like this in one of my own projects, to set a custom mail config:
NOTE: Your mileage may vary due to the order in which service providers are loaded in your app.
Create a serviceprovider like app\Providers\ConfigProvider.php
public function boot()
{
$this->app->booted(function () {
$shouldSetCustomConfig = true;
// Set config values from database.
if($shouldSetCustomConfig) {
config([
'mail.host' => Config::get('mail.host'),
'mail.port' => Config::get('mail.port'),
]);
}
});
}
The $this->app->booted() is a simple callback that gets called after the application has been booted. This might not always work correctly because I've seen various packages that use this callback too to do various stuff. When this is the case, the order of registration matters. Note that it is not required to use this callback. One might simply call the config(['key' => 'newval']) directly and it could work as intended.
The service provider above should be loaded BEFORE the provider you are setting configuration for. In the example above it would be the Illuminate\Mail\MailServiceProvider::class. This should make sure the correct config is loaded.
I'm building enterprise modular Laravel web application but I'm having a small problem.
I would like to have it so that if someone goes to the /api/*/ route (/api/ is a route group) that it will go to an InputController. the first variable next to /api/ will be the module name that the api is requesting info from. So lets say for example: /api/phonefinder/find
In this case, when someone hit's this route, it will go to InputController, verifiy if the module 'phonefinder' exists, then sends anything after the /api/phonefinder to the correct routes file in that module's folder (In this case the '/find' Route..)
So:
/api/phonefinder/find - Go to input controller and verify if phonefinder module exists (Always go to InputController even if its another module instead of phonefinder)
/find - Then call the /find route inside folder Modules/phonefinder/routes.php
Any idea's on how to achieve this?
Middlewares are designed for this purpose. You can create a middleware by typing
php artisan make:middleware MiddlewareName
It will create a middleware named 'MiddlewareName' under namespace App\Http\Middleware; path.
In this middleware, write your controls in the handle function. It should return $next($request); Dont change this part.
In your Http\Kernel.php file, go to $routeMiddleware variable and add this line:
'middleware_name' => \App\Http\Middleware\MiddlewareName::class,
And finally, go to your web.php file and set the middleware. An example can be given as:
Route::middleware(['middleware_name'])->group(function () {
Route::prefix('api')->group(function () {
Route::get('/phonefinder', 'SomeController#someMethod');
});
});
Whenever you call api/phonefinder endpoint, it will go to the Middleware first.
What you are looking for is HMVC, where you can send internal route requests, but Laravel doesn't support it.
If you want to have one access point for your modular application then you should declare it like this (for example):
Route::any('api/{module}/{action}', 'InputController#moduleAction');
Then in your moduleAction($module, $action) you can process it accordingly, initialize needed module and call it's action with all attached data. Implement your own Module class the way you need and work from there.
Laravel doesn't support HMVC, you can't have one general route using other internal routes. And if those routes (/find in your case) are not internal and can be publicly accessed then also having one general route makes no sense.
I am developing web application using Laravel 5 and angularJs with RESTFUL apis.
Using middleware to authentication purpose. My problem is after sending few request simultaneously,system automatically logged out and sending 401 exception from laravel side.
API base controller:
class ApiController extends BaseController {
use DispatchesCommands, ValidatesRequests;
function __construct() {
$this->middleware('api.auth');
}
}
Middleware:
class APIMiddleware {
/**
* Handle an incoming request.
*
* #param Request $request
* #param Closure $next
* #return mixed
*/
public function handle($request, Closure $next) {
if (!Auth::check()) {
abort(401, "Unauthorized");
}
return $next($request);
}
}
Log in controller
public function login(LoginRequest $request) {
if (Auth::check()) {
Auth::logout();
}
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')], $request->input('is_remember'))) {
return array(true);
} else {
abort(401, "Invalid email & password");
}
}
After few request gone, Server log out and sends 401 exception. I am stuck with this issue.
Now I'm not 100% sure (and depending on your set-up I can't even say I'm 90% sure) But after changing my session_driver from file to database I seem to have fixed this issue - that is if it's the same issue.
I think do the samething as you with my app - that is on a start up of a page, I'm making 6 request (this is development and I will be changing it to one so please don't cry). If I load this page, it works with about 3 or 4 request, then the other 2-3 come back with a unauthorised response. It also only happens on request that require middleware => auth.
So here's my theory to why this is happening: Because, by default, sessions are saved in a file - making multiple requests at once means that file is being opened 6 times at once - probably messing it up (depending on your machine). Therefore changing the session to a database, which is designed to have thousands of requests at once, works!
SOLUTION:
Go to your .env file and change SESSION_DRIVER=file to SESSION_DRIVER=database.
Next you will need to create a session migration: php artisan session:table.
Now composer dump-autoload for good practice.
Finally migrate (php artisan migrate).
NOTE: I'm not 100% sure though if this is the case, but for me this solution worked. I am also aware that this question is really old, but both the developers I work with and myself have had this issue and there doesn't seem to be a solution, so Just though I'd post this.
Managed to figure it out.. Since i use laravel for pretty much all my projects, I forgot to change the session name, as a result, one session was overwriting the other, causing the auto-loggout.. So if you have multiple laravel projects running, make sure they all have different session names. Hope this helps someone in future !
Here is a Laracast thread on this issue.
For me this was the process to solve the problem:
Cleared my browser's cookies for localhost.
Changed value of cookie key in app/session.php.
Ran php artisan config:clear.
It may be a problem that you are accessing the user variable illegally. Please use Auth::check() before accessing Auth::user() This seems to work for my project. Optionally you can try for changing the session driver from .env file.
Might be useful for someone: Had the very same problem. I've changed the cookie name in session settings. By default it is laravel_session, so try setting it to something else
I solved the same issue by clearing cache using php artisan cache:clear and also running composer dump-autoload. Hope this works for you.
I had a similar problem this week. I have a server with multiple Laravel applications. One application was logging the other out.
The problem had to do with session management. The session name was the same for all the applications. Changing it would be enough to avoid different applications conflict. However, I can have different instances of the same application in the server (for testing purposes, for example). So, changing only the session name would not be enough.
To solve my problem properly, I used the session path to make the configuration unique per instance. In the config/session.php, I defined something like this:
'cookie' => 'systemx_session',
'path' => parse_url(env('APP_URL', 'http://localhost'), PHP_URL_PATH),
I use the parse_url function with the environment variable APP_URL because my server has the instances deployed under something like http://example.com/systemx.
I hope this helps someone who might end up having the same kind of problem.
I think you copied an old project for a new application, so you need to change the config/session.php
'cookie' => 'new_session',
I had a similar problem that the users didn't login at all & I found Its because of my authenticatable eloquent model, specified in my auth guard in config/auth.php (User in my case).
I was applying a global scope (in my case verified) so that users were filtered by a specific column & auth guard couldn't find the user so it logged out everytime ...
I solved my problem by this post https://laracasts.com/discuss/channels/laravel/ignore-global-scopes-for-auth