Using custom package view templates for email verification notification - laravel

I'm sending email verification by extending VerifyEmail in my custom package:
<?php
namespace MyPackages\Foo\Notifications;
use Illuminate\Support\Facades\Crypt;
class VerifyEmail extends \Illuminate\Auth\Notifications\VerifyEmail
{
/**
* Get the verification URL for the given notifiable.
*
* #param mixed $notifiable
* #return string
*/
protected function verificationUrl($notifiable)
{
$hash = Crypt::encrypt($notifiable->getKey());
return config('foo.email_verify_url') . $hash;
}
}
It's correctly using the url from config/foo.php in Foo package.
But how to tell it to use the templates which are in the two following folders:
packages/my-packages/foo/src/resources/views/vendor/mail
packages/my-packages/foo/src/resources/views/vendor/notifications
instead of the templates in:
resources/views/vendor/mail
resources/views/vendor/notifications
Knowing that I also have...
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'foo');
...set in my package provider.

Handling views in custom Laravel packages is documented here: Package development - views
Option 1: Views in your Laravel installation
In config/view.php you can add additional paths where your views are located - see the config.
'paths' => [
resource_path('views'),
// ...
],
Option 2: Custom package
If you ship your views inside a custom package, the you would need to publish your views.
In your service provider specify the package views folder
protected function loadViews()
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'foo');
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/foo'),
]);
}
Then run artisan vendor:publish (Laravel docs) to make them available to your main application.

Related

Why does Intelephense dislike my custom helper class?

I am trying to write some custom helper functions for my Laravel 9 app using the advice given in the second answer (written by heisian) to this question. I think I've imitated everything faithfully but when I try to use the new function, intelephense says "Undefined type 'Helper'.
Here is my Helper.php (stored in app/Helpers/Helper.php):
<?php
namespace App\Helpers;
class Helper {
public static function hello() {
return "Hello!";
}
}
?>
Here is the only section I changed in config/app.php:
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
'Helper' => App\Helpers\Helper::class
])->toArray(),
Here is the part of my code where I actually use the new hello() function:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Helper;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Listing>
*/
class ListingFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
$this->faker = \Faker\Factory::create();
/* Choose a single job title at random from the collection of job titles. */
// $titlesCollection = collect(['Junior Laravel Developer', 'Intermediate Laravel Developer', 'Senior Laravel Developer', 'Laravel Project Leader']);
// $randomTitleString = $titlesCollection->random();
$randomTitleString = Helper::hello();
Intelephense highlights the final line of this excerpt by putting a red squiggly line under Helper. I can make the error go away by changing:
use Helper;
to
use app\Helpers\Helper;
However, if I then try to execute php artisan migrate:refresh --seed I get a different error. However, the refresh/seed WORKS with use Helper; despite the error and the hello() function does exactly what I've told it to do. (I should mention that I have done the composer dump-autoload on my terminal as per the instructions in the linked question.)
Ultimately, the only real problem here is that Intelephense doesn't recognize the Helper class for what it is. Short of uninstalling Intelephense from my copy of VS Code, is there anything I can do to make it recognize that Helper is a legitimate class?

Is it possible to import excel data into laravel REST API?

I don't know how to import the excel data to my database via REST API in laravel, I try so much research on google but those tutorials and videos aren't related to API..... pls help
Download the dependecy using composer for Import and export excel file.
composer require maatwebsite/excel
Add providers and aliases in config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
......,
......,
Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
.......,
-------,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
Now publish the changes using vendor:publish
php artisan vendor:publish
Make migration and migrate it using command.
Add routes
Create Import and Export class using import/export command
Note: This command avaialble only if you download dependecy successfully using composer(step 1)
In app/Imports/BulkImport.php file
<?php
namespace App\Imports;
use App\Bulk;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class BulkImport implements ToModel,WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Bulk([
'name' => $row['name'],//fields from excel
'email' => $row['email'],
]);
}
}
Make A controller and in controller use
Excel::import(new BulkImport,request()->file('file'));
Bulk is the model in this example
Hope it Will helps Have a Good Day

Passing Company Data to All controller in Laravel 6.x

I am building an app where each company have multiple users. And all users can upload documents/images/xls etc. I want to keep all company data in company separate folder. To complete this I am checking the company detail for every user and then upload data to company specific folder. Can I check company database once per user login and share user's company details to all controller and can easily access.
Use view composer in your AppServiceProvider
App\Providers\AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('*',function($view) {
if(auth()->user()) {
$comanyData = App\Company::where('user_id',auth()->user()->id);
$view->with('companyData', $companyData);
}
});
}
}
You can make the helper function to use in controllers or blades files.
Let’s create a helper!
Create a simple PHP file.
Create Helper.php inside the app directory or wherever directory you want.
<?php
/**
* get company data
*
*/
function companyData()
{
// Create logic of company data
// return company data
}
Autoload Composer
After we created our helper, Laravel won’t recognize our file so we need to register the helper file to our composer.json. Add File array inside the autoload section. It may look like this:
"autoload": {
"classmap": ["database"],
"psr-4": {"App\\": "app/"},
"files" : ["app/Helper.php"]
}
Then don’t forget to run
composer dumpautoload
Using helper function
Our helper is autoloaded now, so we should be able to use our helper immediately on different controllers. Just call our function in any class
$companyData = companyData();
or in blade view
{{ companyData() }}
Let me know if you are facing an issue.
Below is how to share a variable with your entire application via the AppServiceProvider, You can also do this inside of your base controller in the construct method.
File: App\Providers\AppServiceProvider.php
<?php
namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::share('key', 'value');
}
}
You can then access $key inside of any view.

