Date and Time localization not works in Laravel-mix - laravel

I have Laravel mix installed on my server. there is a chat part on website and I use some kind of class :
class ActivityCell extends Component {
getTimestamp() {
const {message} = this.props;
return (
<span className="font-weight-semi-bold">
{utcDateCalendarTime(message.created_at)}
</span>
);
}
And here is my AppServiceProvider.php file :
<?php
namespace App\Providers;
use Illuminate\Http\Resources\Json\Resource;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function boot()
{
setlocale(LC_ALL, Config::get('app.lc_all'));
Carbon::setLocale(Config::get('app.locale'));
}
public function register()
{
$this->registerPlugins();
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$this->bootDatabase();
$this->bootResource();
}
/**
* Boot database schema
*
* #return void
*/
private function bootDatabase()
{
Schema::defaultStringLength(191);
}
/**
* Boot resource
*
* #return void
*/
private function bootResource()
{
Resource::withoutWrapping();
}
/**
* Register plugins
*
* #return void
*/
private function registerPlugins()
{
$pluginDirs = File::directories(base_path('app/Plugins'));
foreach ($pluginDirs as $pluginDir) {
$class = "App\\Plugins\\" . basename($pluginDir) . "\\PluginServiceProvider";
if (class_exists($class) && is_subclass_of($class, ServiceProvider::class)) {
$this->app->register($class);
}
}
}
}
I tried to put setlocale(LC_TIME, 'tr'); on top of the class file but there is no success. Then tried to use carbon in order to make the date is viewed in different languages when I change the website language.
I added the following codes in app/config.php :
'locale' => env('APP_LOCALE', 'az'),
'lc_all' => env('APP_LC_ALL', 'az_AZ.UTF-8'),
and added following to the env file :
APP_LOCALE = az
APP_LC_ALL = az_AZ.UTF-8
in both methods, I was not successful. I am pretty sure that I am doing a mistake somewhere but can not find where exactly. Maybe I am missing to add something else to add. Any help would be highly appreciated.
EDIT : Adding Chat.php :
<?php
namespace App\Models;
use App\Events\ChatParticipationChanged;
use App\Events\ChatUpdated;
use App\Http\Resources\ChatMessage as ChatMessageResource;
use App\Http\Resources\MarketplaceTrade as MarketplaceTradeResource;
use ArrayObject;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use JSsVPSDioNXpfRC;
use DateTimeInterface;
class Chat extends Model
{
protected $lastMessageAttribute;
protected $lastMarketplaceTradeAttribute;
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* The event map for the model.
*
* #var array
*/
protected $dispatchesEvents = [
'updated' => ChatUpdated::class
];
/**
* Indicates if the IDs are auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
/**
* Get the route key for the model.
*
* #return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return $date->translatedFormat('A B M');
}
public function getRouteKeyName()
{
return 'id';
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function creator()
{
return $this->belongsTo(User::class, 'creator_id', 'id');
}
/**
* Participants for this chat
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function participants()
{
return $this->hasMany(ChatParticipant::class, 'chat_id', 'id');
}
/**
* Messages for this chat
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function messages()
{
return $this->hasMany(ChatMessage::class, 'chat_id', 'id');
}
/**
* Update user's participation record
*
* #param User $user
*/
public function updateParticipation($user)
{
$this->participants()->where('user_id', $user->id)
->update(['last_read_at' => now()]);
broadcast(new ChatParticipationChanged($this, $user));
}
/**
* All marketplace trades hosted by this chat
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function marketplaceTrades()
{
return $this->hasMany(MarketplaceTrade::class, 'chat_id', 'id')
->has('buyer')->has('seller');
}
/**
* #return Model|\Illuminate\Database\Eloquent\Relations\HasMany|mixed|object|null
*/
public function getLatestMarketplaceTrade()
{
if (!isset($this->lastMarketplaceTradeAttribute)) {
$trade = $this->marketplaceTrades()->latest()->first();
$this->lastMarketplaceTradeAttribute = new MarketplaceTradeResource($trade);
}
return $this->lastMarketplaceTradeAttribute;
}
/**
* Last chat message
*
* #return ChatMessageResource|ArrayObject|mixed
*/
public function getLatestMessage()
{
if (!isset($this->lastMessageAttribute)) {
$message = $this->messages()->latest()->first();
if ($message) {
$this->lastMessageAttribute = new ChatMessageResource($message);
} else {
$this->lastMessageAttribute = new ArrayObject();
}
}
return $this->lastMessageAttribute;
}
/**
* #param User $user
* #return array
*/
public function getParticipation($user)
{
$participant = $this->participants()
->where('user_id', $user->id)->without('user')
->first();
$unreadMessagesCount = ($participant && $participant->last_read_at) ?
$this->messages()->where('user_id', '!=', $user->id)
->where('created_at', '>', $participant->last_read_at)
->count() :
$this->messages()->where('user_id', '!=', $user->id)
->count();
return [
'user_id' => $user->id,
'unread_messages_count' => $unreadMessagesCount
];
}
/**
* If user should be allowed in this chat
*
* #param User $user
* #return bool
*/
public function shouldAllowUser($user)
{
$isParticipant = $this->participants()
->where('user_id', $user->id)->exists();
return (
$isParticipant ||
$user->can('moderate_chats')
);
}
/**
* #return string
*/
public function attachmentsDir()
{
return "chats/{$this->id}/message-attachments";
}
}

