<repo_name>chhuovanna/secondhand<file_sep>/app/seller.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Seller extends Model
{
    //
    protected $table ='seller';
    protected $primaryKey = 'seller_id';

    public static function getSeller($seller_id)
    {
        $sql = "select * from seller";
        return DB::select($sql);
    }

     public function post()
    {
        return $this->hasMany('App\Post','seller_id','seller_id');//ADD key
    }
    public function image(){
        return $this->belongsTo('App\Image','image_id','image_id');
    }
    public static function getSellersWithImage($offset=0){
        $sellers = Seller::select(['seller_id', 'name', 'address', 'email','phone','message_account','type','seller.image_id','seller.created_at','seller.updated_at','location','file_name'])
            ->leftJoin('image','seller.image_id', '=', 'image.image_id')->orderBy('seller.name')->offset($offset)
            ->limit(04)
            ->get();
        return $sellers;
    }
    public function user(){
        return $this->belongsTo('App\Models\Auth\User','user_id','id');
    }

//     public static function getactivefeatured($seller_id){
//         $sql = <<<EOT
//         select date(start_date_time) as start_date, date(end_date_time) as end_date
//         from featured_product
//         where seller_id = $seller_id and (date(end_date_time) > curdate()
//             or date(end_date_time) = '9999-01-01')
//         order by updated_at desc
//         limit 0, 1;
// EOT;
//         return DB::select($sql);


//     }

//     public static function savefeatured($seller_id, $start_date, $end_date){
//         $sql = <<<EOT
//         insert into featured_product(product_id, start_date_time, end_date_time)
//         values($product_id, '$start_date', '$end_date');
// EOT;
//         return DB::insert($sql);

//     }

//     public static function updatefeatured($product_id, $start_date, $end_date){
//         $old_featured = Product::getactivefeatured($product_id);
//         $old_featured = $old_featured[0];
//         $sql = <<<EOT
//         update featured_product set
//             start_date_time = '$start_date',
//             end_date_time = '$end_date'
//         where product_id = $product_id
//             and date(start_date_time) = '$old_featured->start_date'
//             and date(end_date_time) = '$old_featured->end_date';

// EOT;
//         return DB::update($sql);

//     }

    //





    // for seller
    public static function getSellersWithThumbnailCategory($offset=0){
        $sellers =  Seller::select(['seller_id', 'name', 'address', 'email', 'phone'
                , 'message_account', 'type', 'seller.image_id', 'seller.created_at'
                , 'seller.updated_at', 'location', 'file_name'])

        ->leftJoin(DB::raw('(select image_id, file_name, location from image) AS temp'), 'seller.image_id', '=', 'temp.image_id')
            ->with('category')

            ->offset($offset)
            ->take(4)
            ->orderBy('seller.seller_id','desc')
            ->get();
        return $sellers;
    }
}
<file_sep>/app/helpers.php
<?php

use App\Helpers\General\Timezone;
use App\Helpers\General\HtmlHelper;


/*
 * Global helpers file with misc functions.
 */
if (! function_exists('app_name')) {
    /**
     * Helper to grab the application name.
     *
     * @return mixed
     */
    function app_name()
    {
        return config('app.name');
    }
}

if (! function_exists('gravatar')) {
    /**
     * Access the gravatar helper.
     */
    function gravatar()
    {
        return app('gravatar');
    }
}

if (! function_exists('timezone')) {
    /**
     * Access the timezone helper.
     */
    function timezone()
    {
        return resolve(Timezone::class);
    }
}

