It would be great if you found this article containing 20 very useful and advanced Useful Laravel Tips that will help you in your future projects and I will only talk about some tips that caught my interest and find that I will use them a lot but visit the source for more depth https://ashallendesign.co.uk/blog/20-useful-laravel-tips
- Using DATETIME Fields Instead of Booleans
class Post extends Model
{
public function isPublished(): bool
{
return $this->published_at !== null; // is_published
}
}
- Using 'when' in PendingRequest
$http = Http::withBasicAuth($username, $password);
if (app()->environment('local')) {
$http->withoutVerifying();
}
// with when
$http = Http::withBasicAuth($username, $password)
->when(app()->environment('local'), function (PendingRequest $request) {
$request->withoutVerifying();
});
- Using getOrPut() in Collections
if (! $collection->has($key)) {
$collection->put($key, $this->builtItem($data));
}
return $collection->get($key);
// getOrPut()
return $collection->getOrPut($key, fn () => $this->buildItem($data));
- Debugging HTTP Requests
Http::dump()->get($url);
Http::dd()->get($url);
- Replicating Models
you can duplicate a model like so
$post = Post::find(123);
$copiedPost = $post->replicate();
$copiedPost->save();
If you want to exclude properties from being copied, you can pass the field names as an array into the method
$post = Post::find(123);
$copiedPost = $post->replicate([
'author_id',
]);
$copiedPost->save();
Additionally, the replicate method creates an unsaved model, so you can chain your usual model methods together. For example, we can copy the model and add " (copy)" on to the end of the title so that we can see that its been replicated
$post = Post::find(123);
$copiedPost = $post->replicate([
'author_id',
])->fill([
'title' => $post->title.' (copy)',
]);
$copiedPost->save();
- Using 'wasRecentlyCreated' on Models
$user = User::firstOrCreate(
['email' => request('email')],
['name' => request('name')],
);
if ($user->wasRecentlyCreated) {
// Your user was just created...
} else {
// Your user already exited and was fetched from the database...
}
- Moving Logic into Methods
let's say that we want to check if a user is approved. Our code might look like so
if ($user->approved === Approval::APPROVED) {
// Do something...
}
our model might now look like this
class User extends Model
{
public function isApproved(): bool
{
return $this->approved === Approval::APPROVED;
}
}
// now
if ($user->isApproved()) {
// Do something...
}
- Changing the Key for Route Model Binding
let's say that you have a route that accepts a blog post's slug
Route::get('blog/{slug}', [BlogController::class, 'show']);
// Model
use App\Actions\PublishPost;
use App\Models\Post;
class BlogController extends Controller
{
public function show($slug)
{
$post = Post::where('slug', $slug)->firstOrFail();
return view('blog.show', [
'post' => $post,
]);
}
}
to simplify this code and clean it up, we could update the slug parameter to be post:slug instead
Route::get('blog/{post:slug}', [BlogController::class, 'show']);
// Model
use App\Actions\PublishPost;
use App\Models\Post;
class BlogController extends Controller
{
public function show(Post $post)
{
return view('blog.show', [
'post' => $post,
]);
}
}
I hope you enjoyed these tips .
Top comments (1)
Beautiful. Thank you.
Route::get('blog/{slug}', [BlogController::class, 'show']); // but i'd advise committing to this if what you really want, to avoid any hiccups, by adding
public function getRouteKeyName()
{
return 'slug';
}
to the model class. Just my piece of thought on this though.