Laravel and Local Tunnel integration - laravel

My idea was to use Local Tunnel's subdomain feature to expose callback URI in a more convenient way. However, I believe that I could've achieved the same results in a simper way.
This is the solution with Laravel Valet:
In package.json I've added a script called shared
"scripts": {
...
"share": "lt --port 80 --subdomain blog --local-host blog.test"
}
In AppServiceProvider.php I've extended the UrlGenerator to avoid redirecting back to http://blog.test
<?php
namespace App\Providers;
use App\Services\LocalTunnelUrlGenerator;
use Blade;
use Illuminate\Http\Resources\Json\Resource;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
(...)
}
public function register()
{
$this->enableLocalTunnel();
}
private function enableLocalTunnel()
{
if (!app()->environment('local') || !config('app.use_local_tunnel')) {
return;
}
$this->app->extend('url', function (UrlGenerator $defaultGenerator) {
/** #var Router $router */
$router = $this->app['router'];
$routes = $router->getRoutes();
return new LocalTunnelUrlGenerator($routes, $defaultGenerator->getRequest());
});
}
}
This is the the LocalTunnelUrlGenerator.php:
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
class LocalTunnelUrlGenerator extends UrlGenerator
{
public function __construct(RouteCollection $routes, Request $request)
{
parent::__construct($routes, $request);
}
public function formatRoot($scheme, $root = null)
{
return "https://blog.localtunnel.me";
}
}
Why all that? Because whenever the application call the redirect() method, we are sent back to http://blog.test.
Do I really need to extend the UrlGenerator to make it work?

Related

Laravel route model binding without global scope

I have following route group in my laravel 8.0 app:
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{transaction:uuid}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{transaction:uuid}', [OfflineTransactionController::class, 'reject'])
->name('reject');
});
And Transaction model is:
class Transaction extends Model implements CreditBlocker
{
//....
protected static function boot()
{
parent::boot();
static::addGlobalScope(new AuthUserScope());
}
//....
}
And this is my AuthUserScope:
class AuthUserScope implements Scope
{
private string $fieldName;
public function __construct($fieldName = 'user_id')
{
$this->fieldName = $fieldName;
}
public function apply(Builder $builder, Model $model)
{
$user = Auth::user();
if ($user) {
$builder->where($this->fieldName, $user->id);
}
}
}
Now the problem is when an admin wants to approve or reject a transaction, 404 Not found error will throws. How can I pass this?
Customizing The Resolution Logic
If you wish to define your own model binding resolution logic, you may
use the Route::bind method. The closure you pass to the bind
method will receive the value of the URI segment and should return the
instance of the class that should be injected into the route. Again,
this customization should take place in the boot method of your
application's RouteServiceProvider:
Solution
What you can do is change the parameter name(s) in your routes/web.php file for the specific route(s).
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{any_transaction}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{any_transaction}', [OfflineTransactionController::class, 'reject'])
->name('reject');
Note the any_transaction. Change that to whatever naming convention you find most convenient.
Then, in your app/Providers/RouteServiceProvider.php file, change your boot(...) method to something like this:
use App\Models\Transaction;
use Illuminate\Support\Facades\Route;
// ...
public function boot()
{
// ...
Route::bind('any_transaction', function($uuid) {
return Transaction::withoutGlobalScopes()->where('uuid', $uuid)->firstOrFail();
});
// ...
}
// ...
Then in your controller app/Http/Controllers/OfflineTransactionController.php file, access the injected model:
use App\Models\Transaction;
// ...
public function approve(Transaction $any_transaction) {
// ...
}
// ...
Credits: Using Route Model Binding without Global Scope #thomaskim
Addendum
If you would like to remove a specific global scope from the route model bound query, you may use
withoutGlobalScope(AuthUserScope::class) in the boot(...) method of the app/Providers/RouteServiceProvider.php file.
Another approach is that I can use Route::currentRouteNamed in AuthUserScope class as following, which I prefer to use instead of Route::bind:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
class AuthUserScope implements Scope
{
private string $fieldName;
public function __construct($fieldName = 'user_id')
{
$this->fieldName = $fieldName;
}
public function apply(Builder $builder, Model $model)
{
$user = Auth::user();
if ($user && !Route::currentRouteNamed('admin.*')) {
$builder->where($this->fieldName, $user->id);
}
}
}

