More Useful Laravel Tips
Tags: webdev, laravel, php, programming
Published: 2022-05-05 14:59:11

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

```php
class Post extends Model
{
    public function isPublished(): bool
    {
        return $this->published_at !== null; // is_published
    }
}
```

- Using 'when' in PendingRequest

```php
$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

```php
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

```php
Http::dump()->get($url);
Http::dd()->get($url);
```

- Replicating Models

you can duplicate a model like so
```php
$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
```php
$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
```php
$post = Post::find(123);
$copiedPost = $post->replicate([
    'author_id',
])->fill([
    'title' => $post->title.' (copy)',
]);
$copiedPost->save();
```

- Using 'wasRecentlyCreated' on Models

```php
$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
```php
if ($user->approved === Approval::APPROVED) {
  // Do something...
}
```
our model might now look like this
```php
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
```php
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
```php
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 .