alexeymezenin / laravel-best-practices Goto Github PK
View Code? Open in Web Editor NEWLaravel best practices
Laravel best practices
Hi!
The Validation example just uses Request
as class to inherit. However laravel by default creates a FormRequest
instead. What I need is a request to validate my json, but I currently do not know which one is the right one. Maybe you could add some more hints to this example?
Добавьте, пожалуйста, пункт к "Соглашение сообщества об именовании", как правильно именовать переменные в представлении? CamelCase или underscore?
$user->full_name vs. $user->fullName ?
Redis can use as standard Laravel tools accepted by community?
E.g.:
$router->get('/users/forgot_password', 'UserController@forgotPassword');
or
$router->get('/users/forgot-password', 'UserController@forgotPassword');
or
$router->get('/users/forgotPassword', 'UserController@forgotPassword');
there's no clue in Resource Controllers doc, but I guess forgot-password seems to be the way to go.
Can't we make it more clear by name if the "class" is a trait or an interfaces as they both are adjectives now. I understand the reasoning but we also need a solution (I think). We might consider recommending creating an interface for every trait.
An example - services.
Might be curious for people who see this first time, where to put Service classes.
I saw people who told to go app/Services
and app/Http/Services
. Some advices might be worth it. My opinion.
P. S. If I'm allowed, I'll contribute my own "opinion".
Is this really working?
// Model
protected $dates = ['ordered_at', 'created_at', 'updated_at']
public function getSomeDateAttribute($date)
{
return $date->format('m-d');
}
// View
{{ $object->ordered_at->toDateString() }}
{{ $object->ordered_at->some_date }}
Is it really adding a property on the fly to the Carbon object?
$object->ordered_at->some_date
doesn't really read fluent...
Camel case prefixed with test. testGuestCannotSeeArticle()
Descriptive names delimited by underscore
<?php
/** @test **/
public function guests_cannot_see_article(){
//Do Something.
}
?>
Laravel's own tutorials don't even follow the camel case standard.
https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/2
https://laracasts.com/series/phpunit-testing-in-laravel/episodes/2 (This one describes both but shows why underscored version is preferred in Laravel)
Hi @alexeymezenin
I translated it and write in my blog
I want you to add Vietnamese language. Is it necessarily on the Github Repository?
Hey, just came here to look for the best practices for Blade components.
ie.
php artisan make:component LongComponentName
Hi!
I found some very useful stuff in here, that makes it easier for me as a beginner to get things right. What I did not understand yet is how to properly convert a model from and to json. I've posted my question on stackoverflow, so more people can find it. If someone has a good tip on that, we could add it to this repository as well.
Thanks :)
request()->all() can be dangerous because when used may cause a security vulnerability.
for example:
# database
users:
- id
- username
- password
- email
- superuser (bool)
# controller
public function store(Request $request) {
User::create($request->all());
return back()->with('alert', 'user created!');
}
if am i a hacker-boy and send a payload with input[name=superuser]=1
magically I will become a superadmin.
bad:
public function store(Request $request) {
User::create($request->all());
return back()->with('alert', 'user created!');
}
good:
public function store(Request $request) {
User::create($request->only('username', 'password', 'email'));
return back()->with('alert', 'user created!');
}
First, thank you to those who have made this possible, as a new developer I find this extremely helpful!
I was wondering if there's a way to print this out so I can have it available offline for when I'm not at my desk.
How to name?
Views
Assets
What is the best practice for the translation variables?
for example __('some variable')
do we do it as snake_case or kebab-case or camelCase?
is it Route::resource('master-products','MasterProductController')
or Route::resource('masterProducts','MasterProductController')
?
For what version of Laravel this best practices?
like when we say php artisan make: resource SomeResouce
should we make them singular, or plural, or in which cAsEs?
...are you alive?
I suppose you have better things to do and I'm happy with it but couldn't you add other maintainers?
Hey there, Alexey!
I want to translate these wonderful practices in Ukrainian language.
Which font and its size I need to use for the image of Laravel?
That info would be enough for me to start the translation.
Thank you!
I was just wondering what the best practices are or what the community's thoughts are on when to use:
a) Constructor injection
b) Method injection
c) Facades
d) Global helper functions
Should we update the linked PSR standard to PSR-12?
Does it make sense to recommend database naming in context of PHP framework?
May be this is confusing for less experienced developers?
And implies violation of best practices, if database is already designed using singular naming style?
Are these practices of database naming possible, if database is already designed using singular naming style?
https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions
Does it means that singular naming at database is not good for Laravel?
For example:
And etc.
Hi, alexeymezenin!
I'm writing here because I don't know how to contact you.
First, thank you for a good article laravel best practices.
I want to spread this good article in Korea.
So I want to translate Korean. If you allow I'll fork your branch and then translate it.
Thanks :D
Class CreateUserRequest
{
public function rules()
{
return [
// ...
];
}
public function getUserDto()
{
return new UserDto(
$this->input('user_name', null),
// ...
);
}
}
Class UserController
{
public function createUser(CreateUserRequest $request, UserCreator $creator)
{
$dto = $request->getUserDto();
DB::transaction(function () use ($creator, $dto) {
$user = $creator->createUser($dto);
$user->save();
});
// ...
}
}
Class CreateUserCommand
{
public function handle(UserCreator $creator)
{
$dto = new UserDto(
$this->argument('user_name'),
// ...
);
DB::transaction(function () use ($creator, $dto) {
$user = $creator->createUser($dto);
$user->save();
});
// ...
}
}
whereHas()
example.whereHas()
to exists
subquery.class UserCreator
{
public function createUser(UserDto $dto)
{
$user = new User();
$user->name = $dto->getUserName();
// You can hook into Model Validation(==Business Policy) logic here
// With mass assignment, you will loose the model validation chance
// ...
return $user;
}
}
class UserModifier
{
public function modifyUser(User $user, UserDto $dto)
{
$name = $dto->getUserName();
if ($name !== null) {
// Again you can do the model validation here
$user->name = $name;
}
// ...
// Donot return the $user, because it was passed by reference.
}
}
https://github.com/alexeymezenin/laravel-best-practices#single-responsibility-principle
That example, while probably contrived, as the first example in the document seems to signal to the reader that calling auth()
inside a model (they are model methods after all, they have get*Attribute()
) is a good thing or widely accepted thing to do. Is this the case? I have not seen this in the wild much (auth() calls probably best exist in the controller or view layers).
If it's purely serving to demonstrate single responsibility, is there a better contrived use case to use? Are you open to this change?
just reaching out regarding few posted materials on http://www.laravelbestpractices.com/
which is referenced from this repo, mostly from this section:
https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions
as per conversation in email, I had placed a link to this repo, under the "Project Contributors". Apologies for delays on putting it on.
Regards,
Darwin
Подскажите, пожалуйста такие пакеты для передачи данных.
Возможно узнать вашу почту или контакты, для вопросов?
можете ответить на почту [email protected]
Читал статью, очень понравилось
Есть упоминание
"Еще лучше использовать специализированный пакет для передачи данных из бэкенда во фронтенд."
Какой пакет порекомендовали бы?
This is the rquest body:
{
"arr": [
{
"a": 3,
"b": 3
},
{
"a": 3,
"b": 3
}
]
}
and with this validations rules:
public function rules()
{
return [
// 'arr' => 'array',
'arr.*.a' => 'required'
];
}
The result of dd($request->validated());
is what I want, I don't need b
to be included
"arr" => array:2 [
0 => array:1 [
"a" => 3
]
1 => array:1 [
"a" => 3
]
]
But when I want to validate the array itself like this:
public function rules()
{
return [
'arr' => 'array',
'arr.*.a' => 'required'
];
}
b
will be added to the output
"arr" => array:2 [
0 => array:1 [
"a" => 3,
"b" => 3
]
1 => array:1 [
"a" => 3,
"b" => 3
]
]
There is no way to exclue b
from the array and it will cause the following error:
Message
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base_require' in 'field list' (SQL: insert into product_variation_unit (base, base_require, max, min, name, product_variation_id, unit_id) values (1000, ?, 10000, 1000, کیلو, 2036, 1))
Level
ERROR
Exception
{
"class": "Illuminate\\Database\\QueryException",
"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base_require' in 'field list' (SQL: insert into product_variation_unit (base, base_require, max, min, name, product_variation_id, unit_id) values (1000, ?, 10000, 1000, \u06a9\u06cc\u0644\u0648, 2036, 1))",
"code": "42S22",
Discussion about it: https://stackoverflow.com/questions/58851288/using-validated-method-with-array-in-laravel
This poll was created based on a suggestion by the author: #44 (comment)
Please upvote with a thumbs up and downvote with a thumbs down.
Is better for generate 1 page PDF like cheat sheet for this?
The part on getting data to JS says this:
The best way is to use specialized PHP to JS package to transfer the data.
What package would that be?
Laravel Sail is provided as the official Laravel development environment.
So I think this article needs to reflect that 🤔
A table is a schema to hold structured information and it often corresponds with a object oriented class that is singular. Its confusing when the Model / Class does not match the Table name.
I am using the bad way.
$apiKey = env('API_KEY');
Laravel 5.7
I followed the steps, when i use
{{ $user->dob->some_date }}
getting error Unknown getter 'some_date'
Under the single responsibility principle "good" example, should the return type for getFullNameAttribute() be "string" and not "bool"?
public function getFullNameAttribute(): bool
{
return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort();
}
Composer can use as standard Laravel tools accepted by community like grunt, gulp?
Or may be composer is 3rd party packages?
Thank you for your work and setting all this gems in one place.
Whenever I have chance I point people on SO to this.
Can you tell something about my doubt here:
Having products
and product_attributes
tables should pivot be product_product_attribute
or product_attribute_product
still following alphabetical convention?
Thanks, Goran
Is there a particular convention that should be followed for Request classes? For example, if I need different Request class for store
and update
, instead of PostRequest
, what should I name my Request classes?
NewPostRequest
and UpdatePostRequest
?
PostNewRequest
and PostUpdateRequest
?
StorePostRequest
and UpdatePostRequest
?
PostStoreRequest
and PostUpdateRequest
?
Something else entirely?
Laravel UI build-in:
should controllers/views sub-dir be singular or plural?
for example: https://github.com/settings/profile
Controllers/Settings/ProfileController.php
or Controllers/Setting/
views/settings/profile.blade.php
or views/setting/
settings.profile
or setting.profile
the only issue i have is with pivot_tables.. most times you want to name them so when you look at your tables in database you know what they are.. user_article may not tell you but something like users_favourited_article etc will
Can be found here!
What about using interface with repository classes?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.