How to implement event/listeners with repository pattern in laravel 5.4

I can't make listeners trigger action update, create or delete when I user patter repository.
Addionally I have added my code in order to help my to solve my problem.
TicketController.php
namespace App\Http\Organizer\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Events\Contracts\IEvent;
use App\Entities\Event;
class TicketController extends Controller
{
protected $IEvent;
public function __construct( IEvent $IEvent )
{
$this->IEvent = $IEvent;
}
public function checkFutbolType ($activityId)
{
// I need to listen this action here
$event = $this->IEvent->update(21927, ['title'=>'new title']);
}
}
My RepoEvent.php:
<?php
namespace App\Http\Events\Repositories;
use App\Http\Events\Contracts\IEvent
;
class RepoEvent implements IEvent
{
protected $model;
public function __construct($model)
{
$this->model = $model;
}
public function update($activityId, $params)
{
return $this->model->where('id', $activityId)->update($params);
}
}
My AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Entities\Event;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//event: creating
Event::creating(function (Event $event) {
return $event->creatingEvent();
});
//event: saving
Event::saving(function (Event $event) {
return $event->savingEvent();
});
//event: updating
Event::updating(function (Event $event) {
return $event->updatingEvent();
});
}
}
My interface IEvent.php:
<?php
namespace App\Http\Events\Contracts;
interface IEvent
{
public function update($activityId, $params);
}
My ServicesOrchestration.php:
<?php
namespace App\Http\Administration\Providers;
use App\Entities\Event;
use App\Http\Administration\Repositories\RepoEvent;
use Illuminate\Support\ServiceProvider;
class ServicesOrchestration extends ServiceProvider
{
public function boot()
{
}
public function register()
{
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(new Event());
});
}
}
My model Event.php
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function creatingUser() {
\Log::info('creating event');
}
public function savingUser() {
\Log::info('saving event');
}
public function updatingUser() {
\Log::info('updating event');
}
}
thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance
Here's the relevant snipped from the docs (scroll to mass updates):
When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.
For your code to work you need to first retrieve the actual model instance like below:
public function update($activityId, $params)
{
$instance = $this->model->find($activityId);
$instance->fill($params);
$instance->save();
}
This will have an additional cost of doing two queries instead of one and only being able to update a single model at a time.
A sidenote: You're passing a model instance to the repository but what you actually want is to pass a query builder instance:
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(Event::query());
});

Laravel Pass Authenticated to Every View

I need to pass a collection to every view; the collection contains the IDs of the items in the user's shopping cart. I've tried Service Providers and a BaseClass but neither worked as (apparently) Auth hasn't been registered at those points and only returns null.
What's the best way get records from an authenticated user and pass it to every view?
Edit: here's the relevant code
User.php
public static function getCart()
{
if (Auth::guest()) {
return [];
}
$collection = new \Illuminate\Database\Eloquent\Collection();
$collection = Auth::user()->cart()->pluck('post_id');
return $collection;
}
CartServiceProvider.php
namespace App\Providers;
use View;
use App\User;
use Illuminate\Support\ServiceProvider;
class CartServiceProvider extends ServiceProvider
{
public function boot()
{
View::share('cart', User::getCart());
}
public function register()
{
//
}
}
In any view...
<?php dd($cart); ?>
returns [] because Auth hasn't been registered yet, so the empty array is returned.
Found the answer on Laracasts and it seems to work quite well.
https://laracasts.com/discuss/channels/general-discussion/l5-service-provider-for-sharing-view-variables
From the OP #imJohnBon: "I managed to solve this issue by creating 2 files. First a ComposerServiceProvider which uses a wildcard to be applied to every view and not just particular views:"
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\View\Factory as ViewFactory;
class ComposerServiceProvider extends ServiceProvider {
public function boot(ViewFactory $view)
{
$view->composer('*', 'App\Http\ViewComposers\GlobalComposer');
}
public function register()
{
//
}
}
"And then the corresponding GlobalComposer where I share variables that should be available in all views:"
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
class GlobalComposer {
public function compose(View $view)
{
$view->with('currentUser', Auth::user());
}
}

