Laravel New Project(5.0)

By ukmodak | March 31st 2024 10:38:02 AM | viewed 1035 times

How to create laravel new project(5.0)?

Server Requirements

Note: php version >= 5.4 support laravel 5.0 // xamp: 1.8.2 installer , portable cause problem for composer

Note: php version >= 5.3 support laravel 4.2 // xamp: 1.7.2 installer

Step-1:

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

Download URL:https://getcomposer.org/download/     download

click on composer.exe and select /xampp/php/php.exe from your xampp installation location

to to check composer installation and version add the following code

c:\users\Modak>composer

Step-2:Create-Project via Composer

Open your command console and to to htdocs directory like d/xampp/htdocs and write the following and enter

composer create-project laravel/laravel projectname version name

After create project browse the url:http://localhost/projectname/public and you will see a basic project

Step-3:To remove public folder:

Rename server.php in your Laravel root folder as index.php

Copy the .htaccess file from /public directory to your Laravel root folder then browse: http://localhost/projectname/

Step-4:About Configuration:

After installing Laravel, the first thing we need to do is to set the write permission for the directory storage and bootstrap/cache.

Generate Application key to secure session and other encrypted data. If the root directory doesn’t contain the .env file then rename the.env.example to .env and run the following command

d/xampp/htdocs/projectname> php artisan key:generate 

You can also configure the locale,time zone,additional component etc. of the application in the config/app.php file.

To rename your application name run the following command

d/xampp/htdocs/projectname> php artisan app:projectname 

To stop server/keep maintenance mode add these command

d/xampp/htdocs/projectname> php artisan down

To stop maintenance mode add these command

d/xampp/htdocs/projectname>php artisan up

In a local environment we need to see errors for debugging purposes. We need to hide these errors from users in production environment. This can be achieved with the variable APP_DEBUG set in the environment file .env stored at the root of the application. Add the following code on .env file

APP_DEBUG=true

Logging is an important mechanism by which system can log errors that are generated. It is useful to improve the reliability of the system. Laravel supports different logging modes like single, daily, syslog, and errorlog modes. You can set these modes in config/app.php file. add the following line

'log' => 'daily'

For database configuration in the application add the following line in .env file that are create in your database server manually

      DB_HOST=localhost
      DB_DATABASE=testone
      DB_USERNAME=root
      DB_PASSWORD=''
      CACHE_DRIVER=file
      SESSION_DRIVER=file

Then run the following command to create laravel basic three tables(password_resets,users,migrations)

d/xampp/htdocs/projectname> php artisan migrate
d/xampp/htdocs/projectname> php artisan config:cache

then browse http://localhost/projectname/auth/register then u can register

Note - After changing any configuration restart the Laravel server.

Step-5:Create Model and their relation using the following command

To create model write the following command one after another

	d/xampp/htdocs/projectname> php artisan make:model App\Models\Auth\Role
	d/xampp/htdocs/projectname> php artisan make:model App\Models\Auth\User_Role
 

Note-After this command automatically create role,user_role table script in the location database/migration/. if not then write the following command

	d/xampp/htdocs/projectname> php artisan make:migration create_basic_role_user_role_table 
 

then go to the location database/migration/ and edit create_basic_role_user_role_table.php file and replace all the following code

 
	<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAutheticationSetupTable extends Migration {

     public function up()
	{
        Schema::create('users', function(Blueprint $table)
		{
			$table->bigIncrements('id')->unsigned();
			$table->string('first_name')->nullable();
                        $table->string('last_name')->nullable();
                        $table->string('user_name')->nullable();
			$table->string('email')->nullable();
                        $table->string('mobile')->nullable();
			$table->string('password', 60);
			$table->rememberToken()->nullable();
			$table->dateTime('create_date')->nullable();
                        $table->dateTime('update_date')->nullable();
                        $table->tinyInteger('active')->default(1);
                        //$table->dropColumn(['votes', 'avatar', 'location']);
		});
		
        Schema::create('roles', function(Blueprint $table)
		{
			$table->bigIncrements('id')->unsigned();
			$table->string('role_name')->nullable();		
		});
                
		Schema::create('user_roles', function (Blueprint $table)
		{
			$table->bigInteger('user_id')->unsigned();
			$table->bigInteger('role_id')->unsigned();                     
			$table->foreign('user_id')->references('id')->on('users')->onDelate('cascade');
			$table->foreign('role_id')->references('id')->on('roles')->onDelate('cascade');
			$table->primary(['user_id', 'role_id']);
			
		});
	
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
	    Schema::drop('users');
		Schema::drop('roles');
		Schema::drop('user_roles');
	}
}
 