Override sendSwiftMessage() Laravel Swiftmailer with custom

I am using Laravel 4.2
The answer given by user3158900 is for Laravel 5.*
Any one can help me with version 4.2 ?
I would like to override sendSwiftMessage() protected function with my own function.
sendSwiftMessage() is located in
"vendor/laravel/framework/src/Illuminate/Mail/Mailer.php"
I created a
Lib/Mailer/CustomMailer.php
and Set the folder Lib to autoload in composer (PSR4).
I can now call/load my function in my controllers by writing:
new Lib\Mailer\CustomMailer;
This is how my file looks like:
<?php namespace Lib\Mailer;
class CustomMailer extends \Illuminate\Mail\Mailer {
/**
* Send a Swift Message instance.
*
* #param \Swift_Message $message
* #return void
*/
protected function sendSwiftMessage($message)
{
if (strpos($message->toString(), 'noemail#noemail.com') == true) {
Log::info('Not sending mail to noemail#noemail.com');
}
else
{
if ($this->events)
{
$this->events->fire('mailer.sending', array($message));
}
if ( ! $this->pretending)
{
$this->swift->send($message, $this->failedRecipients);
}
elseif (isset($this->logger))
{
$this->logMessage($message);
}
}
}
}
However, this sendSwiftMessage() function is not used when I send an email with Swiftmailer in my controller by doing EXAMPLE:
Mail::send(xxxx);
My question: How can I make Swiftmailer/Laravel use my custom sendSwiftMessage() function when I send a message if I don't want to modify all my Controllers that currently use the Mail::send() code
Think I got this figured out, however I am getting an error but I think that's on you because your custom class is using a property that doesn't exist so here's the solution anyway.
In AppServiceProvider.php in the boot() method, I've added the following:
$this->app->singleton('customMailer', function($app) {
return new CustomMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
});
In app/Lib/Mailer folder, I've added another class for the facade.
namespace App\Lib\Mailer;
use Illuminate\Support\Facades\Facade;
class Mail extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'customMailer';
}
}
In config/app.php, I've replaced the Mail alias with the following...
'Mail' => App\Lib\Mailer\Mail::class,
And that should be all you need to do.
One other thing, I just noticed you are missing in your namespace the App which explains why you had to add the Lib folder to the autoloader. If you namespace it correctly to keep it inline with PSR-4 by adding the App\ onto the beginning, then you don't need to add anything to your composer.json file to get additional classes loaded.

Share data to all views in laravel5.2

I have the following problem, I want to share an array to all views in my project so I followed the documentation and it works fine, but I want to get the authenticated user in service provider boot function and it always return null ?
any suggestions ?
this is my code
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public $myusers;
public function boot()
{
$origLat=\Auth::user()->lat;
$origLon=\Auth::user()->lng;
$dist=5;
$lon1=$origLon-$dist/cos(deg2rad($origLat))*73.2044736;
$lon2=$origLon+$dist/cos(deg2rad($origLat));
$lat1=$origLat-($dist/73.2044763);
$lat2=$origLat+($dist/73.2044763);
$id=\Auth::user()->id;
$pictures=User::find($id)->pictures;
$this->myusers = DB::table('users')->select(
DB::raw("*,
3956 * 2 *
ASIN(SQRT( POWER(SIN(($origLat- lat)*pi()/180/2),2)
+COS($origLat*pi()/180 )*COS(lat*pi()/180)
*POWER(SIN(($origLon-lng)*pi()/180/2),2)))*1.609344
as distance"
))
->where('users.id', '!=', \Auth::user()->id)
->whereBetween('lng',[$lon1,$lon2])
->whereBetween('lat',[$lat1,$lat2])
->having("distance", "<", "$dist")
->orderBy("distance")
->get();
view()->share('myusers', $this->myusers);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Unfortunately, at this point the Laravel application request lifecycle works in such a way that when the boot method of the App\Providers\AppServiceProvider class is executed the session is not yet initialised (since that's done in a middleware that is executed after the boot method).
Since the authentication systems needs the session in order to get the authenticated user, in your particular case you can't use view()->share() successfully there (although it's the recommended approach). Instead you can use an alternative approach by doing that in a middleware. Here are the steps that you can follow to make this work:
1. Create a middleware class, let's call it LoadUsers, by running this command:
php artisan make:middleware LoadUsers
2. That will generate a class in app/Http/Middleware/LoadUsers.php. Now you just need to move your code from the AppServiceProvider to the handle method of the middleware:
class LoadUsers
{
public function handle($request, Closure $next)
{
// Your code that shares the data for all views goes here
return $next($request);
}
}
3. Next you need to register the middleware with the App\Http\Kernel class. You can add it to the web group from $routeMiddleware if you want to apply the middleware to all routes that that use that or create your specific group or route middleware. So something like this if you want to add it to web:
protected $middlewareGroups = [
'web' => [
...
// Make sure to add this line is after the
// StartSession middleware in this list
\App\Http\Middleware\LoadUsers::class,
],
...
];
Now you should have the proper shared data for all your views that can depend on Auth::user().

Resources