laravel 5.1 - trait boot not being called for model::update() function

I have created trait as follows on this page app/Traits/ModelEventThrower.php
namespace App\Traits;
use Input;
use Event;
use App\Events\ActivityLog;
use Illuminate\Database\Eloquent\Model;
//use Illuminate\Support\Facades\Event;
/**
* Class ModelEventThrower
* #package App\Traits
*
* Automatically throw Add, Update, Delete events of Model.
*/
trait ModelEventThrower {
/**
* Automatically boot with Model, and register Events handler.
*/
protected static function bootModelEventThrower()
{
foreach (static::getModelEvents() as $eventName) {
static::$eventName(function (Model $model) use ($eventName) {
try {
$reflect = new \ReflectionClass($model);
echo "here";exit;
} catch (\Exception $e) {
return true;
}
});
}
}
/**
* Set the default events to be recorded if the $recordEvents
* property does not exist on the model.
*
* #return array
*/
protected static function getModelEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}
return [
'created',
'updated',
'deleted',
];
}
}
My City Model is something like this
namespace App;
use App\Traits\ModelEventThrower;
use App\Events\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Event;
class City extends Model
{
use ModelEventThrower;
//protected static $recordEvents = ['updated'];
...
}
My CitiesController is
namespace App\Http\Controllers\Admin;
use App\City;
use App\Country;
use Input;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CitiesController extends Controller
{
......
public function update(City $city,Request $request)
{
......
$city->where('id','=',$input['id'])->update($input);
Somehow, I dont see its calling the function written in trait file. When I tried to create $city->create($input); it echos "here" and stops execusion, but not doing same for update function , however I could successfully update the records.
Any suggestion/help will be highly appreciated.
I had a similar issue with Laravel. By adding a constructor in the model to call the boot() function of the parent Model, like so:
public function __construct()
{
parent::boot();
}
you can make sure that all the traits are booted. This solved it for me.

Facade not found by AliasLoader in Laravel

I added a custom facade to my 'config/app.php' in my laravel project under 'aliases'
'GeoLocation' => '\App\Facades\GeoLocation',
The folder of the custom class is in 'app/Facades/GeoLocation.php' and the service provider in 'app/Providers/GeoLocationServiceProvider.php'
How do I need to state the correct alias in the app.php to be able to load the Facade correctly? The error message is:
ErrorException in AliasLoader.php line 63:
Class 'Facades\GeoLocation' not found
This is my facade:
<?php namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class GeoLocation extends Facade {
protected static function getFacadeAccessor() { return 'geolocation'; }
}
Could it be that the return value of my service provider is incorrect?
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class GeoLocationServiceProvider extends ServiceProvider {
public function register() {
\App::bind('geolocation', function()
{
return new GeoLocation;
});
}
}
For a test I created another service provider called custom function:
<?php namespace App\Helpers;
class CustomFunction {
//Generate random float between -1 and 1
function f_rand($min = 0, $max = 1, $mul = 1000000) {
if ($min>$max) return false;
return mt_rand($min*$mul, $max*$mul) / $mul;
}
function test() {
echo "OK";
}
}
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class CustomFunctionServiceProvider extends ServiceProvider {
public function register() {
\App::bind('customfunctions', function()
{
return new CustomFunction;
});
}
}
the simplest way is to change the namespace to the file app/Facades/GeoLocation.php' to App\Facades;
then update aliase registration to
'GeoLocation' => 'App\Facades\GeoLocation',

Resources