I would like to send a mail from a button on Laravel Nova with an action (which I think is the most appropriate).
I already have a template of the mail saved in the mailable, I have made my resource but I don't know what to put inside since I need to retrieve information from this resource like for example the name, a price or the date when the line was created (in my table related to my resource).
My resource code:
<?php
namespace App\Nova;
use App\Image;
use Gloudemans\Shoppingcart\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Fields\Heading;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
use Techouse\IntlDateTime\IntlDateTime;
class Order extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\Order::class;
public static $group = 'Paramètres';
public static function label()
{
return __('Commandes');
}
public static function singularLabel()
{
return __('Commande');
}
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Nom du client', 'name'),
IntlDateTime::make('Passée le', 'created_at')
->locale('fr')
->readonly(),
Currency::make('Prix', 'total')->currency('EUR'),
Text::make('Mode de paiement', 'gateway')
->readonly(),
Text::make('Numéro de téléphone', 'phone'),
Heading::make('Adresse de livraison'),
Text::make('Adresse', 'address')
->hideFromIndex(),
Text::make('Code postal', 'postal_code')
->hideFromIndex(),
Text::make('Ville', 'city')
->hideFromIndex(),
Text::make('Pays', 'country')
->hideFromIndex(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
My mailable code:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ResendOrder extends Mailable
{
use Queueable, SerializesModels;
/**
* Elements de contact
* #var array
*/
public $contact;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(Array $contact)
{
$this->contact = $contact;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orderconfirmation')
->subject("Confirmation de commande");
}
}
And finally my Action code:
<?php
namespace App\Nova\Actions;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
class EmailOrderConfirmation extends Action
{
use InteractsWithQueue, Queueable;
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public $name = 'Renvoyer le mail de confirmation de commande';
public function handle(ActionFields $fields, Collection $models)
{
return Action::message('Mail envoyé');
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [];
}
}
I don't really know where to go and what to use, if you could enlighten me on that I would be very grateful, thank you!
// in EmailOrderConfirmation --nova action
// declare what you are using
// use Illuminate\Support\Facades\Mail;
// use App\Mail\ResendOrder;
public function handle(ActionFields $fields, Collection $models)
{
//loop over the orders that have been selected in nova
foreach ($models as $order) {
$contact = $order->contract; //however you are getting contract data
//assuming you have a $order->user order belongs to user relationship
//send mail to the user, with the order/contract details to create your email
Mail::to($order->user->email)->send(new ResendOrder($contact));
}
//return a message to nova
return Action::message('Mail envoyé');
}
// in Order /Nova resource
// declare what you are using
// use App\Nova\Actions\EmailOrderConfirmation;
public function actions(Request $request)
{
return [new EmailOrderConfirmation];
}
Related
With some Models, when I make a new Nova Resource for them, seems that Nova can't find the Model because they doesn't show on sidebar (i can't reach them also by URL, giving me a 404).
But this happens only for specific Models and if I try to modify the target Model in the Resource with another one (editing the $model variable), it works and shows the Resource in the sidebar (but with the wrong model). Nova isn't throwing me any error so the debugging is getting crazy difficult.
The Models that doesn't work in my project are named "Product" and "Company".
I'm using Laravel 7.28.3, Nova 3.9.1, MariaDB 10.4.11 and PHP 7.4.1 with Homestead.
Here's the code of Product resource:
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Http\Requests\NovaRequest;
class Product extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\Product::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'title';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'name'
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
And here's the Model code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Product extends Model implements HasMedia
{
use InteractsWithMedia;
public function visits()
{
return visits($this);
}
public function user() {
return $this->belongsTo('App\User');
}
public function company() {
return $this->belongsTo('App\Company');
}
public function productVariety() {
return $this->belongsTo('App\ProductVariety', 'product_variety_id');
}
public function productSpecies() {
return $this->belongsTo('App\ProductSpecies', 'product_species_id');
}
public function productNutrients() {
return $this->hasMany('App\ProductNutrient');
}
public function baseProduct() {
return $this->hasOne('App\Product', 'base_product_id');
}
public function recipes() {
return $this->hasMany('App\Recipe', 'base_product_id');
}
protected $fillable = [
'user_id', 'company_id', 'imageline_id', 'products_species_id', 'products_varieties_id', 'base_product_id',
'name', 'scientific_name', 'production_start', 'production_end', 'production_city', 'description', 'story', 'curiosities', 'advices', 'quantity_advices', 'why_good', 'who_good',
'is_base_product', 'show_related_recipes', 'show_related_products'
];
}
Check your AuthServiceProvider on app/Providers/AuthServiceProvider.php if there is a Policy set to this model. Then on your policy class (probably ProductPolicy which is bind to Product model, check view and viewAny methods, these methods must return true or conditional true.
I'm trying to write a unit test for the startedAt() method using mocks however the problem I'm facing is that I don't think I can access the builder instance from inside that startedAt() method.
To test the startedAt() method I created a fixture class called ExampleFilters and had it extend the parent class of Filters. Inside of the ExampleFilters class I import the FiltersByStartDate trait.
Does anyone have any suggestions on how I can access the builder property from the FiltersByStartDate trait?
Any ideas on this?
<?php
namespace App\Filters\Concerns;
trait FiltersByStartDate
{
/**
* Filter a query to include models of a specific date started.
*
* #param array $startedAt
* #return \Illuminate\Database\Eloquent\Builder
*/
public function startedAt($startedAt)
{
if (isset($startedAt[1])) {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereBetween('started_at', [
$startedAt[0],
$startedAt[1]
]);
});
} else {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereDate('started_at', $startedAt[0]);
});
}
return $this->builder;
}
}
<?php
namespace Tests\Fixtures;
use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Filters;
class ExampleFilters extends Filters
{
use FiltersByStartDate;
}
<?php
namespace App\Filters;
use Illuminate\Http\Request;
abstract class Filters
{
/**
* #var \Illuminate\Http\Request
*/
protected $request;
/**
* The Eloquent builder.
*
* #var \Illuminate\Database\Eloquent\Builder
*/
protected $builder;
/**
* Registered filters to operate upon
*
* #var array
*/
protected $filters = [];
/**
* Create a new class instance.
*
* #param \Illuminate\Http\Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply the filters.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply($builder)
{
$this->builder = $builder;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->builder;
}
/**
* Fetch all relevant filters from the request.
*
* #return array
*/
public function getFilters()
{
return array_filter($this->request->only($this->filters));
}
}
<?php
namespace Tests\Unit\Filters\Concerns;
use Illuminate\Database\Query\Builder;
use Tests\Fixtures\ExampleFilters;
use Tests\TestCase;
/*
* #group filters
*/
class FiltersByStartDateTest extends TestCase
{
/* #var Tests\Fixtures\ExampleFilters */
protected $subject;
public function setUp(): void
{
$this->subject = app(ExampleFilters::class);
}
/** #test */
public function models_can_be_filtered_by_their_start_date()
{
// $this->markTestIncomplete();
$dateSet = ['2020-01-01 00:00:00'];
$mock = \Mockery::mock(Builder::class)
->shouldReceive('whereHas', \Mockery::any())
->shouldReceive('whereDate')
->withArgs(['started_at', $dateSet])
->once()
->andReturn(true)
->getMock();
dd($this->subject->startedAt($dateSet));
$builderMockFromDate = $this->subject->startedAt($dateSet);
$this->assertSame($builderMockFromDate, $mock);
}
}
I using Laravel 5.4 and I am trying to write a policy for my index view. I am trying to use a Method Without a Model, I am receiving the following error:
HttpException in Handler.php line 133:
This action is unauthorized.
Here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\County;
use Session;
use App\Http\Controllers\Controller;
class CountyController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$counties = County::orderBy('id', 'desc')->paginate(5);
$this->authorize('index');
return view('county.index', array(
'counties' => $counties
));
}
Here is my AuthServicePovider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Role;
use App\County;
use App\Policies\CountyPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
County::class => CountyPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('is-Admin', function ($user) {
if($user->roles()->where('name','Admin')->first()){
return true;
}
return false;
});
}
}
Here is my Policy:
<?php
namespace App\Policies;
use App\User;
use App\Role;
use App\County;
use Illuminate\Auth\Access\HandlesAuthorization;
class CountyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function index(User $user)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin'];
$testArr = array_intersect($acceptedRoles, $userRoles);
dd($testArr);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function view(User $user, County $county)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin','Client'];
$testArr = array_intersect($acceptedRoles, $userRoles);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can create counties.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function update(User $user, County $county)
{
//
}
/**
* Determine whether the user can delete the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function delete(User $user, County $county)
{
//
}
}
I never get to dd($testArr) in the index policy. Also the view policy is working perfectly.
How do I write a policy for my index view?
keeping everything the same but changing:
$this->authorize('index');
to
$this->authorize('index', County::class);
fixed the problem. Apparently the model class needs to be passed on actions that don't require a model. This is only described under the middleware section of Laravel's docs, not the controller helpers... A little confusing.
I have a Controller that have a index method, but also have a multiple levels of users that have access to this method, but single the admin can view all records of the database How can i add a middleware for select the action corresponding to user? I have the next code
<?php
namespace SET\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use SET\Http\Requests;
use SET\Http\Requests\LabRequest;
use SET\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use SET\Lab;
use Validator;
use Auth;
use DB;
class LaboratorioController extends Controller
{
public function __construct(){
$this->beforeFilter('#find', ['only' => ['show','edit','update','destroy']]);
}
public function find(Route $route){
$this->laboratorio = Lab::findOrFail($route->getParameter('laboratorio'));
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$labs = Lab::all();
return view('comp.lab.index',['labs' => $labs]);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('comp.lab.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(LabRequest $request)
{ Lab::create($request->all());
Session::flash('message','Laboratorio creado correctamente');
return Redirect::to('/laboratorio');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show()
{
$teams = $this->laboratorio;
return view('comp.lab.show',['lab'=>$this->laboratorio]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit()
{
return view('comp.lab.edit',['lab'=>$this->laboratorio]);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(LabRequest $request)
{
$this->laboratorio->update($request->all());
Session::flash('message','El laboratorio se actualizo correctamente');
return Redirect::to('/laboratorio');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy()
{
$this->laboratorio->delete();
Session::flash('message','El laboratorio fue eliminado correctamente');
return Redirect::to('/laboratorio');
}
Thanks :D
Here's a general idea:
$user_group = $user::get_user_group($user_id)
if($user_group->group_id === 'something'){
\\method to return data for group 'something'
}
Get data by groups
$user_data = $user::get_data_by_group_id($group_id)
So I am working on a page in Laravel that generates invite codes upon email submission. I have run into this issue, every time when I enter my email into the form, it is supposed to generate an invite code an input it into my DB then redirect me. Instead I get this error code:
Argument 1 passed to myapp\Repositories\Invite\EloquentInviteRepository::__construct()
must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Foundation\Application given, called in /var/www/laravel/bootstrap/compiled.php
on line 4259 and defined
This is my EloquentInviteRepository.php file, apparently line 21 is the line in error:
<?php namespace myapp\Repositories\Invite;
use myapp\Repositories\Crudable;
use Illuminate\Support\MessageBag;
use myapp\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;
use myapp\Repositories\AbstractRepository;
class EloquentInviteRepository extends AbstractRepository implements Repository, Crudable, InviteRepository {
/**
* #var Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Construct
*
* #param Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $model)
{
parent::__construct(new MessageBag);
$this->model = $model;
}
/**
* Find a valid invite by a code
*
* #param string $code
* #return Illuminate\Database\Eloquent\Model
*/
public function getValidInviteByCode($code)
{
return $this->model->where('code', '=', $code)
->where('claimed_at', '=', null)
->first();
}
/**
* Create
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function create(array $data)
{
$data['code'] = bin2hex(openssl_random_pseudo_bytes(16));
return $this->model->create($data);
}
/**
* Update
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function update(array $data){}
/**
* Delete
*
* #param int $id
* #return boolean
*/
public function delete($id){}
}
In case anyone was curious; the __construct() interface from Illuminate\Database\Eloquent\Model.php:
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
* #return void
*/
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
and Illuminate\Foundation\Application.php:
/**
* Create a new Illuminate application instance.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
public function __construct(Request $request = null)
{
$this->registerBaseBindings($request ?: $this->createNewRequest());
$this->registerBaseServiceProviders();
$this->registerBaseMiddlewares();
}
In case these help in debugging the issue!
As per request I have included my controller element used during the post function, this is the part that seems to activate the repository and prompt the error:
<?php
use myapp\Repositories\Invite\InviteRepository;
class InviteController extends BaseController {
/**
* InviteRepository
*
* #var myapp\Repositories\Invite\InviteRepository
*/
protected $repository;
/**
* Create a new instance of the InviteController
*
* #param myapp\Repositories\Invite\InviteRepository
*/
public function __construct(InviteRepository $repository)
{
$this->repository = $repository;
}
/**
* Create a new invite
*
* #return Response
*/
public function store()
{
$invite = $this->repository->create(Input::all());
}
}
RepositoryServiceProvider.php
<?php namespace myapp\Repositories;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider {
/**
* Register
*/
public function register()
{
$this->registerInviteRepository();
}
/**
* Register the Invite Repository
*
* #return void
*/
public function registerInviteRepository()
{
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
}
}
Any idea's as to what I am missing?
Thanks for the help guys,
You've been a great resource so far!
In the file RepositoryServiceProvider.php, replace this
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
With this:
$this->app->bind('myapp\Repositories\Invite\InviteRepository',
'myapp\Repositories\Invite\EloquentInviteRepository');