Note:when you update existing users table field, you must drop previous users table from database.Otherwise command generate error

Then run the following command to create table in the database

d/xampp/htdocs/projectname> php artisan migrate
d/xampp/htdocs/projectname> php artisan config:cache

Note:You can run this command to run specific folder script as:php artisan migrate --path=/database/migrations/select_folder/

Edit the model file app/User.php and the following code to maintain relation to other tables

        protected $table = 'users';
        public $timestamps = false;
        protected $guarded = ['id'];
	    protected $hidden = ['password', 'remember_token'];
        
        public function roles()
        {
            return $this->belongsToMany('App\Models\Auth\Role', 'user_roles', 'user_id', 'role_id');
        }
        
        public function hasAnyRole($roles)
        {
            if (is_array($roles)) {
                foreach ($roles as $role) {
                    if ($this->hasRole($role)) {
                        return true;
                    }
                }
            } else {
                if ($this->hasRole($roles)) {
                    return true;
                }
            }
            return false;
        }
    
        public function hasRole($role)
        {
            if ($this->roles()->where('role_name', $role)->first()) {
                return true;
            }
            return false;
        }

Edit the model file app/Models/Auth/Role.php and replace all the following code to maintain relation to other tables


<?php namespace App\Models\Auth;

use Illuminate\Database\Eloquent\Model;

class Role extends Model {

	    protected $table = 'roles';
        public $timestamps = false;
        protected $guarded = ['id'];
        
        
        public function users()
        {
            return $this->belongsToMany('App\User', 'user_roles', 'user_id', 'role_id');
        }

        public function findRole($userId)
        {
           if ($this->users()->where('id', $userId)) {
                return $this->users()->where('id', $userId);
            }
            return false;
        }

}

Edit the model file app/Models/Auth/User_Role.php and replace all the following code to maintain relation to other tables


<?php namespace App\Models\Auth;

use Illuminate\Database\Eloquent\Model;

class User_Role extends Model {

	    protected $table = 'user_roles';
        public $timestamps = false;

        public function users()
        {
            return $this->belongsTo('App\User', 'user_id', 'id');
        }
        
         public function roles()
        {
            return $this->belongsTo('App\Models\Auth\Role', 'role_id', 'id');
        }
}

Note: This relation are usefull on the view file if you use Eloquent ORM

Step-6:Create Controller using the following command

Add UserController in the location App\Http\Controllers\Auth\ using the following command

   d/xampp/htdocs/projectname> php artisan make:controller Auth\UserController 
 

After creating file replace all the following code

<?php namespace App\Http\Controllers\Auth;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use App\Models\Auth\Role;
use Carbon\Carbon;
use Session;
use DB;
use Auth;
use Illuminate\Support\Facades\Input;


class UserController extends Controller {

	public function index(Request $request)               
	{

            $un = (Input::get('un')? Input::get('un'):null); 
            $em = (Input::get('em')? Input::get('em'):null);
            $ac = (Input::get('ac')? Input::get('ac'):null); 
			//$dt = (Input::get('dt')? Carbon::createFromFormat('d/m/Y',Input::get('dt')):null); 
			 
            $users;
            $totalCount; 
            $pageNo = 10;
			
			if($un ||  $em || $ac) {
			
					 $users = User::orderBy('id','DESC')
					           ->where(function($query) use($un,$em,$ac){
							     if($un){
		                            $query->where('user_name','LIKE',"%$un%");
		                         }
								 if($em){
		                            $query->where('email','LIKE',"%$em%");
		                         }
								 if($ac){
		                            $query->where('active','=',$ac);
		                         }
		                       })
		                        ->paginate($pageNo)
		                        ->setPath(route('user/index',['un'=>$un,'em'=>$em,'ac'=>$ac]));
								
		            $totalCount = User::orderBy('id','DESC')
					           ->where(function($query) use($un,$em,$ac){
			                        if($un){
			                            $query->where('user_name','LIKE',"%$un%");
			                         }
									 if($em){
			                            $query->where('email','LIKE',"%$em%");
			                         }
									 if($ac){
			                            $query->where('active','=',$ac);
			                         }
		                         })
								 ->count();
 
          }else{
              
		            $users = User::orderBy('id','DESC')
		                        ->paginate($pageNo)
		                        ->setPath(route('user/index'));
								
		            $totalCount = User::orderBy('id','DESC')
								 ->count();
          }

           return view('auth.user_index',compact('users','totalCount','un','em','ac')) ->with('i', ($request->input('page', 1) - 1) * 5);

               
	}

