Few Laravel quick tips

This time I would like to share few Laravel quick tips, which I use and it help me to make some things faster and cleaner code.

In Routes, you can create a group within a group. Also, assign a certain middleware only to some of them.

Route::group(['prefix' => 'user', 'as' => 'user.'], function() {
 Route::get('login', 'UserController@login');
 Route::get('register', 'UserController@register');
 Route::group(['middleware' => 'auth'], function() {
   Route::get('edit', 'UserController@edit');

Increment or decrement column value.

// increment by one
// increment by 50
User::find($userId)->increment('points', 50);

No timestamp columns

If you don’t need created_at and updated_at timestamps, you can easily disable them.

class Article extends Model
   public $timestamps = false;

Soft-deletes: multiple restore

If you use soft-delete it’s an easy way to restore multiple records.

Article::withTrashed()->where('author_id', 1)->restore();

Preview email before sending

If you are using Mailables to send emails, you can preview the result without sending them. You can review directly in your browser. Just return a Mailable as route result:

Route::get('/email', function () {
 return new App\Mail\InvoicePaid(App\Invoice::find(1));

Get view without create Controllers

If you want the route to show a certain view, you don’t need to create a Controller method. You can do it in a simple way:

// Instead of creating controller
Route::get('about', 'PageController@about');

class PageController extends Controller
 public function about()
 return view('pages.about');
// Do this
 in your routes file
Route::view('about', 'pages.about');

Check if user is authenticated in blade

Instead of if-statement to check logged in user, we can use @auth.

 // The user is authenticated.
The opposite is @guest directive.
 // The user is not authenticated.

Column name change

Sometimes you need to change column in your query. In Eloquent Query Builder, you can specify “as” to return any column with a different name. For example:

$items = DB::table('article')
->select('title', 'author_id as article_author_id')

Return default model

It’s possible to assign a default model in belongsTo relationship, to avoid fatal errors when calling it. For example we need attribute name from user {{ $post->user->name }} and $post->user doesn’t exist. Use function withDefault() like:

public function user()
 return $this->belongsTo('App\User')->withDefault();

Debug query

Did you know that you can use dd() to debug query.

User::where('name', 'Demo')->dd();

Eager loading with specific columns

You can do eager loading with the exact columns you want to get from the relationship.

$articles = App\Article::with('author:id,name')->get();

An easy way to calculate child relationships records

You don’t need to do specific queries to get related records count if you are using hasMany() relationship. Use withCount(). For example:

$users = User::withCount(['posts'])->get();

And then, in your Blade file, access count number with [relationship]_count property.

{{ $user->posts_count }}

Update model dates

If you want to update updated_at field on the database table for the given model.

$article = Article::find($id);

Capitalize translations parameters values

In translation files it’s possible to specify variables not only as
:variable, but also capitalized as :VARIABLE or :Variable – and then whatever value you pass – will be also capitalized automatically. Magic!

// resources/lang/en/example.php
'welcome' => 'Welcome, :Name'
// Result will be: "Welcome, Demo"
echo __('example.welcome', ['name' => 'demo']);

Leave a Reply

Your email address will not be published. Required fields are marked *