Define a Variable in Laravel Construct Method and use in all Methods

In this tutorial we will discuss, how to use a variable in all methods of a class by passing constructor.

Laravel define a variable in constructor

If you wanna define a variable once and use on many methods of same controller then use that variable in constructor by $this keyword.

Example controller

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller{
  public function __construct(){
    $this->name = "anmol sharma";
  }

  public function index(){
    $userName = $this->name;
    echo "user name is". $userName;
  }
}

You read this tutorial on advanced web tuts provided by anmol sharma.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links