The problem is on your namespace :
// Using PHP callable syntax
use Carbon\Carbon;
Or,
// Using string syntax
\Carbon\Carbon::setLocale('ru');
You also need to use translatedFormat() method on your blade for use the translate format, like :
{{ Carbon\Carbon::now()->translatedFormat('A B M') }} // утра 428 фев
You can use serializeDate() method on your model, to change timestamp column as a translated dataTime format :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->translatedFormat('A B M');
}

Related

Laravel Nova page detail not found due to The relationship

I am trying to test the tool I have been created. When I used relationship field in one of my resource, the page detail on this resource give me Not found.
/* My Relationship field */ (Ticket Resource)
HasMany::make(__('Replies'), 'replies',Reply::class)
/* Include */
use TicketWhmcs\TicketWhmcsPackage\Nova\Reply;
/* Ticket Model */
<?php
namespace TicketWhmcs\TicketWhmcsPackage\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use TicketWhmcs\TicketWhmcsPackage\Traits\API;
use TicketWhmcs\TicketWhmcsPackage\Models\TicketReplay;
class Ticket extends Model
{
use HasFactory, API;
protected $table = 'tickets';
protected $fillable = [
'tid',
'user_id',
'dept_id',
'subject',
'message',
'priority',
'status',
'admin',
];
public function department()
{
return $this->belongsTo(Department::class, 'dept_id', 'id');
}
/**
* Get all of the replies for the Ticket
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function replies()
{
return $this->hasMany(TicketReplay::class);
}
}
/* My resource */
namespace TicketWhmcs\TicketWhmcsPackage\Nova;
My Reply Resource
<?php
namespace TicketWhmcs\TicketWhmcsPackage\Nova;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
class Reply extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \TicketWhmcs\TicketWhmcsPackage\Models\TicketReplay::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/* Sort */
public static $sort = [
'id' => 'desc',
];
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'admin',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make(__('Message'), 'message')->hideFromIndex(),
Text::make(__('Message'), 'message')->displayUsing(function ($value) {
return Str::limit($value, 50);
})->onlyOnIndex(),
Text::make(__('Author'), 'admin')->displayUsing(function ($value) {
if ($value) {
return 'Admin';
} else {
return 'You';
}
})->hideWhenCreating(),
Text::make('Last Update', 'updated_at')
->displayUsing(function ($lastActive) {
if ($lastActive === null) {
return null;
}
return $lastActive->diffForHumans();
})->hideWhenCreating(),
];
}
/**
* 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 [];
}
public function authorizedToUpdate(Request $request)
{
return false;
}
public function authorizedToDelete(Request $request)
{
return false;
}
public static function indexQuery(NovaRequest $request, $query)
{
if (empty($request->get('orderBy'))) {
$query->getQuery()->orders = [];
return $query->orderBy(key(static::$sort), reset(static::$sort));
}
return $query;
}
}
I register My resource in NovaServiceProvider
public function resources()
{
Nova::resources([
Reply::class
]);
}
And it's worked!

Add Multiple OneSignal APP in Custom Notification in laravel

I have two Notification channels
app/Channels/Reseller/Web/OneSignalWeb.php
<?php
namespace App\Channels\Reseller\Web;
use Berkayk\OneSignal\OneSignalClient;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\OneSignal\Exceptions\CouldNotSendNotification;
use NotificationChannels\OneSignal\OneSignalChannel;
class OneSignalWeb extends OneSignalChannel
{
public function __construct()
{
$client = new OneSignalClient(
env("ONESIGNAL_RESELLER_APP_ID"),
env("ONESIGNAL_RESELLER_REST_API_KEY"),
''
);
parent::__construct($client);
}
/**
* Send the given notification.
*
* #param mixed $notifiable
* #param \Illuminate\Notifications\Notification $notification
*
* #return \Psr\Http\Message\ResponseInterface
* #throws \NotificationChannels\OneSignal\Exceptions\CouldNotSendNotification
*/
public function send($notifiable, Notification $notification)
{
if (!$userIds = $notifiable->devices()->where('platform', 'web')->pluck('uuid')->toArray()) {
return;
}
/** #var ResponseInterface $response */
$response = $this->oneSignal->sendNotificationCustom(
$this->payload($notifiable, $notification, $userIds)
);
if ($response->getStatusCode() !== 200) {
throw CouldNotSendNotification::serviceRespondedWithAnError($response);
}
return $response;
}
}
app/Channels/Merchant/Web/OneSignalWeb.php
<?php
namespace App\Channels\Merchant\Web;
use Berkayk\OneSignal\OneSignalClient;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\OneSignal\Exceptions\CouldNotSendNotification;
use NotificationChannels\OneSignal\OneSignalChannel;
class OneSignalWeb extends OneSignalChannel
{
public function __construct()
{
$client = new OneSignalClient(
env("ONESIGNAL_MERCHANT_APP_ID"),
env("ONESIGNAL_MERCHANT_REST_API_KEY"),
''
);
parent::__construct($client);
}
/**
* Send the given notification.
*
* #param mixed $notifiable
* #param \Illuminate\Notifications\Notification $notification
*
* #return \Psr\Http\Message\ResponseInterface
* #throws \NotificationChannels\OneSignal\Exceptions\CouldNotSendNotification
*/
public function send($notifiable, Notification $notification)
{
if (!$userIds = $notifiable->devices()->where('platform', 'web')->pluck('uuid')->toArray()) {
return;
}
/** #var ResponseInterface $response */
$response = $this->oneSignal->sendNotificationCustom(
$this->payload($notifiable, $notification, $userIds)
);
if ($response->getStatusCode() !== 200) {
throw CouldNotSendNotification::serviceRespondedWithAnError($response);
}
return $response;
}
}
In both of these channel only the difference is that in __constructwe load different keys for both Reseller and Merchant
public function __construct()
{
$client = new OneSignalClient(
env("ONESIGNAL_RESELLER_APP_ID"),
env("ONESIGNAL_RESELLER_REST_API_KEY"),
''
);
parent::__construct($client);
}
And this is the Nofications/Base.php where i've load both ResellerWeb and MerchantWeb Notification in via methods
public function via($notifiable)
{
return [
'database',
'broadcast',
ResellerWeb::class,
MerchantWeb::class,
];
}
I want to optimize the norification where instead of loading MerchantWeb::class and ResellerWeb::cass i want to create and load a general channel lets say NotificationWeb::class and want to use it for both Reseller and Merchant. And when i use it i will need to switch the env() keys based on for which i use.
How can this be achieved

Extending and customizing Laravel Reset Password Logic

Does anybody know how to customize ResetPassword logic in Laravel. I want to use custom field 'phone' vs 'email'. Small workaround with create_passwords_resets migration and done
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('phone')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
But i've started to get exceptions on absent field 'email' users tables simply doesn't have it all.
I'm just trying to use Password::Facade like
$status = Password::sendResetLink($request->only('phone'));
Why in such customizable platform hard-coded things like DatabaseTokenRepository even exist?
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array) $this->getTable()->where(
'email', $user->getEmailForPasswordReset()
)->first();
return $record &&
! $this->tokenExpired($record['created_at']) &&
$this->hasher->check($token, $record['token']);
}
How can i override it?
If i try to implement one of the answers on Stack doing this:
namespace App\Auth;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Auth\Passwords\DatabaseTokenRepository as DatabaseTokenRepositoryBase;
use Illuminate\Support\Carbon;
class DatabaseTokenRepository extends DatabaseTokenRepositoryBase
{
public function create(CanResetPasswordContract $user)
{
$email = $user->getEmailForPasswordReset();
$mobile = $user->getMobileForPasswordReset();
$this->deleteExisting($user);
$token = $this->createNewToken();
$this->getTable()->insert($this->getPayload($email, $mobile, $token));
return $token;
}
protected function deleteExisting(CanResetPasswordContract $user)
{
return $this->getTable()
->where("email", $user->getEmailForPasswordReset())
->orWhere("mobile", $user->getMobileForPasswordReset())
->delete();
}
protected function getPayload($email, $mobile, $token): array
{
return [
"email" => $email,
"mobile" => $mobile,
"token" => $this->hasher->make($token),
"created_at" => new Carbon(),
];
}
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array)$this->getTable()
->where("email", $user->getEmailForPasswordReset())
->orWhere("mobile", $user->getMobileForPasswordReset())
->first();
return $record &&
! $this->tokenExpired($record["created_at"]) &&
$this->hasher->check($token, $record["token"]);
}
It throws exception like:
"Declaration of App\Auth\DatabaseTokenRepository::getPayload($email, $mobile, $token) must be compatible with Illuminate\Auth\Passwords\DatabaseTokenRepository::getPayload($email, $token)"
Valid workaround is original #miken32 answer on Password reset in Laravel 5.5 by email or mobile
But with complete re-implementation of DatabaseTokenRepository class, like:
<?php
namespace App\Auth;
use Carbon\Traits\Creator;
use Illuminate\Auth\Passwords\TokenRepositoryInterface;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
class DatabaseTokenRepository implements TokenRepositoryInterface
{
/**
* The database connection instance.
*
* #var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* The Hasher implementation.
*
* #var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* The token database table.
*
* #var string
*/
protected $table;
/**
* The hashing key.
*
* #var string
*/
protected $hashKey;
/**
* The number of seconds a token should last.
*
* #var int
*/
protected $expires;
/**
* Minimum number of seconds before re-redefining the token.
*
* #var int
*/
protected $throttle;
/**
* Create a new token repository instance.
*
* #param \Illuminate\Database\ConnectionInterface $connection
* #param \Illuminate\Contracts\Hashing\Hasher $hasher
* #param string $table
* #param string $hashKey
* #param int $expires
* #param int $throttle
* #return void
*/
public function __construct(ConnectionInterface $connection, HasherContract $hasher,
$table, $hashKey, $expires = 60,
$throttle = 60)
{
$this->table = $table;
$this->hasher = $hasher;
$this->hashKey = $hashKey;
$this->expires = $expires * 60;
$this->connection = $connection;
$this->throttle = $throttle;
}
/**
* Determine if the token has expired.
*
* #param string $createdAt
* #return bool
*/
protected function tokenExpired($createdAt)
{
return Carbon::parse($createdAt)->addSeconds($this->expires)->isPast();
}
/**
* Determine if the given user recently created a password reset token.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #return bool
*/
public function recentlyCreatedToken(CanResetPasswordContract $user)
{
$record = (array) $this->getTable()->where(
'phone', $user->getPhoneForPasswordReset()
)->first();
return $record && $this->tokenRecentlyCreated($record['created_at']);
}
/**
* Determine if the token was recently created.
*
* #param string $createdAt
* #return bool
*/
protected function tokenRecentlyCreated($createdAt)
{
if ($this->throttle <= 0) {
return false;
}
return Carbon::parse($createdAt)->addSeconds(
$this->throttle
)->isFuture();
}
/**
* Delete a token record by user.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #return void
*/
public function delete(CanResetPasswordContract $user)
{
$this->deleteExisting($user);
}
/**
* Delete expired tokens.
*
* #return void
*/
public function deleteExpired()
{
$expiredAt = Carbon::now()->subSeconds($this->expires);
$this->getTable()->where('created_at', '<', $expiredAt)->delete();
}
/**
* Create a new token for the user.implements TokenRepositoryInterface
*
* #return string
*/
public function createNewToken()
{
return hash_hmac('sha256', Str::random(40), $this->hashKey);
}
/**
* Get the database connection instance.
*
* #return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Begin a new database query against the table.
*
* #return \Illuminate\Database\Query\Builder
*/
protected function getTable()
{
return $this->connection->table($this->table);
}
/**
* Get the hasher instance.
*
* #return \Illuminate\Contracts\Hashing\Hasher
*/
public function getHasher()
{
return $this->hasher;
}
public function create(CanResetPasswordContract $user)
{
$mobile = $user->getPhoneForPasswordReset();
$this->deleteExisting($user);
$token = $this->createNewToken();
$this->getTable()->insert($this->getPayload($mobile, $token));
return $token;
}
protected function deleteExisting(CanResetPasswordContract $user)
{
return $this->getTable()
->where('phone', $user->getPhoneForPasswordReset())
->delete();
}
protected function getPayload($mobile, $token)
{
return ['phone' => $mobile, 'token' => $this->hasher->make($token), 'created_at' => new Carbon];
}
public function exists(CanResetPasswordContract $user, $token)
{
$record = (array) $this->getTable()
->where('phone', $user->getPhoneForPasswordReset())
->first();
return $record &&
! $this->tokenExpired($record['created_at']) &&
$this->hasher->check($token, $record['token']);
}
}

