10 Laravel Tricks You Shouldn't Miss

10 Laravel Tricks You Shouldn't Miss

Introduction

Hello everyone. The topic of this post is to summarize some small tips when coding with Laravel. Laravel is one of the most popular PHP frameworks for building web applications. It's known for its clear syntax and rich features. In this article, we'll explore 10 Laravel tricks that can make your development process more efficient and enjoyable.

10 Laravel Tricks You Shouldn't Miss
10 Laravel Tricks You Shouldn't Miss

Cache Database Queries

When your project uses too many database queries, over time our application will become very slow. Luckily, Laravel has provided us with a simple mechanism for caching queries by using the remember method, for example:

$news = News::remember(60)->get();

For the next hour, the above query will be stored in the cache and no longer needs to go through the database.

No Need to Create a Controller

If we just want the URL to show a view, we don't need to create a Controller. For example, instead of:

Route::get('intro', 'InfoController@intro');

and

class InfoController extends Controller
{
    public function intro()
    {
        return view('intro');
    }
}

We can just use:

Route::view('intro', 'intro');

Restore Multiple Soft Deleted Records

When using Laravel's soft delete feature, we can restore multiple records by using withTrashed and restore:

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

Disable timestamp

By default, Laravel will automatically update the values of the two fields created_at and updated_at for models. If we don't want to use them, just set the value of timestamp to false in the model. For example:

class Blog extends Model
{
    public $timestamps = false;
}

If we still want to use one of the two fields above, we can override it through the getUpdatedAtColumn method in the model:

public function getUpdatedAtColumn()
{
    return null;
}

or just declare in the model:

const CREATED_AT = null;
const UPDATED_AT = null;

increment and decrement

Suppose we want to increase or decrease the value of a field, for example:

  • Increase the view_count every time a user views a post.
  • After a product is paid for, it will automatically be deducted from inventory. We will use increment and decrement. For example:
Blog::find($post_id)->increment('view_count'); 

Product::find($product_id)->decrement('quantity', 50);

Check if a View Exists

We can check if a view exists before rendering it to the user through:

if (view()->exists('blog.page')) {
 // Load the view
}

Error Page

When we want to create an error notification page, for example, the HTTP Code 404 error, we just need to create a blade view with the error code as the file name, for example resources/views/errors/404.blade.php, Laravel will automatically map that 404 error to the page we just created.

dd()

Instead of having to write

$users = User::where('name', 'p2ptuts')->get();
dd($users);

we can add the dd() method directly to the end of the query:

$users = User::where('name', 'p2ptuts')->get()->dd();

Update Parent Model's updated_at Field

When we update a child model record and want to update the parent model's updated_at field as well, for example, when we add a comment to a post and want to update the parent model Post's updated_at, we just need to add $touches = ['post']; in the child model Comment.

Specifically:

class Comment extends Model
{

 protected $touches = ['post'];
}

 

Auth::once()

 

When we want the user to be logged in without creating any session or cookie (very useful for stateless APIs - APIs where after the client sends data to the server, the server executes it, returns the result, and then the "relationship" between the client and server is "cut off" - the server does not store any client data), we will use Auth::once():

if (Auth::once($credentials)) {
    // Do something here
}

References

https://laraveldaily.com/wp-content/uploads/2018/11/Laravel-Tips-2.pdf

https://laravel-news.com/eloquent-tips-tricks