	public function create()
	{
	    return view('auth.user_create');
	}
        
     
	public function store(Request $request)
	{
         
                   $this->validate($request, [
                     'user_name'       => 'regex:/^[A-Za-z0-9-_]{5,20}/',
                     'email' => 'required | email | unique:users',
                     'mobile' => 'required | unique:users',
                    ]);
                        
                        if($request->input('password')==$request->input('password_confirmation')){  
                            
                            $insert = User::create([
                              'first_name'=> $request->input('first_name'),
                              'last_name'=> $request->input('last_name'),
                              'user_name'=> $request->input('user_name'),
                              'email'=> $request->input('email'),
                              'mobile'=> $request->input('mobile'),
                              'password'=> bcrypt($request->input('password')),
                              'remember_token'=> $request->input('_token'),
                              'create_date'=> Carbon::now(),
                              'active' => 1                      
                               ]);
                            
                                  
                                  return redirect()->route('user/index/page')->with('success','Data insert successfull');  
                        }else{
                              $request->session()->flash('fail','Data insert fail');
                              return redirect()->route('user/create');  
                        }

                    
                       
                
	}

	
	public function edit($id)
	{
	    $users = User::find($id);
        
            return view('auth.user_edit', compact('users','id'));

	}

	public function update(Request $request,$id)
	{
                                                        
                        if($request->input('password')==$request->input('password_confirmation')){  
                            
                               User::find($id)->update([
                              'first_name'=> $request->input('first_name'),
                              'last_name'=> $request->input('last_name'),
                              'user_name'=> $request->input('user_name'),
                              'email'=> $request->input('email'),
                              'mobile'=> $request->input('mobile'),
                              'update_date'=> Carbon::now(),
                              'active' => 1                      
                               ]);

                                  return redirect()->route('user/index/page',['page'=>''])->with('success','Data update successfull');  
                        }else{
                              $request->session()->flash('fail','Data update fail');
                              return redirect()->route('user/index/page',['page'=>'']);  
                        }
                   

	}

	public function destroy($id)
	{
		$user = User::find($id)->delete();
                
                 return redirect()->route('user/index/page')->with('success','Data deleted successfully');

	}
        
        public function addUserRole()
	{
           $usersList = User::all()->lists('user_name','id'); 
           $rolesList = Role::all()->lists('role_name','id');
	   return  view('auth.user_role',['usersList'=>$usersList,'rolesList'=>$rolesList]);	
	}
        
        public function userRoleStore(Request $request)
	{
	    $user = User::find($request->input('user_id'));
            
            if($user->roles()->sync($request->input('role_id'))){
                return redirect()->route('user/index/page')->with('success','Data insert successfull');
            }else{
               return redirect()->route('user/addUserRole')->with('fail','Data insert fail'); 
            }
	}
        
        

}

Add RoleController in the location App\Http\Controllers\Auth\ using the following command

   d/xampp/htdocs/projectname> php artisan make:controller Auth\RoleController 
 

After creating file replace all the following code

  <?php namespace App\Http\Controllers\Auth;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Validator;
use App\Models\Auth\Role;
use App\Models\Auth\User_Role;
use Carbon\Carbon;
use Session;

class RoleController extends Controller {


	public function index(Request $request)
	{
           $roles = Role::orderBy('id','DESC')->paginate(10)->setPath('index');
           $totalCount = Role::orderBy('id','DESC')->count();
               return view('auth.role_index',compact('roles','totalCount')) ->with('i', ($request->input('page', 1) - 1) * 5);

               
	}

	public function create()
	{
	    return view('auth.role_create');
	}

	public function store(Request $request)
	{
		      
                   $this->validate($request, [
                     'role_name'       => 'required |regex:/^[A-Za-z-_]{5,20}/ | unique:roles',
                     
                    ]);
                                                                                                                                           
                    $insert = Role::create([
                      'role_name'=> $request->input('role_name')  
                       ]);
           
                return redirect()->route('role/index/page')->with('success','Data insert successfull');  
         
	}

	public function show($id)
	{
		//
	}

	public function edit($id)
	{
	    

	}

	public function update(Request $request,$id)
	{
		  
	}

	public function destroy($id)
	{
            
                  $userRole = User_Role::where('role_id',$id);                                  
		          $role = Role::find($id);                                

                    if($userRole->delete() && $role->delete()){
                       return redirect()->route('role/index/page')->with('success','Data deleted successfully'); 
                    }else{
                      return redirect()->route('role/index/page')->with('fail','Data delation fail');  
                    }
                 
                
                 
	}

}

 

Step-7:Create layouts and view files

Follow laravel theme tutorial.  Go

Step-8:Setup route for browsing url

Follow laravel route tutorial.  Go

Step-9:Browse url

To view user registration page browse url:http://localhost/user/create

bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States