ReflectionException Class app\Repositories\MailMessageRepository does not exist

i'm having trouble accessing a repository, I can't call functions. I'm trying to integrate a softdelete button on my MailMessages datatable but I can't use the repository, I recived the following message:
ReflectionException Class app\Repositories\MailMessageRepository does
not exist
My MailMessageController
<?php
namespace App\Http\Controllers;
use App\DataTables\MailMessageDataTable;
use App\Http\Requests\MailMessageRequest;
use app\Repositories\MailMessageRepository;
use App\MailMessage;
use Illuminate\Http\Request;
use DataTables;
use PulkitJalan\Google\Facades\Google;
class MailMessageController extends Controller
{
protected $mailMessageRepository;
/**
* UserController constructor.
* #param $mailmessageRepository
*/
public function __construct(mailmessageRepository $mailmessageRepository)
{
parent::__construct();
$this->MailMessageRepository = $mailmessageRepository;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(MailMessageDataTable $MailMessageDataTable)
{
return $MailMessageDataTable->render('mailmessage.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
// $MailMessage = $this->MailMessageRepository;
return view('mailmessage.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(MailMessageRequest $request)
{
$MailMessage = $this->MailMessageRepository->saveMailMessage($request);
return redirect()->route('MailMessage.show', ["id" => $MailMessage->id])
->with(["message" => __('messages.create.success')]);
}
/**
* Display the specified resource.
*
* #param \App\MailMessage $mailMessage
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$MailMessage = MailMessage::find($id);
return view('MailMessage.show', ['MailMessage' => $MailMessage]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\MailMessage $mailMessage
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$MailMessage = MailMessage::find($id);
return view('MailMessage.edit', ['MailMessage' => $MailMessage]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\MailMessage $mailMessage
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$MailMessage = MailMessage::find($id);
$MailMessage->type = $request->type;
$MailMessage->description = $request->description;
$MailMessage->from_value = $request->from_value;
$MailMessage->to_value = $request->to_value;
$MailMessage->update();
return redirect('MailMessage/' .$MailMessage->id)->with(["message" => __('messages.edit.success')]);
}
/**
* Remove the specified resource from storage.
*
* #param \App\MailMessage $mailMessage
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$MailMessage = $this->MailMessageRepository->getMessagebyId($id, true);
if ($MailMessage->trashed()) {
$MailMessage->restore();
}else{
$MailMessage->delete();
}
return redirect()->route('MailMessage.index')
->with(["message" => __('messages.update.success')]);
}
public function digest_report(MailMessage $mailMessage)
{
}
}
my MailMessageRepository
<?php
namespace App\Repositories;
use App\User;
use App\MailMessage;
use App\Enums\MailMessageType;
use Illuminate\Support\Facades\Auth;
class MailMessageRepository
{
public function getMessage($id, $trashed = false)
{
if($trashed){
return MailMessage::withTrashed();
}
return MailMessage;
}
public function getMessageById($id, $trashed = false)
{
if ($trashed) {
return MailMessage::withTrashed()->with('roles')
->where('id', '=', $id)->first();
}
return MailMessage->where('id', '=', $id)->first();
}
public function deleteMailMessage($id)
{
$MailMessage = MailMessage::find($id);
$MailMessage->delete();
}
public function saveMailMessage($request)
{
$MailMessage = new Message($request->all());
$MailMessage->save();
return $MailMessage;
}
public function setOAuthAccessToken($accessToken)
{
}
public function updateMailMessage($request, $id) {
}
}
Maybe something wrong, you declare mailMessageRepository variable so you need to use $this->mailMessageRepository
public function __construct(mailmessageRepository $mailmessageRepository)
{
parent::__construct();
$this->MailMessageRepository = $mailmessageRepository;
}
try this
public function __construct(MailMessageRepository $mailmessageRepository)
{
parent::__construct();
$this->mailMessageRepository = $mailmessageRepository;
}
and try replace all $this->MailMessageRepository to $this->mailMessageRepository in your code

Laravel - Query scopes across models

In a nutshell, I want to create a function that my query scopes can use across multiple models:
public function scopeNormaliseCurrency($query,$targetCurrency) {
return $query->normaliseCurrencyFields(
['cost_per_day','cost_per_week'],
$targetCurrency
);
}
I have got my logic working within this scope function no problem, but I want to make this code available to all my models, as there are multiple currency fields in different tables and I don't want to be replicating the code in each query scope - only specify the columns that need attention.
So, where would I make my function normaliseCurrencyFields? I have extended the Model class as well as used the newCollection keyword to extend Collection but both result in Call to undefined method Illuminate\Database\Query\Builder::normaliseCurrencyFields() errors.
I have looked into Global Scoping but this seems to be localised to a Model.
Am I along the right lines? Should I be targeting Eloquent specifically?
Create an abstract base model that extends eloquent then extend it with the classes you want to have access to it. I do this for searching functions, uuid creation, and class code functions. So that all of my saved models are required to have to certain attributes and access to my searching functions. For instance I created a static search function getobjectbyid(). So that when extended I can call it like so:
$user = User::getobjectbyid('habwiifnbrklsnbbd1938');
Thus way I know I am getting a user object back.
My base model:
<?php
/**
* Created by PhpStorm.
* User: amac
* Date: 6/5/17
* Time: 12:45 AM
*/
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
abstract class Model extends Eloquent
{
protected $guarded = [
'class_code',
'id'
];
public $primaryKey = 'id';
public $incrementing = false;
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
$this->class_code = \App\Enums\EnumClassCode::getValueByKey(get_class($this));
$this->id = $this->class_code . uniqid();
return $this;
}
public static function getObjectById($id){
$class = get_called_class();
$results = $class::find($id);
return $results;
}
public static function getAllObjects(){
$class = get_called_class();
return $class::all();
}
my user model:
<?php
namespace App;
use Mockery\Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Model as Model;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'contact', 'username', 'email_address'
];
/**
* The column name of the "remember me" token.
*
* #var string
*/
protected $rememberTokenName = 'remember_token';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token', 'active'
];
/**
* the attributes that should be guarded from Mass Assignment
*
* #var array
*/
protected $guarded = [
'created_at', 'updated_at', 'password_hash'
];
/**
* Define table to be used with this model. It defaults and assumes table names will have an s added to the end.
*for instance App\User table by default would be users
*/
protected $table = "user";
/**
* We have a non incrementing primary key
*
* #var bool
*/
public $incrementing = false;
/**
* relationships
*/
public function contact(){
// return $this->hasOne(Contact::class, 'id', 'contact_id');
return $this->hasOne(Contact::class);
}
public function customers(){
// return $this->hasOne(Contact::class, 'id', 'contact_id');
return $this->hasMany(Customer::class);
}
/**
* User constructor.
* #param array $attributes
*/
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
// Your construct code.
$this->active = 1;
return $this;
}
/**
* #param $password string
* set user password_hash
* #return $this
*/
public function setPassword($password){
// TODO Password Validation
try{
$this->isActive();
$this->password_hash = Hash::make($password);
$this->save();
} catch(\Exception $e) {
dump($e->getMessage());
}
return $this;
}
/**
* Returns whether or not this use is active.
*
* #return bool
*/
public function isActive(){
if($this->active) {
return true;
} else {
Throw new Exception('This user is not active. Therefore you cannot change the password', 409);
}
}
public function getEmailUsername(){
$contact = Contact::getObjectById($this->contact_id);
$email = Email::getObjectById($contact->email_id);
return $email->username_prefix;
}
/**
* #return string
*
* getFullName
* returns concatenated first and last name of user.
*/
public function getFullName(){
return $this->first_name . ' ' . $this->last_name;
}
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName(){
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier(){
return $this->{$this->getAuthIdentifierName()};
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword(){
return $this->password_hash;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken(){
if (! empty($this->getRememberTokenName())) {
return $this->{$this->getRememberTokenName()};
}
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value){
if (! empty($this->getRememberTokenName())) {
$this->{$this->getRememberTokenName()} = $value;
}
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName(){
return $this->rememberTokenName;
}
/**
* Get the e-mail address where password reset links are sent.
*
* #return string
*/
public function getEmailForPasswordReset(){
}
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token){
}
public function validateAddress(){
}
}
a TestController:
public function test(){
$user = User::getObjectById('USR594079ca59746');
$customers = array();
foreach ($user->customers as $customer){
$contact = Contact::getObjectById($customer->contact_id);
$name = PersonName::getObjectById($contact->personname_id);
$c = new \stdClass();
$c->id = $customer->id;
$c->name = $name->preferred_name;
$customers[] = $c;
}
$response = response()->json($customers);
return $response;
}
Take note on how getObjectById is extended and available to my other classes that extend my base model. Also I do not have to specify in my user model an 'id' or 'class_code' and when my user model is constructed it calls the parent constructor which is the constructor on my base model that handles 'id' and 'class_code'.

Resources