Author - StudySection Post Views - 375 views
Laravel tips

Some tips for the laravel framework

Let’s go through some tips and tricks which we can add to Laravel applications to optimize website performance.

  1. Invokable Controllers:

    If you want to create a controller with just one action in Laravel, you can use the __invoke() method and even create an “invokable” controller.
    Example:

    Class ControllerName extends controller {
    Public function _invoke($id){
    return view(‘user.profie’, [‘user’ => User::findOrFail($id)]);
    }}
    Routes: Route::get('user/{id}' ‘ControllerName’);

    Command to generate command:
    php artisan make:controller ControllerName --invokable

  2. Unsigned Integer:

    For foreign key migrations instead of integer() we should use unsignedInteger() type or integer()->unsigned() , otherwise you may get SQL errors.
    Example: Schema::create('employees', function (Blueprint $table) {
    $table-> unsignedInteger ('company_id'); //if primary id Increments
    $table->foreign('company_id')->references('id')->on('companies');
    });

  3. OrderBy with Eloquent: You can specify orderBy() directly on your Eloquent relationships.

    Example: return $this->hasMany(Product::class)->orderBy('name');

  4. Raw DB Queries: You can use RAW DB queries in various places, including havingRaw() function after groupBy().

    Example: Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();

  5. Eloquent where date methods: In Eloquent, check the date with functions whereDay() , whereMonth() , whereYear() , whereDate() and whereTime() .

    Example:
    $products = Product::whereDate('created_at', '2018-01-31')->get();
    $products = Product::whereMonth('created_at', '12')->get();
    $products = Product::whereDay('created_at', '31')->get();
    $products = Product::whereYear('created_at', date('Y'))->get();
    $products = Product::whereTime('created_at', '=', '14:13:58')->get();

  6. Route group within a group: In Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the “parent” group.
    Example:
    Route::group(['prefix' => 'account', 'as' => 'account.'], function() {
    Route::get('login', 'AccountController@login');
    Route::get('register', 'AccountController@register');
    Route::group(['middleware' => 'auth'], function() {
    Route::get('edit', 'AccountController@edit');
    });
    });
  7. Increments and decrements: if we want to increment some DB column in some table in Laravel, just use increment() function. We can increment value with any number.

    Example:
    Post::find($post_id)->increment('view_count');
    User::find($user_id)->increment('points', 50);

  8. We can check if the View file exists before actually loading it.
    Example:
    if (view()->exists('custom.page')) {
    // Load the view
    }
  9. No timestamp columns in the table: If our DB table doesn’t contain timestamp fields created_at and updated_at, we can specify that the Eloquent model wouldn’t use them, with $timestamps = false property.
    Example:
    class Company extends Model
    {
    public $timestamps = false;
    }
  10. Database migrations column types:
    $table->geometry('positions');
    $table->ipAddress('visitor');
    $table->macAddress('device');
    $table->point('position');
    $table->uuid('id');

    See all column types: visit here

  11. Soft-deletes: multiple restores: When using soft-deletes, we can restore multiple rows in one sentence.

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

  12. Don’t create Controllers when we want the route to just show a certain view:
    Just use Route::view() function
    Route::view('about', 'texts.about');
  13. Image validation: While validating uploaded images, we can specify the dimensions that are required.
    Example:
    'photo' => 'dimensions:max_width=4096,max_height=4096'
  14. Blade @auth: Instead of if-statement to check logged in user, use @auth directive.
    Example:
    @auth
    // The user is authenticated.
    @endauth
  15. To Fail or Not to Fail function: In addition to findOrFail(), there’s also the Eloquent method firstOrFail() which will return a 404 page if no records for the query are found.
    Example:
    $user=User::where('email','codechief@gmail.com')->firstOrFail();
  16. More convenient DD: Instead of doing dd($result); you can put ->dd() as a method directly at the end of your Eloquent sentence, or any Collection.
    Example:
    // Instead of
    $users = User::where('name', 'Taylor')->get();
    dd($users);
    // Do this
    $users = User::where('name', 'Taylor')->get()->dd();
  17. How to avoid error in {{ $post->user->name }} if user is deleted? :
    You can assign a default model in belongsTo relationship, to avoid fatal errors when calling it like {{ $post->user->name }} if $post->user doesn’t exist.

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

  18. Redirect to Specific Controller Method: We can redirect() not only to URL or specific route, but to a specific Controller’s specific method, and even pass the parameters. Use this:
    Example: return redirect()->action('SomeController@method',['param' => $value]);
  19. Update parent updated_at easily: If we are updating a record and want to update the updated_at column of the parent relationship (like, we add new post comment and want posts.updated_at to renew), just use $touches = [‘post’]; property on child model.
    Example:
    class Comment extends Model
    {
    /**
    * All of the relationships to be touched.
    *
    * @var array
    */
    protected $touches = ['post'];
    }
  20. Use withCount() to Calculate Child Relationships Records: If you have hasMany() relationship, and you want to calculate “children” entries, don’t write a special query. For example, if you have posts and comments on your User model, write this withCount() :
    public function index()
    {
    $users = User::withCount(['posts', 'comments'])->get();
    return view('users', compact('users'));
    }

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Leave a Reply

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

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri