Laravel add method to a vendor class - laravel

In laravel we can use with() along with redirect(), like
return redirect('home')->with(['message' => 'Some message');
I want to create some other functions like withError(), withSuccess().
How and where to create this ?

As the Laravel RedirectResponse class uses the Macroable trait, you can register response macros to do this.
Just create a new service provider say ResponseMacroServiceProvider. Register it in your app.php and register a macro in the boot method like so:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Http\RedirectResponse;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Register the application's response macros.
*
* #return void
*/
public function boot()
{
RedirectResponse::macro('withError', function ($value) {
return; // add logic here
});
RedirectResponse::macro('withSuccess', function ($value) {
return; // add logic here
});
}
}

Related

Use Auth in AppServiceProvider

I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $profile, I want all files in the view to have $profile
public function index(){
$profil = Profil_user::where('user_id',$auth)->first();
View::share('profil', $profil);
return view('user.index');
}
I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?
public function boot(){
$auth = Auth::user();
dd($auth);
}
exist several way to pass a variable to all views. I explain some ways.
1. use middleware for all routes that you need to pass variable to those:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
go to app/Http/Middleware/RootMiddleware.php and do following example code:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
then must register this middleware in app/Http/Kernel.php and put this line 'root' => RootMiddleware::class, to protected $routeMiddleware array.
then use this middleware of routes or routes group, for example:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
or set for single root:
Route::get('/profile', 'ProfileController#profile')->name('profile')->middleware('RootMiddleware');
2. other way that you pass variable to all views with view composer
go to app/Http and create Composers folder and inside it create ProfileComposer.php, inside ProfileComposer.php like this:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
now it's time create your service provider class, I named it ComposerServiceProvider
write this command in terminal : php artisan make:provider ComposerServiceProvider
after get Provider created successfully. message go to config/app.php and register your provider with put this \App\Providers\ComposerServiceProvider::class to providers array.
now go to app/Providers/ComposerServiceProvider.php and do like following:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
3. is possible that without create a service provider share your variable in AppServiceProvider, go to app/Provider/AppServiceProvider.php and do as follows:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
I hope be useful
you can use this
view()->composer('*', function($view)
{
if (Auth::check()) {
$view->with('currentUser', Auth::user());
}else {
$view->with('currentUser', null);
}
});

Laravel Global Variable to specific views

I would like assistance with calling a global variable on Laravel app for specific pages or routes.
This is my current code which works on login
App\Providers\AppServiceProvider
public function boot()
{
view()->composer(['auth.login'], function ($view) {
$view->with('settings', AppSetting::where('id',1)->first());
});
}
This is the route for the login page
Route::get('/', function () {
return view('auth.login');
});
[Edit 1]
On the login page , I used this code bellow to get the app version
{{$settings->app_version}}
After digging a little I think a good solution might be caching your AppSetting Model.
Write the given code in App\Providers\RouteServiceProvider
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
parent::boot();
App::before(function($request) {
App::singleton('settings', function(){
return AppSetting::where('id',1)->first();
});
// If you use this line of code then it'll be available in any view
// as $settings but you may also use app('settings') as well
View::share('settings', app('settings'));
});
}
}
App::singleton will call once AppSetting::where('id',1)->first() and after one call your settings will be cached.
And you can use {{$settings->app_version}} in your view.
Reference: stackoverflow.com/a/25190686/7047493

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.

using auth in laravel service provider

whenever i tried to use \Auth::User() i am getting non object property because my Auth::guest() returns true whenever i use them in service provider
use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\View\Factory;
use App\relations;
use App\User;
use DB;
use Illuminate\Support\Facades\Auth;
class RelationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
\Auth::User()->id;
$relation_friend_for_logged_user = DB::select( DB::raw("SELECT * FROM users"));
$value = "asd";
// for injecting objct
View()->share('count', $value);
}
but why \Auth::guest() is returning true whether i am logged in
You probably want to use a View Composer for this. As far as I know the authenticated user is not yet available in your service providers boot method.
public function boot(Guard $auth) {
view()->composer('*', function($view) use ($auth) {
// get the current user
$currentUser = $auth->user();
// do stuff with the current user
// ...
// pass the data to the view
$view->with('currentUser', $currentUser);
});
}
Code modified from https://laracasts.com/discuss/channels/general-discussion/how-do-i-get-the-current-authenticated-user-laravel-5

Only use translations from messages.php in Laravel 5

I would like to load all our translations into a flat array in resources/lang/en/messages.php and resources/lang/fr/messages.php
I would like to translate them in the view simply with trans('key') rather than trans('file.key')
Anyway to enable this behaviour? Seems it does not come out of the box. Thanks.
Figured out how, first define your own provider in App\Providers. Have it use your own custom class instead.
<?php namespace App\Providers;
use App\Utilities\TranslationUtility;
use Illuminate\Translation\TranslationServiceProvider;
class SimpleTranslationProvider extends TranslationServiceProvider {
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->registerLoader();
$this->app->singleton('translator', function($app)
{
$loader = $app['translation.loader'];
$locale = $app['config']['app.locale'];
$trans = new TranslationUtility($loader, $locale);
$trans->setFallback($app['config']['app.fallback_locale']);
return $trans;
});
}
}
Custom class:
<?php namespace App\Utilities;
use Illuminate\Translation\Translator;
class TranslationUtility extends Translator {
public function get($key, array $replace = array(), $locale = NULL)
{
return parent::get('messages.' . $key);
}
}
Then add your service provider in config/app.php instead of 'Illuminate\Translation\TranslationServiceProvider'

Resources