if (! function_exists('include_route_files')) {

    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_route_files($folder)
    {
        try {
            $rdi = new recursiveDirectoryIterator($folder);
            $it = new recursiveIteratorIterator($rdi);

            while ($it->valid()) {
                if (! $it->isDot() && $it->isFile() && $it->isReadable() && $it->current()->getExtension() === 'php') {
                    require $it->key();
                }

                $it->next();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

if (! function_exists('home_route')) {

    /**
     * Return the route to the "home" page depending on authentication/authorization status.
     *
     * @return string
     */
    function home_route()
    {
        if (auth()->check()) {
            if (auth()->user()->can('view backend')) {
                return 'admin.dashboard';
            } else {
                return 'frontend.user.dashboard';
            }
        }

        return 'frontend.index';
    }
}

if (! function_exists('style')) {

    /**
     * @param       $url
     * @param array $attributes
     * @param null  $secure
     *
     * @return mixed
     */
    function style($url, $attributes = [], $secure = null)
    {
        return resolve(HtmlHelper::class)->style($url, $attributes, $secure);
    }
}

if (! function_exists('script')) {

    /**
     * @param       $url
     * @param array $attributes
     * @param null  $secure
     *
     * @return mixed
     */
    function script($url, $attributes = [], $secure = null)
    {
        return resolve(HtmlHelper::class)->script($url, $attributes, $secure);
    }
}

if (! function_exists('form_cancel')) {

    /**
     * @param        $cancel_to
     * @param        $title
     * @param string $classes
     *
     * @return mixed
     */
    function form_cancel($cancel_to, $title, $classes = 'btn btn-danger btn-sm')
    {
        return resolve(HtmlHelper::class)->formCancel($cancel_to, $title, $classes);
    }
}

if (! function_exists('form_submit')) {

    /**
     * @param        $title
     * @param string $classes
     *
     * @return mixed
     */
    function form_submit($title, $classes = 'btn btn-success btn-sm pull-right')
    {
        return resolve(HtmlHelper::class)->formSubmit($title, $classes);
    }
}

if (! function_exists('camelcase_to_word')) {

    /**
     * @param $str
     *
     * @return string
     */
    function camelcase_to_word($str)
    {
        return implode(' ', preg_split('/
          (?<=[a-z])
          (?=[A-Z])
        | (?<=[A-Z])
          (?=[A-Z][a-z])
        /x', $str));
    }
}
<file_sep>/app/Http/Controllers/SellerController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File; // for deleting file
use Illuminate\Support\Facades\Auth;
use App\Repositories\Frontend\Auth\UserRepository;
use App\Seller;
use App\Image; //need to use it to call new Image();
use Datatables;


use DB;



class SellerController extends Controller
{


    /**
     * @var UserRepository
     */
    protected $userRepository;

    /**
     * RegisterController constructor.
     *
     * @param UserRepository $userRepository
     */
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function index() {
        return view('scrud.sellerindex');
    }
    public function create() {
        if (Auth::user()->hasRole('administrator')) {
            return view('scrud.sellercreate');
        }else{
            return redirect()
                ->back()
                ->withFlashDanger("You don't have the permission"); // redirect back
        }
    }
    public function store(Request $request) { // add access control if else return you dont have pẻmission
        if (Auth::user()->hasRole('administrator')) {
            $seller = new Seller();
            //$seller->seller_ID = $request->get('seller_id');
            $seller->name = $request->get('name');
            $seller->address = $request->get('address');
            $seller->email = $request->get('email');
            $seller->phone = $request->get('phone');
            $seller->message_account = $request->get('message_account');
            $seller->type = $request->get('type');
            //$seller->created_at = $request->get('created_at');
            //$seller->updated_at = $request->get('updated_at');
            //$seller->image_id = $request->get('image_id');

            //validate if the upload file is image
            $validatedData = $request->validate([
                'image_id' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]);

            //get file from input
            $file = $request->file('image_id');
            $image = new Image();
            $image->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
            $image->location = 'images/seller'; //seller is stored in public/images/seller
            try {

                $image->save();
                //seller the file to it's location on server
                $file->move(public_path($image->location), $image->file_name);

                //image of seller
                $seller->image_id = $image->image_id;

                //create new user for selelr

                $test = array(
                    'first_name'        => $seller->name,
                    'last_name'         => "",
                    'email'             => $seller->email,
                    'password'          => <PASSWORD>,
                    'backend'         => 1
                );


                $user = $this->userRepository->create($test);
                if ($user){
                    $user->assignRole('executive');
                }

                $seller->user_id = $user->id;
                $seller->save();
                //echo $seller->image_id;
                return redirect()->route('seller.index')->withFlashSuccess('seller is added');

            } catch (\Exception $e) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withFlashDanger("Seller can't be added. " . $e->getMessage());

            }
        }else{
            return redirect()
                ->back()
                ->withFlashDanger("You don't have the permission"); // redirect back
        }
    }
    public function edit($id) {
        if(Auth::user()->hasRole('administrator')){
            $seller = Seller::with('image')->find($id);
            return view('scrud.selleredit', ['seller' => $seller]);
        }else{
            $user = Auth::id();
            $seller = Seller::where('user_id',$user)->first();
            if ($seller->seller_id == $id){
                $seller = Seller::with('image')->find($id);
                return view('scrud.selleredit', ['seller' => $seller]);
            }else{
                return redirect()->back()->withFlashDanger("You dont have the permission");
            }

        }

    }

    public function update(Request $request, $id) { // add access control
        $permit = false;
        $changeemail = false;
        if (Auth::user()->hasRole('administrator')) {
            $permit = true;
        }else{
            $user = Auth::id();
            $seller = Seller::where('user_id',$user)->first();
            if ($seller->seller_id == $id){
                $permit = true;
            }else{
                return redirect()
                    ->back()
                    ->withFlashDanger("You dont have the permission " );
            }
        }

        if($permit){
            $seller = Seller::find($id);
            $seller->seller_id = $request->get('seller_id');
            $seller->name = $request->get('name');
            $seller->address = $request->get('address');
            if ($seller->email != $request->get('email')){
                $changeemail = true;
            }
            $seller->email = $request->get('email');
            $seller->phone = $request->get('phone');
            $seller->message_account = $request->get('message_account');
            $seller->type = $request->get('type');
            $seller->created_at = $request->get('created_at');
            $seller->updated_at = $request->get('updated_at');
            // $seller->image_id = $request->get('image_id');

            $validateData = $request->validate([
                'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);


            try {
                // test if image is updated or not
                if ($request->hasFile('image_id')) {
                    $file = $request->file('image_id');
                    $image = new Image();
                    $image->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
                    $image->location = 'images/seller';

                    $file->move(public_path($image->location), $image->file_name);
                    $image->save();//save new image


                    $old_image = $seller->image_id; // Keep the old image for removing if it exists
                    $seller->image_id = $image->image_id;    //change the image to the new one

                }

                $seller->save();//save the update of category
                if($changeemail){
                    DB::update('update users set email = ? where id = ?', [$seller->email,$seller->user_id]);
                }
                if (isset($old_image)) {
                    $old_image = Image::find($old_image);
                    //remove old image from harddisk
                    $file = public_path($old_image->location) . '/' . $old_image->file_name;
                    if (File::exists($file)) {
                        File::delete($file);
                    }

                    $old_image->delete(); //delete the old image if user add a new one
                }


                return redirect()->route('seller.index')->withFlashSuccess('Seller is updated');
            } catch (\Exception $e) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withFlashDanger("Seller can't be updated. " . $e->getMessage());
            }
        }
    }
    public function destroy($id) {
        if (Auth::user()->hasRole('administrator')) {
            try {

                //to get image of the seller to be deleted. in Seller model, there is function called image
                $image = Seller::find($id)->image;

                //delete seller from database
                $res['seller'] = Seller::destroy($id);
                if ($image) {

                    $file = public_path($image->location) . '\\' . $image->file_name;

                    //test if the image file exists or not
                    if (File::exists($file)) {
                        //delete the file from the folder
                        if (File::delete($file)) {
                            //delete the image of the seller from database;
                            $res['image'] = $image->delete();
                        }
                    }
                }


                if ($res['seller'])
                    return [1];
                else
                    return [0];
            } catch (\Exception $e) {
                return [0, $e->getMessage()];
            }
        }else{
            return [0, "You don't have the permission"];
        }
    }


    public function getseller(){
        if(Auth::user()->hasRole('administrator')) {
            //$sellers = seller::select(['seller_id', 'name', 'address', 'email','phone','instant_massage_account','type','seller.created_at','seller.updated_at','seller.image_id','location','file_name']);
            $sellers = Seller::select(['seller_id', 'name', 'address', 'email', 'phone', 'message_account', 'type', 'seller.image_id', 'seller.created_at', 'seller.updated_at', 'location', 'file_name'])
                ->leftJoin(DB::raw('(select image_id, file_name, location from image) AS temp'), 'seller.image_id', '=', 'temp.image_id');
        }else{
            $user = Auth::id();
            $seller = Seller::where('user_id',$user)->first();
            $sellers = Seller::select(['seller_id', 'name', 'address', 'email', 'phone'
                , 'message_account', 'type', 'seller.image_id', 'seller.created_at'
                , 'seller.updated_at', 'location', 'file_name'])
                ->leftJoin(DB::raw('(select image_id, file_name, location from image) AS temp'), 'seller.image_id', '=', 'temp.image_id')
                ->where('seller.seller_id',$seller->seller_id);
                return Datatables::of($sellers)

                ->addColumn('action', function ($seller) {
                    $html = '<a href="'.route('seller.edit', ['seller_id' => $seller->seller_id]).'" class="btn btn-primary btn-sm"><i class="far fa-edit"></i> Edit</a>&nbsp;&nbsp;&nbsp;';
                    //$html .= '<a data-id="'.$seller->seller_id.'" class="btn btn-danger btn-sm seller-delete"><i class="far fa-trash-alt"></i></i> Delete</a>&nbsp;&nbsp;&nbsp;' ;

                    return $html;
                })
                ->make(true);
        }
        return Datatables::of($sellers)

            ->addColumn('action', function ($seller) {
                $html = '<a href="'.route('seller.edit', ['seller_id' => $seller->seller_id]).'" class="btn btn-primary btn-sm"><i class="far fa-edit"></i> Edit</a>&nbsp;&nbsp;&nbsp;';
                $html .= '<a data-id="'.$seller->seller_id.'" class="btn btn-danger btn-sm seller-delete"><i class="far fa-trash-alt"></i></i> Delete</a>&nbsp;&nbsp;&nbsp;' ;

                return $html;
            })
            ->make(true);
    }
//for shop
     public function getsellermore(Request $request){
        $sellers = Seller::getSellersWithImage($request->get('offset'));
        if(sizeof($sellers) > 0){
            $items = array();
            foreach ($sellers as $seller){
                $html = <<<eot
                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item" data-seller_id="$seller->seller_id">
                    <!-- Block2 -->
                    <div class="block2" style="height:100%">
                        <div class="block2-pic hov-img0" >
eot;
                if($seller->file_name){
                    $location = asset($seller->location);
                    $html .= <<<eot
                            <img src="$location/$seller->file_name" alt="IMG-SELLER">
eot;
                }else{
                    $location = asset('images/thumbnail');
                    $html .= <<<eot
                            <img src="$location/default.png" alt="IMG-SELLER">
eot;
                }
                $location = asset('cozastore');
                $url = route('frontend.product.showbyshop', $seller->seller_id);
                $html .= <<<eot
                            <a href="$url" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 show-product-shop" data-seller_id="$seller->seller_id">
                                View Store
                            </a>
                        </div>
                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                            <span class="stext-105 cl3 ">
                                    <b class="sname">Name: $seller->name</b>
                                </span>


                                <span class="stext-105 cl3 address">
                                    <strong>Address: </strong>$seller->address
                                </span>
                                <span class="stext-105 cl3 email">
                                    <strong>Email: </strong>$seller->email
                                </span>
                                <span class="stext-105 cl3 phone">
                                    <strong>Phone: </strong>$seller->phone
                                </span>
                                <span class="stext-105 cl3 message_account">
                                    <strong>Message Account: </strong>$seller->message_account
                                </span>
                                <span class="stext-105 cl3 type">
                                    <strong>Type: </strong>$seller->type
                                </span>
                            </div>
                            
                        </div>
                    </div>
                </div>
eot;
                $items[] = $html;
            }
            //return [1,$html];
            $totalSize = Seller::count();
            return [1,$totalSize,$items];
        }
        else{
            $totalSize = Seller::count();
            return [0,$totalSize];

        }

    }

}
<file_sep>/routes/web.php
<?php

use App\Http\Controllers\LanguageController;


/*
 * Global Routes
 * Routes that are used between both frontend and backend.
 */

// Switch between the included languages
Route::get('lang/{lang}', [LanguageController::class, 'swap']);

/*
 * Frontend Routes
 * Namespaces indicate folder structure
 */
Route::group(['namespace' => 'Frontend', 'as' => 'frontend.'], function () {
    include_route_files(__DIR__.'/frontend/');
});

/*
 * Backend Routes
 * Namespaces indicate folder structure
 */
Route::group(['namespace' => 'Backend', 'prefix' => 'admin', 'as' => 'admin.', 'middleware' => 'admin'], function () {
    /*
     * These routes need view-backend permission
     * (good if you want to allow more than one group in the backend,
     * then limit the backend features by different roles or permissions)
     *
     * Note: Administrator has all permissions so you do not have to specify the administrator role everywhere.
     * These routes can not be hit if the password is expired
     */
    include_route_files(__DIR__.'/backend/');
});
//Route::get ('edit','EditcategoryController@editcategory');
//Route::get('delete','DeletecategoryController@deletecategory');
//Route::get('category','CategoryController@category');


//Route::get('admin/category/rate','CategoryController@getform')->name('category.rate');
//Route::post('admin/category/saveseller','CategoryController@saveseller');
//Route::get('admin/category/showrate','CategoryController@showrate')->name('category.showrate');
//Route::get('admin/category/getseller','CategoryController@getseller')->name('category.getcategory');
Route::get('admin/category/getseller','SellerController@getseller')->name('seller.getseller');
Route::get('admin/category/getcategory', 'CategoryController@getcategory')->name('category.getcategory');
Route::get('admin/category/getproduct', 'ProductController@getproduct')->name('product.getproduct');
//Route::get('signup','Sign_upController@signup');
//Route::post('signup','Sign_upController@postSignup');
Route::get('admin/category/getcategorymore', 'CategoryController@getcategorymore');
Route::get('admin/category/getsellermore', 'SellerController@getsellermore');
Route::get('admin/product/createwithpost/{post}', 'ProductController@createwitholdpost')->name('product.create.with.oldpost');;
Route::get('admin/product/getphotos', 'ProductController@getphotos');
Route::get('admin/product/getactivefeatured','ProductController@getactivefeatured');
Route::get('admin/product/savefeatured','ProductController@savefeatured');
Route::get('admin/product/getproductmore','ProductController@getproductmore');
Route::get('admin/seller/getsellermore','SellerController@getsellermore');
Route::get('admin/product/getproductdetail','ProductController@getproductdetail');
Route::get('admin/message/listmessage', 'MessageController@index')->name('message.listmessage');
Route::get('admin/message/getmessage', 'MessageController@getmessage')->name('message.getmessage');
Route::get('admin/message/markread', 'MessageController@markread')->name('message.markread');
Route::get('admin/message/getUnread', 'MessageController@getUnread');
Route::get('admin/product/likeUnlike', 'ProductController@likeUnlike');
Route::get('admin/product/getproductmorefeature','ProductController@getproductmorefeature');




Route::resource('admin/category','CategoryController');
Route::resource('admin/seller','SellerController');
Route::resource('admin/product','ProductController');
<file_sep>/database/migrations/2019_05_01_073834_create_seller_table.php
<?php

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

class CreateSellerTable extends Migration
{

    public function up()
    {
        Schema::create('seller', function (Blueprint $table) {
            $table->increments('seller_id');
            $table->string('name')->unique();
            $table->string('address')->nullable();
            $table->string('email')->nullable();
            $table->string('phone')->nullable();
            $table->string('message_account')->nullable();
            $table->string('type')->nullable();
            $table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
            $table->integer('user_id')->unsigned()->nullable();
            $table->integer('image_id')->unsigned()->nullable();
            $table->foreign('image_id')->references('image_id')->on('image');
            $table->foreign('user_id')->references('id')->on('users');
            $table->engine = 'InnoDB';
        });
    }
    public function down()
    {
        Schema::drop('seller');
    }
}
<file_sep>/app/image.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $table ='image';
    protected $primaryKey = 'image_id';

    public function product()
    {
        return $this->belongsTo('App\Product','product_id',' product_id'); //not seller
    }

    public function category()
    {
        return $this->hasOne('App\Category', 'image_id', 'image_id');
    }

    public function seller()
    {
        return $this->hasOne('App\Seller','image_id','image_id');
    }
}
<file_sep>/resources/js/backend/app.js
import '@coreui/coreui'
import 'decimal.js'
import "datatables.net"
import "datatables.net-dt"
import "select2"
import "lightgallery"
import "lg-thumbnail"
import "lg-fullscreen"
<file_sep>/database/migrations/2019_05_03_081926_create_product_table.php
<?php

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

class CreateProductTable extends Migration
{

    public function up()
    {
        Schema::create('product', function (Blueprint $table) {//create product not seller
            $table->increments('product_id');
            $table->string('name');
            $table->decimal('price');
            $table->text('description')->nullable();
            $table->integer('like_number')->nullable();
            $table->text('status')->nullable();
            $table->text('pickup_address')->nullable();
            $table->text('pickup_time')->nullable();
            $table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
            $table->integer('post_id')->unsigned()->nullable();
            $table->foreign('post_id')->references('post_id')->on('post');
            $table->integer('image_id')->unsigned()->nullable();
            $table->foreign('image_id')->references('image_id')->on('image');
            $table->engine = 'InnoDB';

        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('product');
    }
}
<file_sep>/routes/breadcrumbs/backend/message.php
<?php
Breadcrumbs::for('message.listmessage', function ($trail) {
    $trail->push( 'List message', route('message.listmessage'));
});
<file_sep>/database/seeds/AboutTableSeeder.php
<?php

use Illuminate\Database\Seeder;

/**
 * Class AboutTableSeeder.
 */
class AboutTableSeeder extends Seeder
{
    use  TruncateTable;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        App\About::truncate();
        DB::table('about')->insert([
            'phone' => '012345678'
            ,'email' => '<EMAIL>'
            ,'website' => 'www.shop.com'
            ,'address' => '#123, st. 45, Phnom Penh, Cambodia'
        ]);
    }
}
<file_sep>/database/seeds/SellerTableSeeder.php
<?php

use Illuminate\Database\Seeder;

/**
 * Class AboutTableSeeder.
 */
class SellerTableSeeder extends Seeder
{
    use  TruncateTable;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //App\Seller::truncate();
        DB::table('seller')->insert([
            "name" => "<NAME>"
            ,'phone' => '012345678'
            ,'email' => '<EMAIL>'
            ,'message_account' => '<EMAIL>'
            ,'address' => '#123, st. 45, Phnom Penh, Cambodia'
            ,'type' => 'Individual'
            ,'user_id' => '1'
        ]);
    }
}
<file_sep>/routes/breadcrumbs/backend/seller.php
<?php
Breadcrumbs::for('seller.index', function ($trail) {
    $trail->push( 'List seller', route('seller.index'));
});

Breadcrumbs::for('seller.create', function ($trail) {
    $trail->parent('seller.index');
    $trail->push( 'Create seller', route('seller.create'));
});

Breadcrumbs::for('seller.create.with.oldpost', function ($trail) {
    $trail->parent('seller.index');
    $trail->push( 'Create seller', route('seller.create'));
});

Breadcrumbs::for('seller.edit', function ($trail,$id) {
    $trail->parent('seller.index');
    $trail->push( 'Create seller', route('seller.edit',$id));
});




<file_sep>/app/category.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $table ='category';
    protected $primaryKey = 'category_id';

    public function product()
    {
        return $this->belongsToMany('App\Product','product_category','category_id','product_id');//not seller ; add intermediate table and key name
    }
    public function thumbnail()
    {
        return $this->belongsTo('App\Image','image_id','image_id');
    }
    public static function getCategorysWithImage($offset=0){
        $categorys = Category::select(['category_id', 'name', 'description'
            ,'category.image_id','category.created_at','category.updated_at'
            ,'location','file_name'])
            ->leftJoin('image','category.image_id', '=', 'image.image_id')->orderBy('category.category_id','desc')->offset($offset)
            ->limit(20)->get();

        return $categorys;

    }

    public static function getSelectOptions(){
        $rows = Category::all();
        $result = [];
        foreach ($rows as $row) {
            $id       = $row->category_id;
            $name     = $row->name;
            $result[$id] = "$id:$name";
        }
        return $result;
    }
}
<file_sep>/app/Http/Controllers/CategoryController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;//for deleting file
use Illuminate\Support\Facades\Auth;
use App\Category;
use App\Image; //need to use it to call new Image();
use Datatables;
use DB;


class CategoryController extends Controller
{
    public function index() {
        return view('scrud.categoryindex');
    }
    public function create()
    {
        if (Auth::user()->hasRole('administrator')) {

            return view('scrud.categorycreate');

        }else{
            return redirect()
                ->back()
                ->withFlashDanger("You don't have the permission");
        }
        
    }
    public function store(Request $request)
    { //add access control
        if (Auth::user()->hasRole('administrator')) {
            $category = new Category();
            //$category->category_id = $request->get('category_id');
            $category->name = $request->get('name');
            $category->description = $request->get('description');
            //$category->image_id = $request->get('image_id');

            //validate if the upload file is image
            $validateData = $request->validate([
                'image_id' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);

            //get file from input
            $file = $request->file('image_id');
            $image = new Image();
            $image->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
            $image->location = 'images/category'; //category is stored in public/images/category

            try {
                $image->save();
                //category the file to it's location on server
                $file->move(public_path($image->location), $image->file_name);

                //image of category
                $category->image_id = $image->image_id;
                $category->save();
                //echo $category->image_id;

                return redirect()->route('category.index')->withFlashSuccess('Category is added');

            } catch (\Exception $e) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withFlashDanger("Category can't be added. " . $e->getMessage());

            }
        }else{
            return "You don't have the permission";
        }
    }
//    public function show($id) {
//        echo 'show';
//    }
    public function edit($id) {
        if (Auth::user()->hasRole('administrator')) {
            //we dont have image function in model category, we only have thumbnail()
            $category = Category::with('thumbnail')->find($id);
            return view('scrud.categoryedit', ['category' => $category]);
        }else{
            return redirect()
                ->back()
                ->withFlashDanger("You don't have the permission");
        }

    }
    public function update(Request $request, $id)
    { // add access control
        if (Auth::user()->hasRole('administrator')) {
            $category = Category::find($id);
            //$category->category_id = $request->get('category_id');
            $category->name = $request->get('name');
            $category->description = $request->get('description');
            //$category->image_id = $request->get('image_id');
            //$category->created_at = $request->get('created_at');
            //$category->updated_at = $request->get('updated_at');

            $validateData = $request->validate([
                'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);


            try {
                // test if image is updated or not
                if ($request->hasFile('image_id')) {
                    $file = $request->file('image_id');
                    $image = new Image();
                    $image->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
                    $image->location = 'images/category';

                    $file->move(public_path($image->location), $image->file_name);
                    $image->save();//save new image


                    $old_image = $category->image_id; // Keep the old image for removing if it exists
                    $category->image_id = $image->image_id;    //change the image to the new one


                }
                $category->save(); //save the update of seller
                if (isset($old_image)) {
                    $old_image = Image::find($old_image);
                    //remove old image from harddisk
                    $file = public_path($old_image->location) . '/' . $old_image->file_name;
                    if (File::exists($file)) {
                        File::delete($file);
                    }

                    $old_image->delete(); //delete the old image if user add a new one
                }
                

                return redirect()->route('category.index')->withFlashSuccess('Category is updated');
            } catch (\Exception $e) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withFlashDanger("Category can't be updated. " . $e->getMessage());
            }

        }else{
            return "You don't have the permission";
        }
    }

    public function destroy($id)
    {
        if (Auth::user()->hasRole('administrator')) {

            try {
                //to get image of the category to be deleted. in Category model, there is function called image
                $image = Category::find($id)->thumbnail;

                //delete category from database
                $res['category'] = Category::destroy($id);
                if ($image) {

                    $file = public_path($image->location) . '/' . $image->file_name;


                    //test if the image file exists or not
                    if (File::exists($file)) {
                        //delete the file from the folder
                        if (File::delete($file)) {
                            //delete the image of the category from database;
                            $res['image'] = $image->delete();
                        }
                    }
                }


                if ($res['category'])
                    return [1];
                else
                    return [0];
            } catch (\Exception $e) {
                return [0, $e->getMessage()];
            }


        }else{
            return [0, "You don't have the permission"];
        }
    }



    public function getcategory(){
        $categorys = Category::select(['category_id', 'name', 'description'
            ,'category.image_id','category.created_at','category.updated_at'
            ,'location','file_name'])
            ->leftJoin(DB::raw('(select image_id, file_name, location from image) AS temp'),'category.image_id', '=', 'temp.image_id')
        ;///need to use subquery with DB::raw to avoid ambigous of created_at and updated_at when search

        if(Auth::user()->hasRole('administrator')){ //is admin, but need to modify
            return Datatables::of($categorys)
                ->addColumn('action', function ($category) {
                    $html = '<a href="'.route('category.edit', ['category_id' => $category->category_id]).'" class="btn btn-primary btn-sm"><i class="far fa-edit"></i> Edit</a>&nbsp;&nbsp;&nbsp;';
                    $html .= '<a data-id="'.$category->category_id.'" class="btn btn-danger btn-sm category-delete"><i class="far fa-trash-alt"></i></i> Delete</a>&nbsp;&nbsp;&nbsp;' ;

                    return $html;
                })
                ->make(true);
        }else{
            return Datatables::of($categorys)
            ->addColumn('action', function ($category) {
                                return "No action";
            })->make(true);
        }
    }



}
<file_sep>/database/migrations/2019_05_12_074705_create_featured_product_table.php
<?php

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

class CreateFeaturedProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('featured_product', function (Blueprint $table) {
            $table->unsignedInteger('product_id');
            $table->date('start_date_time')->nullable();
            $table->date('end_date_time')->nullable();
            $table->text('status')->nullable();
            $table->foreign('product_id')->references('product_id')->on('product'); //on product not seller
            $table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
            //add primary key
            $table->primary(['product_id', 'start_date_time','end_date_time'],"primaryindex");
            $table->engine = 'InnoDB';

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('featured_product');
    }
}
<file_sep>/app/Http/Controllers/Frontend/HomeController.php
<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;


use App\Product;
use App\Category;
use App\Seller;
use App\About;
use PharIo\Manifest\Author;

/**
 * Class HomeController.
 */
class HomeController extends Controller
{
    /**
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $categories = Category::all();
        $about = About::first();

        if (Auth::check()){
            $products = Product::getProductsWithThumbnailCategory(0,0,0,1);
        }else{
            $products = Product::getProductsWithThumbnailCategory(0,0,0,0);
        }
        $totalSize = Product::getSize(0,0);
        return view('frontend.index', ['categories' => $categories, 'products' => $products , 'about' => $about, 'totalSize' =>$totalSize]);
    } 

   

    public function shop(){
            $sellers = Seller::getSellersWithImage();
            $categories = Category::all();
            $about = About::first();
            $totalSize = Seller::count();
        return view('frontend.shop', ['sellers' => $sellers, 'categories' => $categories, 'about' => $about , 'totalSize' => $totalSize]);
        //return view('frontend.shop');
    }


    public function features(){
        $categories = Category::all();
        $about = About::first();
        $totalSize = Product::getSize(0,1);

        if(Auth::check()){
            $products = Product::getProductsWithThumbnailCategory(0,0,1,1);

        }else{
            $products = Product::getProductsWithThumbnailCategory(0,0,1,0);

        }

        return view('frontend.features', ['categories' => $categories, 'products' => $products
            , 'about' => $about , 'totalSize' => $totalSize]);

    }

    public function about(){
        $categories = Category::all();
        $about = About::first();
        if (!$about){

            $about = new About();
            $about->phone = '012 123 456';
            $about->email = '<EMAIL>';
            $about->website = 'www.shop.com';
            $about->address = '#12, Happy Ave. Phnom Penh Cambodia';
            $about->save();

        }
        return view('frontend.about' , ['about' => $about, 'categories' => $categories]);



    }

    public function contact(){
        $categories = Category::all();
        $about = About::first();
        return view('frontend.contact',[ 'categories' => $categories, 'about' => $about]);

    }

}
<file_sep>/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;

use App\About;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;
use App\Product;
use App\Image;
use App\Category;
use App\Post;
use App\Seller;
use App\Like;
use Datatables;
use DB;




class ProductController extends Controller
{
    protected $productwithpost;

    public function index()
    {

        return view('scrud.productindex');
    }

    public function create()
    {
        $categories = Category::getSelectOptions();
        $seller = Seller::where('user_id', Auth::id())->first();
        return view('scrud.productcreate', ['categories' => $categories, 'pickup_address' => $seller->address]);
    }

    public function createwitholdpost($post_id)
    {
        $categories = Category::getSelectOptions();
        $product = Product::where('post_id', '=', $post_id)->first();

        return view('scrud.productcreate', ['categories' => $categories
            , 'post_id' => $post_id
            , 'pickup_time' => $product->pickup_time
            , 'pickup_address' => $product->pickup_address]);
    }

    public function store(Request $request)
    {
        $product = new Product();
        //$product->product_id = $request->get('product_id');
        $product->name = $request->get('name');
        $product->price = $request->get('price');
        $product->description = $request->get('description');
        $product->like_number = $request->get('like_number');
        $product->status = $request->get('status');
        $product->pickup_address = $request->get('pickup_address');
        $product->pickup_time = $request->get('pickup_time');
        //$product->created_at = $request->get('created_at');
        //$product->updated_at = $request->get('updated_at');
        //$product->post_id = $request->get('post_id');
        //$product->image_id = $request->get('image_id');
        $validateData = $request->validate([
            'thumbnail_id' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'photos[]' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
        //get file from input
        $file = $request->file('thumbnail_id');
        $thumbnail = new Image();
        $thumbnail->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
        $thumbnail->location = 'images/thumbnail'; //thumbnail is stored in public/images/thumbnail

        try {
            $thumbnail->save();
            //product the file to it's location on server
            $file->move(public_path($thumbnail->location), $thumbnail->file_name);

            //thumbnail of product
            $product->image_id = $thumbnail->image_id;
            if ($request->get('post_id') !== null) {
                $product->post_id = $request->get('post_id');
            } else {
                $user_id = Auth::id();
                $seller = Seller::where('user_id', '=', $user_id)->first();
                $post = new Post();
                $post->seller_id = $seller->seller_id;
                $post->save();
                $product->post_id = $post->post_id;
            }
            //add seller is missing
            $product->save();


            //test if user has upload other photos or not
            if ($request->hasFile('photos')) {
                //get the array of photos
                $photos = $request->file('photos');
                foreach ($photos as $key => $file) {
                    $photo = new Image();
                    $photo->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
                    //photos are stored on server in folder public/images/photos
                    $photo->location = 'images/photos';

                    //photo belongs to product
                    $photo->product_id = $product->product_id; //not (id) product_id
                    $photo->save();
                    $file->move(public_path($photo->location), $photo->file_name);
                }
            }
            $category = $request->get('category_id');
            if (sizeof($category) > 0) {
                $product->category()->attach($category);
            }


            //dd($category);


            if ($request->get('add_more') == 1) {


                return redirect()->route('product.create.with.oldpost', ['post_id' => $product->post_id])->withFlashSuccess('Product is added. You wish you add more product in the same post. We suggest the same pickup time and date');
            }
            return redirect()->route('product.index')->withFlashSuccess('Product is added');
        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput($request->all())
                ->withFlashDanger("Product can't be added. " . $e->getMessage());
        }
    }

    public function show($id)
    {
        echo 'showlalal' . $id;
    }

    public function edit($id)
    {

        $product = Product::with('thumbnail')->with('photo')->with('post')->find($id);
        $post = $product->post;
        $seller = Seller::find($post->seller_id);

        $categories = Category::getSelectOptions();


        if (Auth::user()->hasRole('administrator')) {
            return view('scrud.productedit', ['categories' => $categories, 'product' => $product]);
        } elseif ($seller->user_id == Auth::id()) {
            return view('scrud.productedit', ['categories' => $categories, 'product' => $product]);
        } else {
            return redirect()->back()->withFlashDanger("You don't have the permission");
        }

    }

    public function update(Request $request, $id)
    {
        $product = Product::with('thumbnail')->with('photo')->with('post')->find($id);

        $permit = false;
        if (Auth::user()->hasRole('administrator')) {
            $permit = true;
        } else {
            $post = $product->post;
            $seller = Seller::find($post->seller_id);
           // $user = Auth::id();
            //$seller = Seller::where('user_id', $user)->first();
            if ($seller->user_id == Auth::id()) {
                $permit = true;
            } else {
                return redirect()
                    ->back()
                    ->withFlashDanger("You dont have the permission ");
            }
        }
        if ($permit) {
            //$product = Product::find($id);
            //$product->product_id = $request->get('product_id');
            $product->name = $request->get('name');
            $product->price = $request->get('price');
            $product->description = $request->get('description');
            //$product->like_number = $request->get('like_number');
            $product->status = $request->get('status');
            $product->pickup_address = $request->get('pickup_address');
            $product->pickup_time = $request->get('pickup_time');
            //$product->created_at = $request->get('created_at');
            //$product->updated_at = $request->get('updated_at');
            //$product->post_id = $request->get('post_id');
            //$product->image_id = $request->get('image_id');

            $validateData = $request->validate([
                'thumbnail_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
                , 'photos[]' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);


            try {
                // test if thumbnail is updated or not
                if ($request->hasFile('thumbnail_id')) {
                    $file = $request->file('thumbnail_id');
                    $thumbnail = new Image();
                    $thumbnail->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();
                    $thumbnail->location = 'images/thumbnail';

                    $file->move(public_path($thumbnail->location), $thumbnail->file_name);
                    $thumbnail->save();//save new thumbnail


                    $old_thumbnail = $product->thumbnail; // Keep the old thumbnail for removing if it exists
                    $product->image_id = $thumbnail->image_id;    //change the thumbnail to the new one


                }


                $product->save(); //save the update of product

                if (isset($old_thumbnail)) {
                    //remove old thumbnail from harddisk
                    $file = public_path($old_thumbnail->location) . '/' . $old_thumbnail->file_name;
                    if (File::exists($file)) {
                        File::delete($file);
                    }

                    $old_thumbnail->delete(); //delete the old thumbnail if user add a new one
                }


                $db_old_photos = $product->photo;//get old photos from db
                if ($db_old_photos) {// if there is any old photos in db

                    $old_photos = $request->get('old_photos'); //get the list of old photos after use update

                    //            print_r($old_photos);
                    foreach ($db_old_photos as $db_old_photo) {

                        //test if user has deleted all old photos, we remove it from db and hard disk
                        //or test if some old photos are deleted by user, we remove it form db and hard disk
                        if (!$old_photos or ($old_photos && !in_array($db_old_photo->image_id, $old_photos))) {

                            if ($db_old_photo->delete()) {
                                //remove old thumbnail from harddisk
                                $file = public_path($db_old_photo->location) . '/' . $db_old_photo->file_name;
                                if (File::exists($file)) {
                                    File::delete($file);
                                }
                            }
                        }
                    }
                }


                //test if user has upload other photos or not
                if ($request->hasFile('photos')) {


                    //get the array of photos
                    $photos = $request->file('photos');


                    foreach ($photos as $file) {
                        $photo = new Image();
                        $photo->file_name = rand(1111, 9999) . time() . '.' . $file->getClientOriginalExtension();

                        //photos are stored on server in folder public/images/photos
                        $photo->location = 'images\photos';

                        //photo belongs to product
                        $photo->product_id = $request->get('product_id');
                        $photo->save();
                        $file->move(public_path($photo->location), $photo->file_name);


                    }
                }
                $category = $request->get('category_id');
                $old_category = $product->category;
                $array_old_category = $old_category->pluck('category_id')->toArray();
                print_r($array_old_category);

                foreach ($old_category as $ele){
                    if (!in_array ( $ele->category_id, $category )){
                        $product->category()->detach($ele->category_id);
                    }
                }

                foreach ($category as $ele){
                    if (!in_array ( $ele, $array_old_category )){
                        $product->category()->attach($ele);
                    }
                }


                return redirect()->route('product.index')->withFlashSuccess('product is updated');
            } catch (\Exception $e) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withFlashDanger("Product can't be updated. " . $e->getMessage());
            }
        }
    }

    public function destroy($id){
        $product = Product::with('thumbnail')->with('photo')->with('post')->find($id);
        $permit = false;
        if (Auth::user()->hasRole('administrator')) {
            $permit = false;
        } else {
            $post = $product->post;
            $seller = Seller::find($post->seller_id);
            // $user = Auth::id();
            //$seller = Seller::where('user_id', $user)->first();
            if ($seller->user_id == Auth::id()) {
                $permit = true;
            } else {
                return redirect()
                    ->back()
                    ->withFlashDanger("You dont have the permission ");
            }
        }
        if ($permit) {
            try {

                //to get the array of photos of the product
                $product = Product::with('photo')->with('thumbnail')->find($id);
                $photos = $product->photo;
                $res['photos'] = true;
                if ($photos) {
                    foreach ($photos as $photo) {
                        $file = public_path($photo->location) . '\\' . $photo->file_name;
                        if (File::exists($file)) {

                            if (File::delete($file)) {//delete the file from the folder
                                $res['photos'] = $res['photos'] && $photo->delete(); //delete the file from database
                            }

                        }
                    }

                }


                //to get thumbnail of the product to be deleted. in product model, there is function called thumbnail
                $thumbnail = $product->thumbnail;

                $post = $product->post;

                //delete product from database
                $res['product'] = Product::destroy($id);

                $otherproduct = $post->product;
                if (sizeof($otherproduct) == 0) {
                    $post->delete();
                }

                if ($thumbnail) {
                    $file = $file = public_path($thumbnail->location) . '\\' . $thumbnail->file_name;
                    //test if the thumbnail file exists or not
                    if (File::exists($file)) {
                        //delete the file from the folder
                        if (File::delete($file)) {
                            //delete the thumbnail of the product from database;
                            $res['thumbnail'] = $thumbnail->delete();
                        }
                    }
                }


                if ($res['product'])
                    return [1];
                else
                    return [0];
            } catch (\Exception $e) {
                return [0, $e->getMessage()];
            }
        }
    }


    public function getproduct(){

        if(Auth::user()->hasRole('administrator')){ //is admin, but need to modify
            $products = Product::select(['product.product_id', 'product.name'/*DB::raw('product.name as pname')*/, 'price'
                                    , 'description','like_number','status','pickup_address','pickup_time','created_at'
                                    ,'updated_at',  'file_name', 'location'])
            ->leftJoin(DB::raw('(select image_id, file_name, location from image) as temp'),'product.image_id', '=', 'temp.image_id')
            ->with('category')
            ;
        }else{
            $user = Auth::id();
            $seller = Seller::where('user_id',$user)->first();

            $products = Product::select(['product.product_id', 'product.name'/*DB::raw('product.name as pname')*/, 'price'
                                    , 'description','like_number','status','pickup_address','pickup_time','created_at'
                                    ,'updated_at',  'file_name', 'location', 'temp1.seller_id'])
            ->leftJoin(DB::raw('(select image_id, file_name, location from image) as temp'),'product.image_id', '=', 'temp.image_id')
            ->leftJoin(DB::raw('(select seller.seller_id, post.post_id  from seller join post on post.seller_id = seller.seller_id) as temp1')
                ,'product.post_id', '=', 'temp1.post_id')
            ->with('category')
            ->where('temp1.seller_id' , $seller->seller_id)
            ;
            return Datatables::of($products)
                        ->addColumn('action', function ($product) {
                                                $html = '<a href="'.route('product.edit', ['id' => $product->product_id]).'" class="btn btn-primary btn-sm"><i class="far fa-edit"></i></a>&nbsp;&nbsp;&nbsp;';
                                                $html .= '<a data-id="'.$product->product_id.'" class="btn btn-danger btn-sm product-delete"><i class="far fa-trash-alt"></i></a>&nbsp;&nbsp;&nbsp;' ;

                                                return $html;
                                            })
                        ->make(true);
        }



        return Datatables::of($products)
                        ->addColumn('action', function ($product) {
                                                $html = '<a href="'.route('product.edit', ['id' => $product->product_id]).'" class="btn btn-primary btn-sm"><i class="far fa-edit"></i></a>&nbsp;&nbsp;&nbsp;';
                                                $html .= '<a data-id="'.$product->product_id.'" class="btn btn-danger btn-sm product-delete"><i class="far fa-trash-alt"></i></a>&nbsp;&nbsp;&nbsp;' ;
                                                $html .= '<a data-id="'.$product->product_id.'" class="btn btn-info btn-sm product-featured" data-toggle="modal" data-target="#featured_product_modal"><i class="fas fa-cog"></i></a>' ;

                                                return $html;
                                            })
                        ->make(true);
    }
    public function getphotos(Request $request){
        $product_id = $request->get('product_id');

        //get the list of photos of product using relationship defined in model
        $photos = Product::find($product_id)->photo;
        $thumbnail = Product::find($product_id)->thumbnail;
        if($thumbnail){
            $photos->push($thumbnail);
        }
        if (sizeof($photos) > 0 || $thumbnail){
            $html = "";
            $source = "";
            $eleclass = "";
            $i=0;
            foreach ($photos as $photo) {

                //get url of each photo
                $source = asset(str_replace('\\','/',$photo->location)) . "/" . $photo->file_name;
                if ($i==0){
                    //set class start to the first photo, so we can use js to click it
                    $eleclass = "class='start'";
                    $i = 1;
                }
                else
                    $eleclass = "";
                //html code for each photo html element
                $html .=  "<a href='" . $source . "' " . $eleclass . " ><img src='" . $source ."' height='40' width='40' ></a>";
            }
            //list of photos must be in the dive with id lightgallery, so in view we can apply the lightgallery library on it
            $html = "<div id='lightgallery'>" . $html . "</div>";
            return [1, $html];
        }else
            return [0];
    }


    //add access control
    public function getactivefeatured(Request $request){
        $product_id = $request->get('product_id');
        $product = Product::with('thumbnail')->with('photo')->with('post')->find($product_id);
        $permit = false;
        if (Auth::user()->hasRole('administrator')) {
            $permit = true;
        }

        if ($permit) {

            $featured_product = Product::getactivefeatured($product_id);
            if (sizeof($featured_product) > 0) {
                return [1, $featured_product];
            } else {
                return [0];
            }
        }else{
            return [2,"You don't have the permission. "];
        }
    }

    //add access control

    public function savefeatured(Request $request)
    {
        $product_id = $request->get('product_id');
        $product = Product::with('thumbnail')->with('photo')->with('post')->find($product_id);
        $permit = false;
        if (Auth::user()->hasRole('administrator')) {
            $permit = true;
        }

        if ($permit) {


            $start_date = $request->get('start_date');
            $end_date = $request->get('end_date');
            $featured_product = Product::getactivefeatured($product_id);

            if ($end_date == null) {
                $end_date = '9999-01-01';
            }
            if (sizeof($featured_product) == 1) {

                try {
                    Product::updatefeatured($product_id, $start_date, $end_date);
                    return [1,1,$product_id];
                } catch (\Exception $e) {
                    return [0, $e->getMessage(),$product_id];
                }

            } else {
                try {
                    Product::savefeatured($product_id, $start_date, $end_date);
                    return [1,1,$product_id];
                } catch (\Exception $e) {
                    return [0, $e->getMessage(),$product_id];
                }

            }
        }else{
            return [2,"You don't have the permission. ", $product_id];
        }
    }

    public function getproductmore(Request $request){

        if(Auth::check()){
            $products = Product::getProductsWithThumbnailCategory($request->get('offset'), $request->get('seller')
                , $request->get('features'), 1);

        }else{
            $products = Product::getProductsWithThumbnailCategory($request->get('offset'), $request->get('seller')
                ,$request->get('features'),0);

        }


        if(sizeof($products) > 0){
            $items = array();

            foreach ($products as $product){
                $category = "";
                $category_name = "";
                $categories = $product->category;
                foreach ($categories as $ele){
                    $category .= str_replace(' ','-',$ele->name). " ";
                    $category_name .= $ele->name. ", ";
                }
                $category_name = substr($category_name,0,strlen($category_name )-2);
                $html = "";
                $html .= <<<eot
				<div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item $category"  data-product_id="$product->product_id">
					<!-- Block2 -->
					<div class="block2" style="height:100%">
						<div class="block2-pic hov-img0" >
eot;
                if($product->file_name){
                    $location = asset($product->location);
                    $html .= <<<eot

							<img src="$location/$product->file_name" alt="IMG-PRODUCT">
eot;
                }else{
                    $location = asset('images/thumbnail');
                    $html .= <<<eot

							<img src="$location/default.png" alt="IMG-PRODUCT">
eot;
                }



                $location = asset('cozastore');
                $html .= <<<eot
							<a href="javascript:void(0);" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1" data-product_id="$product->product_id">
								Quick View
							</a>
						</div>

						<div class="block2-txt flex-w flex-t p-t-14">
							<div class="block2-txt-child1 flex-col-l ">


                                <span class="stext-105 cl3">
eot;
                $active_featured_product = Product::getactivefeatured($product->product_id);
                if (sizeof($active_featured_product) == 1){
                    $html .= <<<eot


                                    <b class='pname'>$product->name</b>
                                    <sup style="color:white;background-color:red;border-radius: 10px;">&nbsp;&nbsp;Hot&nbsp;&nbsp;</sup>

eot;

                }else{
                    $html .= <<<eot
                    <b class='pname'>$product->name</b>
eot;
                }

                $html .= <<<eot
								</span>

								<span class="stext-105 cl3 price">
									$product->price
								</span>

								<span class="stext-105 cl3 category">
									$category_name
								</span>
							</div>

                             <div class="block2-txt-child2 flex-r p-t-3">
eot;
                $like = $product->like;
                $location = asset('cozastore');
                $number_like = sizeof($like);
                if($number_like > 0){

                    $user_id = optional(auth()->user())->id;
                    $number_like = sizeof($like);
                    foreach($like as $ele){
                        if($user_id && $user_id == $ele->user_id){
                            $html .= <<<eot
                            <span class="number-like">$number_like</span>
                            <a href="javascript:void(0);" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2 js-addedwish-b2" data-product_id="$product->product_id">
                                <img class="icon-heart1 dis-block trans-04" src="$location/images/icons/icon-heart-01.png" alt="ICON">
                                <img class="icon-heart2 dis-block trans-04 ab-t-l" src="$location/images/icons/icon-heart-02.png" alt="ICON">
                            </a>
eot;
                        }else{
                            $html .= <<<eot
                            <span class="number-like">$number_like</span>
                            <a href="javascript:void(0);" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2" data-product_id="$product->product_id">
                                <img class="icon-heart1 dis-block trans-04" src="$location/images/icons/icon-heart-01.png" alt="ICON">
                                <img class="icon-heart2 dis-block trans-04 ab-t-l" src="$location/images/icons/icon-heart-02.png" alt="ICON">
                            </a>
eot;
                        }
                    }

                }else{
                    $html .= <<<eot
                    <span class="number-like">$number_like</span>
                    <a href="javascript:void(0);" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2" data-product_id="$product->product_id">
                    <img class="icon-heart1 dis-block trans-04" src="$location/images/icons/icon-heart-01.png" alt="ICON">
                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="$location/images/icons/icon-heart-02.png" alt="ICON">
                </a>
eot;
                }


                $html .= <<<eot
							</div>
 						</div>
					</div>
				</div>
eot;
                $items[] = $html;
            }


            //return [1,$html];
            $totalSize = Product::getSize( $request->get('seller'),$request->get('features'));
            return [1, $totalSize,$items];
        }
        else{
            $totalSize = Product::getSize( $request->get('seller'),$request->get('features'));
            return [0, $totalSize];
        }
    }



    public function getproductdetail(Request $request){
        $product = Product::with('photo')->with('thumbnail')->with('category')->find($request->get('product_id'));

        $post = Post::where('post_id',$product->post_id)->first();
        $seller = Seller::where('seller_id',$post->seller_id)->first();

        if(isset($product->thumbnail)){
            $location = str_replace('\\','/',$product->thumbnail->location);
            $product->thumbnail->location = $location;
        }else{
            $product->thumbnail_id = asset('images/thumbnail').'/default.png';
        }

        if(isset($product->photos)){
            $size = sizeof($product->photo);
            for($i = 0 ; $i < $size; $i ++){
                $location = asset(str_replace('\\','/',$product->photos[$i]->location));
                $product->photos[$i]->location = $location;
            }

        }
        return [1,$product, $seller];
    }


    public function likeUnlike(Request $request)
       {
           if(Auth::check()){
                $product_id = $request->get('product_id');
                $operation = $request->get('operation');


                $product = Product::find($product_id);
                if (!$product) {
                    return 0;
                }

                $user_id = Auth::id();
                if($operation == 'like'){
                    $like = new Like();
                    $like->user_id = $user_id;
                    $like->product_id = $product_id;

                    $like->save();
                    $product = Product::find($product_id);
                    $product->like_number = $product->like()->count();
                    $product->save();
                    return 1;
                }elseif ($operation == 'unlike'){
                    $like = Like::where('product_id',$product_id)
                    ->where('user_id',$user_id)->first();
                    if($like){
                        DB::table('like')
                        ->where('product_id',$product_id)
                        ->where('user_id',$user_id)
                        ->delete();
                        $product = Product::find($product_id);
                        $product->like_number = $product->like()->count();
                        $product->save();
                    }
                    return 1;
                }
           }else{
               return 2;

           }

       }

    public function showProductByShop($seller_id){

        $categories = Category::all();
        $about = About::first();
        $seller = Seller::find($seller_id);
        $totalSize = Product::getSize($seller_id,0);


        if (Auth::check()){
            $products = Product::getProductsWithThumbnailCategory(0,$seller_id,0,1);
        }else{
            $products = Product::getProductsWithThumbnailCategory(0,$seller_id,0,0);
        }
        return view('frontend.shopproduct', ['categories' => $categories, 'products' => $products
            , 'about' => $about , 'seller' =>$seller, 'totalSize' =>$totalSize]);

    }

    public function showProductDetail($product_id){


        $categories = Category::all();
        $about = About::first();
        $request = new Request();
        $request->setMethod('get');
        $request->request->add(['product_id' => $product_id]);
        $data = $this->getproductdetail($request);

        return view('frontend.productdetail',['categories' => $categories
                    , 'about' => $about, 'product' => $data[1], 'seller'=>$data[2]]);
    }
}

<file_sep>/routes/breadcrumbs/backend/product.php
<?php
Breadcrumbs::for('product.index', function ($trail) {
    $trail->push( 'List Product', route('product.index'));
});

Breadcrumbs::for('product.create', function ($trail) {
    $trail->parent('product.index');
    $trail->push( 'Create product', route('product.create'));
});

Breadcrumbs::for('product.create.with.oldpost', function ($trail) {
    $trail->parent('product.index');
    $trail->push( 'Create product', route('product.create'));
});

Breadcrumbs::for('product.edit', function ($trail,$id) {
    $trail->parent('product.index');
    $trail->push( 'Create product', route('product.edit',$id));
});




<file_sep>/app/Http/Controllers/MessageController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Datatables;

use App\Message;


class MessageController extends Controller
{
    public function index() {

        if(Auth::user()->hasRole('administrator')){ //is admin, but need to modify
            return view('scrud.messageindex');
        }else{
            return redirect()->back()->withFlashDanger("You don't have the permission");
        }
    }

    public function getmessage(){

        // to be change
        $messages = Message::select(['message_id', 'full_name','email','phone', 'message','status','message.created_at','message.updated_at'])->get();

       // if(Auth::user()->hasRole('administrator')){ //is admin, but need to modify
            //return Datatables::of($messages)
            return Datatables::of($messages)

                 ->addColumn('action', function ($message) {
                                                $html = '<a href="'.route('message.markread', ['id' => $message->message_id]).'" class="btn btn-primary btn-sm"><i class="far fa-envelope-open"></i></a>';


                                                return $html;
                                            })
                ->make(true);
       // }
    }

    public function markread(Request $request){
        $message_id = $request->get('id');
        $message = Message::find($message_id);
        $message->status = 1;
        $message->save();
        return redirect()->back();
    }
    public function getUnread(){
        if (Auth::user()->hasRole('administrator'))
            return Message::where('status',0)->count();
        else
            return 0;
    }

}
<file_sep>/app/post.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\App;

class Post extends Model
{
    public $primaryKey = 'post_id';
    public $table = 'post';
    public function product()//not function command
    {
        return $this->hasMany('App\Product','post_id','post_id');
    }

    public function seller(){ //create seller function
        return $this->belongsTo('App\Seller','seller_id','seller_id');

    }
}
<file_sep>/app/product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Product extends Model
{
    //
    protected $table ='product';
    protected $primaryKey = 'product_id';

    public static function getProduct($product_id)
    {
        $sql = "select * from product";
        return DB::select($sql);
    }

    public function post()
    {
        return $this->belongsTo('App\Post','post_id','post_id');
    }


    public function category()
    {
        return $this->belongsToMany('App\Category','product_category', 'product_id','category_id'); //belong to many category
    }


    public function thumbnail()
    {
        return $this->belongsTo('App\Image','image_id','image_id');

    }

    public function photo()
    {
        return $this->hasMany('App\Image','product_id','product_id');

    }

    public function featured_product()//add function featured_product
    {
        return $this->hasMany('App\FeaturedProduct','product_id','product_id');

    }

    public static function getactivefeatured($product_id){
        $sql = <<<EOT
        select date(start_date_time) as start_date, date(end_date_time) as end_date
        from featured_product
        where product_id = $product_id and (date(end_date_time) >= curdate())
            
        order by updated_at desc
        limit 0, 1;
EOT;
        return DB::select($sql);


    }

    public static function savefeatured($product_id, $start_date, $end_date){
        $sql = <<<EOT
        insert into featured_product(product_id, start_date_time, end_date_time)
        values($product_id, '$start_date', '$end_date');
EOT;
        return DB::insert($sql);

    }

    public static function updatefeatured($product_id, $start_date, $end_date){
        $old_featured = Product::getactivefeatured($product_id);
        $old_featured = $old_featured[0];
        $sql = <<<EOT
        update featured_product set
            start_date_time = '$start_date',
            end_date_time = '$end_date'
        where product_id = $product_id
            and date(start_date_time) = '$old_featured->start_date'
            and date(end_date_time) = '$old_featured->end_date';

EOT;
        return DB::update($sql);

    }

    public static function getProductsWithThumbnailCategory($offset=0,$seller_id=0, $features = 0, $like =0){
        $products = Product::select(['product.product_id', 'product.name', 'price'
        , 'description','like_number','status','pickup_address','pickup_time','created_at'
        ,'updated_at',  'file_name', 'location'])
        ->leftJoin(DB::raw('(select image_id, file_name, location from image) as temp')
            ,'product.image_id', '=', 'temp.image_id')
        ->where('status','Available')
        ->with('category');
        
        if ($seller_id != 0){
            $products = $products->leftJoin(DB::raw('(select post_id, seller_id from post) as temp1')
            ,'product.post_id', '=', 'temp1.post_id')
            ->where('temp1.seller_id',$seller_id);
        }

        if($like ==1){
            $products = $products->with('like');
        }
        if($features == 1){
            $products = $products->join(DB::raw('(select product_id from featured_product where (date(end_date_time) >= curdate() and date(start_date_time) <= curdate()) group by product_id ) as temp2')
            , 'temp2.product_id','product.product_id');
        }

        $products = $products->offset($offset)
            ->take(4)
            ->orderBy('product.product_id','desc')
            ->get();

        return $products;


    }

    public function like()
    {
        return $this->hasMany('App\Like','product_id', 'product_id'); //belong to many category
    }

    public static function getSize($seller_id, $features){
        $products = Product::where('status','Available');
        
        if ($seller_id != 0){
            $products = $products->leftJoin(DB::raw('(select post_id, seller_id from post) as temp1')
            ,'product.post_id', '=', 'temp1.post_id')
            ->where('temp1.seller_id',$seller_id);
        }

        if($features == 1){
            $products = $products->join(DB::raw('(select product_id from featured_product where (date(end_date_time) >= curdate() and date(start_date_time) <= curdate()) group by product_id ) as temp2')
            , 'temp2.product_id','product.product_id');
        }

        $size = $products->count();

        return $size;
    }

}
<file_sep>/public/cozastore/js/main.js

(function ($) {
    "use strict";

    /*[ Load page ]
    ===========================================================*/
    $(".animsition").animsition({
        inClass: 'fade-in',
        outClass: 'fade-out',
        inDuration: 1500,
        outDuration: 800,
        linkElement: '.animsition-link',
        loading: true,
        loadingParentElement: 'html',
        loadingClass: 'animsition-loading-1',
        loadingInner: '<div class="loader05"></div>',
        timeout: false,
        timeoutCountdown: 5000,
        onLoadEvent: true,
        browser: [ 'animation-duration', '-webkit-animation-duration'],
        overlay : false,
        overlayClass : 'animsition-overlay-slide',
        overlayParentElement : 'html',
        transition: function(url){ window.location.href = url; }
    });

    /*[ Back to top ]
    ===========================================================*/
    var windowH = $(window).height()/2;

    $(window).on('scroll',function(){
        if ($(this).scrollTop() > windowH) {
            $("#myBtn").css('display','flex');
        } else {
            $("#myBtn").css('display','none');
        }
        $('.isotope-grid').isotope('layout');
    });

    $('#myBtn').on("click", function(){
        $('html, body').animate({scrollTop: 0}, 300);
    });


    /*==================================================================
    [ Fixed Header ]*/
    var headerDesktop = $('.container-menu-desktop');
    var wrapMenu = $('.wrap-menu-desktop');

    if($('.top-bar').length > 0) {
        var posWrapHeader = $('.top-bar').height();
    }
    else {
        var posWrapHeader = 0;
    }


    if($(window).scrollTop() > posWrapHeader) {
        $(headerDesktop).addClass('fix-menu-desktop');
        $(wrapMenu).css('top',0);
    }
    else {
        $(headerDesktop).removeClass('fix-menu-desktop');
        $(wrapMenu).css('top',posWrapHeader - $(this).scrollTop());
    }

    $(window).on('scroll',function(){
        if($(this).scrollTop() > posWrapHeader) {
            $(headerDesktop).addClass('fix-menu-desktop');
            $(wrapMenu).css('top',0);
        }
        else {
            $(headerDesktop).removeClass('fix-menu-desktop');
            $(wrapMenu).css('top',posWrapHeader - $(this).scrollTop());
        }
    });


    /*==================================================================
    [ Menu mobile ]*/
    $('.btn-show-menu-mobile').on('click', function(){
        $(this).toggleClass('is-active');
        $('.menu-mobile').slideToggle();
    });

    var arrowMainMenu = $('.arrow-main-menu-m');

    for(var i=0; i<arrowMainMenu.length; i++){
        $(arrowMainMenu[i]).on('click', function(){
            $(this).parent().find('.sub-menu-m').slideToggle();
            $(this).toggleClass('turn-arrow-main-menu-m');
        })
    }

    $(window).resize(function(){
        if($(window).width() >= 992){
            if($('.menu-mobile').css('display') == 'block') {
                $('.menu-mobile').css('display','none');
                $('.btn-show-menu-mobile').toggleClass('is-active');
            }

            $('.sub-menu-m').each(function(){
                if($(this).css('display') == 'block') { console.log('hello');
                    $(this).css('display','none');
                    $(arrowMainMenu).removeClass('turn-arrow-main-menu-m');
                }
            });

        }
    });


    /*==================================================================
    [ Show / hide modal search ]*/
    $('.js-show-modal-search').on('click', function(){
        $('.modal-search-header').addClass('show-modal-search');
        $(this).css('opacity','0');
    });

    $('.js-hide-modal-search').on('click', function(){
        $('.modal-search-header').removeClass('show-modal-search');
        $('.js-show-modal-search').css('opacity','1');
    });

    $('.container-search-header').on('click', function(e){
        e.stopPropagation();
    });


    /*==================================================================
    [ Isotope ] */
    var $topeContainer = $('.isotope-grid');
    var $filter = $('.filter-tope-group');

    // filter items on button click
    /*$filter.each(function () {
        $filter.on('click', 'button', function () {
            var filterValue = $(this).attr('data-filter');
            $topeContainer.isotope({filter: filterValue});
        });

    });
*/

    /////////////////////edited by vanna

    function perform_filter($this){
        var price = Number($this.find('.price').text());
        var filter_by = $('.filter-price').val();
        var active_category = $('.how-active1').data('filter').substring(1);
        var filter_by_name = $('#search_name').val().trim().toLowerCase().split(' ');
        var product_name = $this.find('.pname').text().toLowerCase();
        var is_in_price;
        var is_in_category;
        var is_in_name = false;
        var i;
        // alert('imaher');

        //$('.testoutput').append('<p>'+active_director+'</p>'+'<p>'+filter_by+'</p>');

        // selected price
        // console.log(filter_by_name);
        // console.log(product_name);
        is_in_price = ( filter_by === 'all'
                    || (filter_by === 'after200' && price >= 200)
                    || (price >= (Number(filter_by) - 50) &&  price <= Number(filter_by) )
                    );
        is_in_category = ( active_category === ''
                            ||  $this.hasClass(active_category)
                        );
        if (filter_by_name.length == 0)
            is_in_name = true;
        else {
            for (i =0; i < filter_by_name.length ; i++){
                if (product_name.indexOf(filter_by_name[i] ) != -1){
                    is_in_name = true;
                    break;
                }
            }
        }

        return is_in_name && is_in_price && is_in_category;



        // if (isNaN(filter_by)){
        //     if (filter_by  == 'all'){
        //         if ( active_category === ''){
        //             return !(product_name.indexOf(filter_by_name) === -1);
        //         }
        //         else{
        //             return ($this.hasClass(active_category) && !(product_name.indexOf(filter_by_name) === -1 ));
        //         }

        //     }else{
        //         if ( active_category === '')
        //             return ((price >= 200 ) && !(product_name.indexOf(filter_by_name) === -1));
        //         else
        //             return ( (price >= 200 ) && $this.hasClass(active_category) && !(product_name.indexOf(filter_by_name) === -1)) ;
        //     }

        // }else{
        //     filter_by = Number(filter_by);

        //     if (price >= (filter_by - 50) &&  price <= filter_by){

        //         if ( active_category === '')
        //             return true && !(product_name.indexOf(filter_by_name) === -1);
        //         else
        //             return $this.hasClass(active_category) && !(product_name.indexOf(filter_by_name) === -1);
        //     }
        //     else
        //         return false;
        // }
    }

    $filter.each(function () {
        $filter.on('click', 'button', function () {
            //var filterValue = $(this).attr('data-filter');

            $topeContainer.isotope({
                filter: function(){
                    return perform_filter($(this));
                }
            });
            updateSize();
        });

    })

    // init Isotope
    $(window).on('load', function () {
        var $grid = $topeContainer.each(function () {
            $(this).isotope({
                itemSelector: '.isotope-item',
                layoutMode: 'fitRows',
                percentPosition: true,
                animationEngine : 'best-available',
                masonry: {
                    columnWidth: '.isotope-item'
                }
            });
        });
    });

    var isotopeButton = $('.filter-tope-group button');

    $(isotopeButton).each(function(){
        $(this).on('click', function(){
            for(var i=0; i<isotopeButton.length; i++) {
                $(isotopeButton[i]).removeClass('how-active1');
            }

            $(this).addClass('how-active1');
        });
    });

    /*==================================================================
    [ Filter / Search product ]*/
    $('.js-show-filter').on('click',function(){
        $(this).toggleClass('show-filter');
        $('.panel-filter').slideToggle(400);

        if($('.js-show-search').hasClass('show-search')) {
            $('.js-show-search').removeClass('show-search');
            $('.panel-search').slideUp(400);
        }
    });

    $('.js-show-search').on('click',function(){
        $(this).toggleClass('show-search');
        $('.panel-search').slideToggle(400);

        if($('.js-show-filter').hasClass('show-filter')) {
            $('.js-show-filter').removeClass('show-filter');
            $('.panel-filter').slideUp(400);
        }
    });




    /*==================================================================
    [ Cart ]*/
    $('.js-show-cart').on('click',function(){
        $('.js-panel-cart').addClass('show-header-cart');
    });

    $('.js-hide-cart').on('click',function(){
        $('.js-panel-cart').removeClass('show-header-cart');
    });

    /*==================================================================
    [ Cart ]*/
    $('.js-show-sidebar').on('click',function(){
        $('.js-sidebar').addClass('show-sidebar');
    });

    $('.js-hide-sidebar').on('click',function(){
        $('.js-sidebar').removeClass('show-sidebar');
    });

    /*==================================================================
    [ +/- num product ]*/
    $('.btn-num-product-down').on('click', function(){
        var numProduct = Number($(this).next().val());
        if(numProduct > 0) $(this).next().val(numProduct - 1);
    });

    $('.btn-num-product-up').on('click', function(){
        var numProduct = Number($(this).prev().val());
        $(this).prev().val(numProduct + 1);
    });

    /*==================================================================
    [ Rating ]*/
    $('.wrap-rating').each(function(){
        var item = $(this).find('.item-rating');
        var rated = -1;
        var input = $(this).find('input');
        $(input).val(0);

        $(item).on('mouseenter', function(){
            var index = item.index(this);
            var i = 0;
            for(i=0; i<=index; i++) {
                $(item[i]).removeClass('zmdi-star-outline');
                $(item[i]).addClass('zmdi-star');
            }

            for(var j=i; j<item.length; j++) {
                $(item[j]).addClass('zmdi-star-outline');
                $(item[j]).removeClass('zmdi-star');
            }
        });

        $(item).on('click', function(){
            var index = item.index(this);
            rated = index;
            $(input).val(index+1);
        });

        $(this).on('mouseleave', function(){
            var i = 0;
            for(i=0; i<=rated; i++) {
                $(item[i]).removeClass('zmdi-star-outline');
                $(item[i]).addClass('zmdi-star');
            }

            for(var j=i; j<item.length; j++) {
                $(item[j]).addClass('zmdi-star-outline');
                $(item[j]).removeClass('zmdi-star');
            }
        });
    });

    /*==================================================================
    [ Show modal1 ]*/
/*
    $('.js-show-modal1').on('click',function(e){
        e.preventDefault();
        $('.js-modal1').addClass('show-modal1');
    });

    $('.js-hide-modal1').on('click',function(){
        $('.js-modal1').removeClass('show-modal1');
    });

*/

    //added by vanna
    // Quick View
    $(document).off('click', '.js-show-modal1');
    $(document).on('click', '.js-show-modal1',function(e){
        $('.js-modal1').addClass('show-modal1');
        $.ajax({
            type:"GET",
            url:window.location.protocol +'//'+window.location.host+"/admin/product/getproductdetail",
            data:{ product_id:$(this).data('product_id')  }   ,
            success: function (data) {
                //console.log(data);
                if(data[0] == 1){
                    var gl_container = $('.gallery-lb');
                    var text_container = $('.detail-text');
                    var product = data[1];
                    var location;
                    var html = "";
                    var size;
                    var i;
                    var temp;
                    var category_name;
                    var category;
                    var seller = data[2];
                    $('.detail-text').empty();


                    if (product['photo'].length > 0){
                        //alert('hter');
                        size = product['photo'].length;
                        for (i = 0; i< size ; i++){
/*
                            location = movie['photos'][i]['location']+'\\'+movie['photos'][i]['file_name'];
                            html = html + '<a class="flex-c-m size-108 how-pos1 bor0 fs-16 cl10 bg0 hov-btn3 trans-04" href="'
                                        +location+'">';
                            html = html + '<i class="fa fa-expand"></i></a>';
*/
                            location = '/'+product['photo'][i]['location']+'/'+product['photo'][i]['file_name'];
                            html = html + '<div class="item-slick3" data-thumb="'+location+'">';
                            html = html + '<div class="wrap-pic-w pos-relative">';
                            html = html + '<img src="'+location+'" alt="IMG-PRODUCT">';
                            html = html + '<a class="flex-c-m size-108 how-pos1 bor0 fs-16 cl10 bg0 hov-btn3 trans-04" href="'
                                        +location+'">';
                            html = html + '<i class="fa fa-expand"></i></a></div></div>';

                        }
                        gl_container.prepend(html);
                        html = "";
                    }


                    if (product['thumbnail'] !== null){
                        location ='/'+ product['thumbnail']['location']+'/'+product['thumbnail']['file_name'];

                    }else{
                        location ='/'+product['thumbnail_id'];
                    }

                    html = '<div class="item-slick3" data-thumb="'+location+'">';
                    html = html + '<div class="wrap-pic-w pos-relative">';
                    html = html + '<img src="'+location+'" alt="IMG-PRODUCT">';
                    html = html + '<a class="flex-c-m size-108 how-pos1 bor0 fs-16 cl10 bg0 hov-btn3 trans-04" href="'
                                +location+'">';
                    html = html + '<i class="fa fa-expand"></i></a></div></div>';

/*                    html = html + '<a class="flex-c-m size-108 how-pos1 bor0 fs-16 cl10 bg0 hov-btn3 trans-04" href="'
                                +location+'">';
                    html = html + '<i class="fa fa-expand"></i></a>';
*/
                    gl_container.prepend(html);
                    html = "";

                    category_name = "";
                    category = product['category'];
                    //alert(category);
                    for (i = 0 ; i < category.length; i++){

                        category_name = category_name + category[i].name +  ", ";
                    }
                    category_name = category_name.substring(0, category_name.length - 2);


                    html = '<h4 class="mtext-105 cl2 js-name-detail p-b-14">'+product.name+'</h4>';
                    html = html + '<span class="mtext-106 cl2">Price : '+product.price+'</span>';
                    html = html + '<p class="stext-102 cl3 p-t-23">Description : '+product.description+'</p>';
                    html = html + '<p class="stext-102 cl3 p-t-23">Availability : '+product.status+'</p>';
                    html = html + '<p class="stext-102 cl3 p-t-23">Like : '+product.like_number+'</p>';
                    html = html + '<p class="stext-102 cl3 p-t-23"><b>Category : </b>'
                            +category_name+'</p>';
                    html = html
                            +'<p class="stext-102 cl3 p-t-23">'
                             +   '<b>Seller : </b><a href="/shop/'+seller.seller_id+'">'
                            +seller.name
                            +'</a></p>'


                            +'<p class="stext-102 cl3 p-t-23">'
                             +   '<b>Address : </b>'
                            +seller.address
                            +'</p>'

                            +'<p class="stext-102 cl3 p-t-23">'
                             +   '<b>Email : </b>'
                            +seller.email
                            +'</p>'
                            +'<p class="stext-102 cl3 p-t-23">'
                             +   '<b>Phone : </b>'
                            +seller.phone
                            +'</p>'

                            +'<p class="stext-102 cl3 p-t-23">'
                             +   '<b>Message_Account : </b>'
                            +seller.message_account
                            +'</p>'

                           + '<p class="stext-102 cl3 p-t-23">'
                            +    '<b>Type : </b>'
                            +seller.type
                            +'</p>';

                    html = html + '<div class="flex-w flex-m p-l-100 p-t-40 respon7 facebookshare"></div>'

                    text_container.prepend(html);
                    temp  =  encodeURIComponent(window.location.protocol+'//'
                                + window.location.hostname+(window.location.port ? ':'+window.location.port: '')
                                + '/product/' + product['product_id'] );
                    html = '<iframe src="https://www.facebook.com/plugins/share_button.php?href='+temp+'&layout=button&size=small&width=59&height=20&appId" width="59" height="20" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>';
                    $('.facebookshare').append(html);
                    $('.gallery-lb').each(function() { // the containers for all your galleries
                        $(this).magnificPopup({
                            delegate: 'a', // the selector for gallery item
                            type: 'image',
                            gallery: {
                                enabled:true
                            },
                            mainClass: 'mfp-fade'
                        });
                    });

                    $('.wrap-slick3').each(function(){
                        var ele = $(this).find('.slick3');

                        if (ele !== null){

                            ele.slick({
                                slidesToShow: 1,
                                slidesToScroll: 1,
                                fade: true,
                                infinite: true,
                                autoplay: false,
                                autoplaySpeed: 6000,

                                arrows: true,
                                appendArrows: $(this).find('.wrap-slick3-arrows'),
                                prevArrow:'<button class="arrow-slick3 prev-slick3"><i class="fa fa-angle-left" aria-hidden="true"></i></button>',
                                nextArrow:'<button class="arrow-slick3 next-slick3"><i class="fa fa-angle-right" aria-hidden="true"></i></button>',

                                dots: true,
                                appendDots: $(this).find('.wrap-slick3-dots'),
                                dotsClass:'slick3-dots',
                                customPaging: function(slick, index) {
                                    var portrait = $(slick.$slides[index]).data('thumb');
                                    return '<img src=" ' + portrait + ' "/><div class="slick3-dot-overlay"></div>';
                                },
                            });

                        }
                    });

                }
            },
            error: function(data){
                console.log(data);
            }

        });

    });

    $(document).off('click','.js-hide-modal1');
    $(document).on('click','.js-hide-modal1',function(){
        $('.js-modal1').removeClass('show-modal1');
        $('.gallery-lb').slick('unslick');
        $('.gallery-lb').empty();
        $('.detail-text').empty();

    });

    //end quick view
    //added by vanna

    /*===================================================================[ Load more ]*/


    $(document).off('click','#loadmore');
    $(document).on('click', '#loadmore', function(){

        var offset = parseInt($('#offset').val());
        var seller_id = $(this).data('seller_id');
        var features = $(this).data('features');
        if (seller_id === undefined){
            seller_id =0;
        }

        if (features === undefined){
            features = 0;
        }

        //alert(window.location.protocol +'//'+window.location.host+"/admin/product/getproductmore/");
        $.ajax({
                    type:"GET",
                    url:window.location.protocol +'//'+window.location.host+"/admin/product/getproductmore/",
                    data:{ offset: offset ,  seller : seller_id , features:features}   ,
                    success: function (data) {
                        console.log(data);
                        if(data[0] == 1){
                            var i;
                            var items = data[2];
                            var $content;
                            for (i=0; i< items.length; i ++){
                                $content = $(items[i]);
                                $('.isotope-grid').append( $content )
                                                    .isotope( 'insert', $content );
                            }

                            offset = offset  +items.length;
                            $('#offset').val(offset);
                        }

                        $('.totalSize').val(data[1]);
                        updateSize();
                    },
                    error: function(data){
                        console.log(data);
                    }
            });

    });


    $(document).off('click','#loadmore_shop');
    $(document).on('click', '#loadmore_shop', function(){

        var offset = parseInt($('#offset').val());

        //alert(offset);
        $.ajax({
                    type:"GET",
                    url:"admin/seller/getsellermore/",
                    data:{ offset: offset  }   ,
                    success: function (data) {
                        console.log(data);
                        if(data[0] == 1){
                            var i;
                            var items = data[2];
                            var $content;
                            for (i=0; i< items.length; i ++){
                                $content = $(items[i]);
                                $('.isotope-grid').append( $content )
                                                .isotope( 'insert', $content );
                            }

                            offset = offset  +items.length;
                            $('#offset').val(offset);
                        }
                        updateSizeShop();
                    },
                    error: function(data){
                        console.log(data);
                    }
            });

    });


 /*===================================================================[ sort by ]*/


    $topeContainer.isotope({
        getSortData: {
            product_id: '[data-product_id] parseInt',
            name: function (itemElem){
                var name = $(itemElem).find('.pname').text();
                return name.toLowerCase();
            },
            price:function( itemElem ) { // function
                var price = $(itemElem).find('.price').text();
                return parseFloat(price);
            }
        },
    });

    $(document).off('click','.sort-by');
    $(document).on('click','.sort-by', function(){
        var sort_by = $(this).data('sort');
        var old_sort_by = $('.filter-link-active.sort-by');
        old_sort_by.removeClass('filter-link-active');
        $(this).addClass('filter-link-active');

        if(sort_by == 'default'){
            $topeContainer.isotope({
                sortBy: ''
            });
        }else if(sort_by == 'name'){
            $topeContainer.isotope({
                sortBy: 'name',
                sortAscending: true
            });
        }else if(sort_by == 'newness'){
            $topeContainer.isotope({
                sortBy: 'product_id',
                sortAscending: false
            });
        }else if (sort_by == 'hightolow'){
            $topeContainer.isotope({
                sortBy: 'price',
                sortAscending: true
            });
        }else if (sort_by == 'lowtohigh'){
            $topeContainer.isotope({
                sortBy: 'price',
                sortAscending: false
            });
        }
    });

/*===================================================================[ filter by ]*/
    $(document).off('click','.filter-by');
    $(document).on('click','.filter-by', function(){


        var old_active = $('.filter-link-active.filter-by');


        $(this).addClass('filter-link-active');
        old_active.removeClass('filter-link-active');

        $('.filter-price').val($(this).data('filter'));



        $topeContainer.isotope({

            filter: function() {
                return perform_filter($(this));
            }

        });

        updateSize();




    })

    /*===================================================================[ search by name ]*/

   $(document).off('keyup','#search_name');
   $(document).on('keyup','#search_name', function(){
        $topeContainer.isotope({

            filter: function() {
                return perform_filter($(this));
            }

        });
        updateSize();
   });
   function updateSize(){
       var totalSize = $('#totalSize').val();
       var loaded = $('#offset').val() ;
       var displayed = $('.isotope-grid').data('isotope').filteredItems.length;
        $('.loaded-report').text( loaded
            + ' out of ' + totalSize + ' products loaded. '
             + ((displayed<loaded)?  displayed + ' products displayed after filtered.' : '')
        );
   }


   $(document).off('keyup','#search_shop_name');
   $(document).on('keyup','#search_shop_name', function(){
        $topeContainer.isotope({

            filter: function() {
                var filter_by_name = $('#search_shop_name').val().trim().toLowerCase().split(' ');
                var shop_name = $(this).find('.sname').text().toLowerCase();
                var i;
                if (filter_by_name.length == 0)
                    return true;
                else {
                    for (i =0; i < filter_by_name.length ; i++){
                        if (shop_name.indexOf(filter_by_name[i] ) != -1){
                            return true;
                        }
                    }
                }
                return false;
            }

        });
        updateSizeShop();
   });
   function updateSizeShop(){
       var totalSize = $('#totalSize').val();
       var loaded = $('#offset').val() ;
       var displayed = $('.isotope-grid').data('isotope').filteredItems.length;
        $('.loaded-report').text( loaded
            + ' out of ' + totalSize + ' shops loaded. '
             + ((displayed<loaded)?  displayed + ' shops displayed after filtered.' : '')
        );
   }

})(jQuery);
<file_sep>/routes/breadcrumbs/backend/category.php
<?php
Breadcrumbs::for('category.index', function ($trail) {
    $trail->push( 'List Category', route('category.index'));
});

Breadcrumbs::for('category.create', function ($trail) {
    $trail->parent('category.index');
    $trail->push( 'Create Category', route('category.create'));
});

Breadcrumbs::for('category.edit', function ($trail,$id) {
	$trail->parent('category.index');
    $trail->push( 'Create Category', route('category.edit',$id));
});

Breadcrumbs::for('category.showrate', function ($trail) {
	$trail->parent('category.index');
    $trail->push( 'Rate Category', route('category.rate'));
});


Breadcrumbs::for('category.rate', function ($trail) {
	$trail->parent('category.index');
	$trail->parent('category.showrate');
    $trail->push( 'Show Rate', route('category.showrate'));
});

