mercredi 26 décembre 2018

How i get image from database to view file in laravel

 <img  src=""  width="140" height="140">

this is the line which i use to get image from database to view file

i use bellow controller to get this image

public function show($id)
{

    $post=Clients::find($id);
    return view('pet.shw',['post'=>$post,'pets'=>$post->pets]); }

and also migration file is shown bellow

public function up()
{
    Schema::create('clients', function (Blueprint $table) {
        $table->increments('id');
        $table->string('ename');
        $table->string('mobile');
        $table->string('mail');
        $table->binary('image') ; //image that i wanna use 
        $table->mediumText('Discription');
        $table->timestamps();
    });
}

this approach was not worked view shows like this how can i solve this problem,suggest the new approaches better than that, i can't use public/storage folder because of all the images should be saved in database



via Chebli Mohamed

lundi 24 décembre 2018

Improving a model attribute for better efficiency and usability

Framework: Laravel 5.1

Background: I have a Product and a ProductVariation model, which both share a ImplementsProductAttributes trait. If a Product is variable, than the product should contain at least a single purchasable ProductVariation to be purchasable, rest of the logic would be obvious within the code sample from the trait. Functionality works as is.

public function getPurchasableAttribute()
{
    if ($this instanceof \App\Product)
    {
        if ($this->type == 'variable')
        {
            foreach ($this->variations as $variation)
            {
                if ($variation->purchasable)
                    return true;
            }

            return false;
        }
        else return $this->isItemPurchasable();
    }
    else
    {
        return $this->isItemPurchasable();
    }
}

public function isItemPurchasable()
{
    if($this->regular_price > 0 AND $this->published)
    {
        if ($this->manage_stock) 
        {
            return $this->stock_quantity > 0;
        }
        else return $this->in_stock;
    }
    else return false;
}

Pros:

  • I make use of laravels attributes,
  • Readable/maintainable code,

Cons:

  • Redundant eager loading on the variations (which could be a problem if this was supposed to be used on an API)
  • Redundant SQL queries (I could implement a single query to get a count in the end, and decide based on that if the product itself is purchasable, but instead I am loading all variations -- at least until i get one with purchasable=true --)

Question: Should I keep this implementation or should I improve by getting rid of pulling relationships and making a simple SQL query to get the purchasable variations?

Please elaborate on your answer as much as you can.

Edit: Also please let me know if you think any other pros/cons exist.



via Chebli Mohamed

dimanche 23 décembre 2018

SVN forbidden by the server issue

I am getting below error while I am committing in SVN.

foysal@laptop:~/Videos/osmall/trunk$ svn commit -m "fixed form submission"
Sending        app/Http/Controllers/DebitNoteController.php
Sending        app/Http/Controllers/SellerHelpController.php
Sending        config/database.php
Sending        resources/views/debitnote/debitnote_view.blade.php
Sending        resources/views/jaguar/jaguar.blade.php
Sending        resources/views/seller/debtor_ageing.blade.php
Sending        resources/views/seller/members.blade.php
Transmitting file data ...svn: E195023: Commit failed (details follow):
svn: E195023: Changing file '/home/foysal/Videos/osmall/trunk/config/database.php' is forbidden by the server
svn: E175013: Access to '/repos/osmall/!svn/txr/10920-90t/trunk/config/database.php' forbidden



via Chebli Mohamed

jeudi 20 décembre 2018

Got GLib-GObject-CRITICAL **: g_type_class_unref: assertion 'g_class != NULL' failed from laravel php controller

I have a file container encrypted via VeraCrypt in a USB flash drive, and I have a Web App based on the LAMP stack and under Laravel framework. Now, I want to mount the encrypted file via the laravel php controller like this:

$cmd = 'veracrypt -p "longlongpassword" /media/username/usbName/encryptedFile /media/veracrypt1'; $process = new Process($cmd); $process->run();

but got an error message says: "GLib-GObject-CRITICAL **: g_type_class_unref: assertion 'g_class != NULL' failed"

However, if I run the command

veracrypt -p "longlongpassword" /media/username/usbName/encryptedFile /media/veracrypt1

from Ubuntu terminal, then it is successfully done without any error.

Can anyone give some suggestion about how to solve this issue? Thanks.



via Chebli Mohamed

lundi 17 décembre 2018

Laravel Secuirty Audit Service

enter image description here

I am using Laravel framework 5.1 for my web application. I'm looking for an audit service where they can scan my current Laravel application for any security flaws before deployment to production environment.

How do I find those type of service online?

Can someone suggest something, please ?



via Chebli Mohamed

How to filter duplicated data of queried result?

 $users = UserDetails::select('user_details.user_id','user_details.user_nickname',
'user_media.media_url','sport_group_details.sport_group_name')
->join('users', function($join)
{
    $join->on('user_details.user_id', '=', 'users.id');

})->join('user_media',function($join){

    $join->on('user_details.user_id', '=', 'user_media.user_id');

})->join('user_to_sport_group_values',function($join){

    $join->on('user_media.user_id', '=', 'user_to_sport_group_values.user_id');

})->join('sport_group_details',function($join){

    $join->on('user_to_sport_group_values.sport_group_id', '=', 'sport_group_details.sport_group_id');

})
->selectRaw('( 6371 * acos( cos( radians(?) ) *
cos( radians( user_lat ) )
* cos( radians( user_lng ) - radians(?)
) + sin( radians(?) ) *
sin( radians(user_lat ) ) )
) AS distance', [$lattitude, $longitude, $lattitude])
->havingRaw("distance <= ?", [$max_distance])
->orderBy('distance')
->orderBy('user_details.user_nickname')->where('users.id','!=',$user_id)
->where('media_type','=','profile')
->where('sport_group_details.language_code','=', $country_code)
->get();

The User can have more than one sport_group_name So i want to get all the sport_group_name for indivisual user along with other data,But i am getting user duplicated multiples times , how can i filter that duplicated users, Any Help would be much appreciated , Thanks in advance.



via Chebli Mohamed

samedi 15 décembre 2018

Calling API of another laravel project

I have two laravel projects. One of them has an API

I am trying to get data using the API.

public function getSyncOrders() {
    $orders = Invoice::where('status', 0)->get();
    return response()->json([
        'data' => [
            'orders'                => $orders
        ]
    ], 200);      
}

I am trying to fetch data in the other laravel project.

public function syncOrders() {
    if(auth()->check()){
        Order::truncate();

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://project1.net/api/sync-orders",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 600,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET"
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            //echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
    }
    else{
        return redirect('/');
    }
}

But I get the error :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'project2.invoice' doesn't exist (SQL: select * from invoice where status = 0)

Project 1 has table invoice in database while project 2 has table orders in database.

If I use the url http://project1.net/api/sync-orders in browser, it returns data.

I need help to fix the curl request so that project 2 doesn't execute code and search in its own database but instead get the data from the API.



via Chebli Mohamed

vendredi 14 décembre 2018

Laravel Call to a member function follows() on a non-object issue

My UserController includes the following:

public function doaction($domain, $some_id)
{
  $user = User::find(Sentry::getUser()->id);
  $user->doactions()->attach($some_id);
  $response = array('message' => 'doactioned', 'url' => 'http://'.$domain.'.'.Config::get('database.domain').'/undoaction/'.$some_id);
  return Response::json($response);
}

My routes.php includes also the following line:

Route::get('/{name}/doaction/{some_id}', array('as' => 'doaction', 'uses' => 'UserController@doaction'));

I am trying to call this front he frontend:

<a href="" class="tumblerclone-btn"> <i class="glyphicon glyphicon-plus"></i> Do action here </a>

And once its pressed (the URL is echoed properly), it leads me to an error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException Call to a member function doactions() on a non-object

The highlighted code part of the error is:

public function doaction($domain, $some_id)
{
  $user = User::find(Sentry::getUser()->id);
  $user->doactions()->attach($some_id);
  $response = array('message' => 'doactioned', 'url' => 'http://'.$domain.'.'.Config::get('database.domain').'/undoaction/'.$some_id);
  return Response::json($response);
}

Any ideas are appreciated in advance.



via Chebli Mohamed

mardi 11 décembre 2018

Laravel 5.1 Intervention Image compressing

I use Laravel 5.1 and the intervention package: http://image.intervention.io/

I try to compress my images. I would like to upload a 2.5Mb image and compress it by reducing the image size to arround 700kb by keeping the resolution and the image quality. Just reducing a large image file to a small one. The uploaded image is a .jpg file

I use the following code:

$targetFolder = public_path().'/images/';
$name=$image->getClientOriginalName();
$extension = $image->getClientOriginalExtension(); // add
$picture = sha1($name . time()) . '.' . $extension; //add

$image->move($targetFolder, $picture);
$image = \Intervention\Image\Facades\Image::make(sprintf('images/%s', $picture))->encode('jpg', 75);

But my image size is still arround 2.07Mb

The question is what method I have to use to get the desired result?



via Chebli Mohamed

mewebstudio/captcha wrong captcha in validation

I know this topic is existing, but no one could solve my problem.
I am using the library mewebstudio/captcha, everything is fine, but when I submit, it tells me always that the captcha is wrong.

My validation rules:

'captcha' => 'required|captcha'

In my html form:

<?= captcha_img(); ?>
<input type="text" name="captcha">



I am using php5.6, Laravel 5.1 and mews/captcha 2.2



via Chebli Mohamed

vendredi 7 décembre 2018

Session expired randomly in laravel 5.1

session is being expired randomly after some pages requests. it is not fixed some time session expired between 10 to 15 minutes , some times session expired after 2 to 3 pages request only . And some times not every times when i posting data from a page it say's TokenMismatchException in VerifyCsrfToken.php but i've added in the form .

I'm using database driver for session. i would like to tell that before this i was using file driver for session but there was same condition.

here is my config/session.php file

``

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'database'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 120,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'laravel_session',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => null,

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => false,

]; ``



via Chebli Mohamed

mardi 4 décembre 2018

How to apply add Click event in laravel full calendar for particular event?

I am trying to apply click event on individual event once the user click on any event it should open a pop up or anything like that but i am not able to achieve this ,Any help would be much appreciated Thanks in advance, below is the code. `

@extends('layouts.app')
@include('layouts.navigations.profile')
@include('layouts.header')
@section('style')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>
@endsection
@section('content')
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card pd-card">
                    <div class="panel panel-default">
                        <div class="panel-heading"></div>
                        <div class="panel-body">
                            {!! $calendar->calendar() !!}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('script')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>
    {!! $calendar->script() !!}
@endsection
@section('script')
    <script>

    </script>
@endsection`



via Chebli Mohamed

lundi 3 décembre 2018

Undefined index: collation laravel 5.1 mysql connection

I m using laravel 5.1 to make connection to mysql host.Here is the sample.

\Config::set('database.connections.mysql', array(
        'driver' => 'mysql',
        'host' => "host name",
        'port' => 3306,
        'database' => 'db name',
        'username' => 'username',
        'password' => 'password'
    ));
$data = \DB::connection('mysql')
        ->table('tablename')
        ->get();

When i run the above code i get the error::

    [ErrorException]            
    Undefined index: collation 



via Chebli Mohamed

Laravel 5.1 Max image size

I'm using Laravel 5.1 and php 7. I try to implement an image upload. Large images fails to upload. (A white screen appears with no error message) I tested it locally on xampp and on a webspace. With small images it works. It fails with an image of 2.5MB but the max value is 5000.

My controller:

public function fileUpload(Request $request)

{

     $this->validate($request, [

        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5000',
     ]);


     $image = $request->file('image');

     $input['imagename'] = time().'.'.$image->getClientOriginalExtension();

     $destinationPath = public_path('/images');

     $image->move($destinationPath, $input['imagename']);


    $this->postImage->add($input);


    return back()->with('success','Image Upload successful');

}

The questions:

  1. Why there is no error message? Only a white screen appears when it fails to upload. (Maybe there is a necessary configuration to do in one of the laravel config files?
  2. Why it works with smaller images? Where in xampp and on the webspace it's a configuration necessary?


via Chebli Mohamed

dimanche 2 décembre 2018

How to send sms in laravel to all users if users table city matches with services table city?

I want to send sms to all users in laravel if service's table city field matches with user's city field.

Take a example:- if i submit a form for a service by selecting a city, then it will match with the users city field, if it matches then automatically send a sms to all users with same city..



via Chebli Mohamed

mardi 27 novembre 2018

Truncate a table base on database connection in Laravel 5

I have a database connection nuc I have a table name Alerts

I'm trying to truncate that table by doing this

DB::connection('nuc')->statement('TRUNCATE Alerts');

I kept getting

enter image description here

QueryException in Connection.php line 629: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "alerts" does not exist (SQL: TRUNCATE Alerts)

How do I force truncate a table base on database connection?



via Chebli Mohamed

lundi 26 novembre 2018

How do I prevent other users from high jacking the HTTP request payload as other users?

I have

a laravel app with the route

Route::put('/api/{deviceMac}/access/update','DeviceController@update');

rule

If user A have deviceMac 000000000000, should only be making a PUT to

http://www.app.com/api/000000000000/access/update
{deviceMac:000000000000, access: true}

If user B have deviceMac 111111111111, should only be making a PUT to

http://www.app.com/api/111111111111/access/update
{deviceMac:111111111111, access: true}

User A should not be able hijacking the route update of other users

hijacking

User A should have access to 000000000000 only,

Right now, User A can tweak the HTTP request and make a PUT as User B

http://www.app.com/api/111111111111/access/update
{deviceMac:111111111111, access: false}


Questions

How do I prevent other users from high jacking the request payload as other users ?

Should I adjust my middleware to take care of this issue ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

samedi 24 novembre 2018

Laravel: is it possible to do orWhere(Model::find())?

I am using Lumen Laravel 5.1. I have a many to many relation between task and user, and pivot table called task_user, I recently asked this question, inspired by the answer and by reading the documentation, I think I can do this

$users = User::tasks()
        ->where('domain_id', $domainId)
        ->where('created_by', $userId)
        ->orWhere(User::tasks()->find($userId))
        ->Where(function ($query) {
            $query->where("is_done", 0)
                ->orderBy('due_date', 'DESC');
        })
        ->Where(function ($query) {
            $query->Where("is_done", 1)
                ->Where("closed_dated", Carbon::today())
                ->orderBy('closed_date', 'ASC');
        })
        ->get();

Before I accept his answer I have two questions:

1- A user can have his id related to a task, in 2 places

  • task_user table if is an assignee
  • created_by in tasks table, if he created it

So I want to know if he's an assignee or if he created it, both cases I want to display his tasks. Found nothing on google, so can I do this?

where(....) -> orwhere(model::find())

  1. My second question is: Should I use ->pivot->id to get to task, instead of find()? The docs about ->pivot are confusing and the tutorials I read don't use it. I don't know if it helps me.


via Chebli Mohamed

mardi 20 novembre 2018

vendredi 16 novembre 2018

auth()->user()->id is not working when I use it in controller using routes to api.php

public function store(Request $request)
    {
        $booking = ($request->isMethod('put')) ? Booking::findOrFail($request->booking_id) : new Booking;
        $booking->checkIn = $request->checkIn;
        $booking->checkOut = $request->checkOut;
        $booking->room_id = $request->room_id;
        $booking->user_id = auth()->user()->id;//not working

        if($booking->save()){
            return new BookingResource($booking);
        }
    }

Route::put('/booking','BookingsController@store');//api.php

Here auth()->user()->id is not working but its working find if i use it the same code but route code in routes/web.php



via Chebli Mohamed

jeudi 15 novembre 2018

Can't modify 'updated_at' in my database after adding a column with a migration in Laravel 5.1

I am trying to add a new integer "id" column in a table of my database to map every row with an id. In order to do so, I am using a migration in Laravel 5.1. The run() function of the migration is exactly the following:

public function up()
{
    Schema::table('license_keys', function($table) {
        $table->integer('id_nuevo');
    });
}

The table I am trying to modify is set with default 'updated_at' and 'created_at' timestamps.

I execute the migration and the column is added correctly. I made sure to add the new column in the $fillable variable in my model. The next step in the process is to set the ids correctly, because that column is created with all 0s. In order to do so, I am using a Seeder with the following code:

public function run()
{
    $i=1;
    $licenses = LicenseKey::getEveryLicenseKey();
    foreach ($licenses as $license){
        $license->id_nuevo = $i;
        //$license->timestamps = false;
        $license->save();
        $i++;
    }

}

But the problem starts here. When I try to update any field of any row with the save() function it gives me the following error:

[Illuminate\Database\QueryException]                                                                                                                                                                     
 SQLSTATE[21S01]: Insert value list does not match column list: 1136       Column count doesn't match value count at row 1 (SQL: update `license_keys`   set `id_nuevo` = 1, `updated_at` = 2018-11-15 13:24:11   
 where `hash_key` = 0...0b)                                                                                                                                                     



  [PDOException]                                                                                                       
  SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1

But if I set the timestamps to false (commented line in the code), the operation succeeds. Even if I try to manually change the value of the 'updated_at' column in phpMyadmin, it gives me the same error. Can anybody help me with this problem?

Thanks



via Chebli Mohamed

dimanche 11 novembre 2018

The installation directory "/usr/local/bin" is not writable - How to fix this? I am trying to install the composer globally

ERROR message while trying to setup Composer

192:~ biancalouisedairo$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" 192:~ biancalouisedairo$ php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" Installer verified 192:~ biancalouisedairo$ php composer-setup.php --install-dir=/usr/local/bin All settings correct for using Composer The installation directory "/usr/local/bin" is not writable 192:~ biancalouisedairo$



via Chebli Mohamed

jeudi 8 novembre 2018

Is there a portable PHP artisan tool?

At work, we are using PHP 5.6, Lumen 5.1. Due to some setup issues related to the project and work, I cannot run any composer command nor PHP artisan, I get errors like this and others. The project only runs on the server. Now if I want to create a table, I have two options:

  • Run the migration on the server, then download it using sftp
  • Create another lumen project on my PC, do migration and then move them to the project's folder

Is there a portable php artisan I can put in the project folder or can I alias php artisan from some other lumen project to generate files in the project I work on?



via Chebli Mohamed

mercredi 7 novembre 2018

How can I change "127.0.0.1:8000" to my desired url. (laravel)

I'm using laravel and I don't know how to customize the default url which is "127.0.0.1:8000" or "localhost:8000" to my desired url.

My expectation is to change 127.0.0.1:8000 to sample.dev when I do php artisan serve

Do I really need to move my projects to htdocs or www?

Please help...



via Chebli Mohamed

mardi 6 novembre 2018

NPM installation problem In Laravel in Windows 10

My NPM ver is 5.6.0 My Node ver is v8.11.3 Laravel Framework 5.7.12

I have some Problems When i want to install The npm in laravel which are as follows

npm install

npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.

npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.

node-sass@4.10.0 install C:\xampp\htdocs\Newapp\node_modules\node-sass

node scripts/install.js

'node' is not recognized as an internal or external command, operable program or batch file.

npm WARN img-loader@3.0.1 requires a peer of imagemin@^5.0.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! node-sass@4.10.0 install: node scripts/install.js

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the node-sass@4.10.0 install script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\bamas\AppData\Roaming\npm-cache_logs\2018-11-07T03_33_04_531Z-debug.log

MY package.json is

{ "private": true, "scripts": { "dev": "npm run development", "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "npm run development -- --watch", "watch-poll": "npm run watch -- --watch-poll", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "prod": "npm run production", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "axios": "^0.18", "bootstrap": "^4.0.0", "cross-env": "^5.1", "jquery": "^3.2", "laravel-mix": "^2.0", "lodash": "^4.17.5", "popper.js": "^1.12", "vue": "^2.5.17" } }

I already tried everithing like cache clear re installing nodemodules but its not effect.. My NPM is alright Because whenever i run my other Nodejs script it work perfectly i am using gitbash....



via Chebli Mohamed

none Database Model two attributes in Laravel

i'm a newbie in Laravel Please Guide me.

1- Port is a Model and Coordinates is a none database Model. 2- 2 floats are lat and long in Port Model.

When a port is loaded from the database, the 2 floats are casted to a Coordinates-object. Second Question How to make a non-database model with two attributes.



via Chebli Mohamed

lundi 5 novembre 2018

Using multiple controllers in the same route gets route undefined

I get an error of undefined route when using multiple controllers in the same route:

Here is the code my controllers:

public function triealphabet(){
    $list_grocery = miscellaneous::all();
    $list_grocery = $list_grocery->sortBy('name');
    return view('markets.miscellaneous')->with('list_grocery',$list_grocery);}
public function triecreation(){
    $list_grocery = miscellaneous::all();
    $list_grocery = $list_grocery->sortBy('created_at');
    return view('markets.miscellaneous')->with('list_grocery',$list_grocery);}

and here are my routes code :

Route::get('/miscellaneous','groceryController@listGrocery')->name('groceriesmarket'); 
Route::get('/miscellaneous','groceryController@triealphabet')->name('triealphabet');
Route::get('/miscellaneous','groceryController@triecreation')->name('triecreation');

P.S: If I use an other route path like '/miscellanous-tri-alphabet' I don't get any other errors, but other than that I get an error of undefined route



via Chebli Mohamed

vendredi 2 novembre 2018

Can any one filter admin theme and give rank to the themes to use in laravel?

I am so confused to choose admin theme for laravel can anyone list me best admin panel as per its quality, and give description for what, that is flexible?



via Chebli Mohamed

kendo directive for anuglarjs how to update record with id and go to update page?

I have taken the id from selected field in kendo grid, and I am using angularjs directive. Now I don't understand how to update the selected Id record. I mean to say with the selected Id I want to go to update page. The work I have done is given below.

 (function () {
angular.module('moduleName').directive('kendoGridRowDblClick', kendoGridRowDblClick);

function kendoGridRowDblClick() {
    return {
        link: function (scope, element, attrs) {
            scope.$on("kendoWidgetCreated", function (event, widget) {

                if (widget !== element.getKendoGrid())
                    return;

                attachDblClickToRows(scope, element, attrs);

                //element.data("kendoGrid").bind('dataBound', function () {
                  //  attachDblClickToRows(scope, element, attrs);
                //});
            });
        }
    };

    function attachDblClickToRows(scope, element, attrs) {
         var id = $(element).find(".k-state-selected td:eq(1) span").html();
     console.log($(element).find(".k-state-selected td:eq(0) span").html());   
    }
})();

With td:eq(1) it gives me the correct id when I dblclick on a record in a grid, With console.log it gives me the span value which is given below, and i want to take the id and go to the new state for updating page. I have defined the span here which is hidden field

{field: "", hidden: true, template: "<span>Akhtar</span>"},

And ofcourse I have database fields too, but here I just want to go to an update state/page instead of just printing the span value Akhtar in console. Any help would be appreciated. Thanks in advanced



via Chebli Mohamed

jeudi 1 novembre 2018

Laravel package musonza/groups Laravel 5 user groups package how to start after running migrations?

I have been able to finish up but the migrations part but i don't know how to start I'm new to laravel and i want to use this package in a project i'm building. Any tutorials, guidance or recommendations is much appreciated.



via Chebli Mohamed

mercredi 31 octobre 2018

NotFoundHttpException error on post method Laravel 5.1

I got error NotFoundHttpException below

Error

Here is my route

Route::post('/ticket/{slug?}/edit', 'TicketsController@update');

My function update on TicketController

public function update($slug, TicketFormRequest $request)
{
    $ticket = Ticket::whereSlug($slug)->firstOrFail();
    $ticket->title = $request->get('title');
    $ticket->content = $request->get('content');
    if($request->get('status') != null) {
        $ticket->status = 0; } else {
    $ticket->status = 1;
}
$ticket->save();
return redirect(action('TicketsController@edit', $ticket->slug))->with('status', 'The ticket '.$slug.' has been updated!');

}

My function edit

 public function edit($slug)
{
    $ticket = Ticket::whereSlug($slug)->firstOrFail();
    return view('tickets.edit', compact('ticket'));
}

Am I missed something? I think my routes was right, maybe my update function is wrong



via Chebli Mohamed

lundi 29 octobre 2018

Query Builder Eloquent Where clause for TimeStamp - Laravel 5.1

I have a table and search bar.

enter image description here

When user input in the search that when I grab that and query my database.

This is what I got

public function getLogsFromDb($q = null) {

    if (Input::get('q') != '') {
        $q = Input::get('q');
    }
    $perPage = 25;

    if ($q != '') {

        $logs = DB::table('fortinet_logs')
            ->orWhere('account_id', 'like', '%'.$q.'%')
            ->orWhere('cpe_mac', 'like', '%'.$q.'%')
            ->orWhere('p_hns_id', 'like', '%'.$q.'%')
            ->orWhere('g_hns_id', 'like', '%'.$q.'%')
            ->orWhere('data', 'like', '%'.$q.'%')
            ->orWhere('created_at', 'like', '%'.$q.'%') <----🐞
            ->orderBy('updated_at', 'desc')->paginate($perPage) 
            ->setPath('');


            //dd($logs);

        $logs->appends(['q' => $q]);

    } else {

        $logs = DB::table('fortinet_logs')
            ->orderBy('created_at', 'desc')->paginate($perPage)
            ->setPath('');
    }

    return view('telenet.views.wizard.logTable', get_defined_vars());

}


Result

In the network tab, I kept getting

Undefined function: 7 ERROR: operator does not exist: timestamp without time zone ~~ unknown

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

samedi 27 octobre 2018

Laravel Model Factory Error: Trying to get property of non-object

I'm trying to use a model factory to seed my database, but when I run it I get the error:

Trying to get property 'id' of non-object

Here is my code:

// TasksTableSeeder.php

factory(pams\Task::class, '2000', rand(1, 30))->create();

// ModelFactory.php

$factory->defineAs(pams\Task::class, '2000', function (Faker\Generator $faker) {
static $task_number = 01;
return [
    'task_number' => $task_number++,
    'ata_code' => '52-00-00',
    'time_estimate' => $faker->randomFloat($nbMaxDecimals = 2, $min = 0.25, $max = 50),
    'work_order_id' => '2000',
    'description' => $faker->text($maxNbChars = 75),
    'action' => '',
    'duplicate' => '0',
    'certified_by' => '1',
    'certified_date' => '2015-11-08',
    'status' => '1',
    'created_by' => '1',
    'modified_by' => '1',
    'created_at' => Carbon\Carbon::now()->format('Y-m-d H:i:s'),
    'updated_at' => Carbon\Carbon::now()->format('Y-m-d H:i:s'),
    ];
});

I've tried removing all variables from the model factory and using constants, but that doesn't fix it. I've tried pulling the data from the ModelFactory.php and put it directly into the TasksTableSeeder.php and it does work, however I was using constants and no variables.

I cannot for the life of me figure out what 'id' it's talking about.

I'm running Laravel v5.1



via Chebli Mohamed

jeudi 25 octobre 2018

how to use this php sql on laravel??? (dynamic form field)

<?php
$fields = array(
 array(
 'meta_id' => 'name',
 'display_name' => 'Name'
 ),
 array(
 'meta_id' => 'address',
 'display_name' => 'Address'
 ),
 array(
 'meta_id' => 'cps_name',
 'display_name' => 'CSP Name'
 )
);


$tables = array();
$query_fields = array();
$joins = array();
$fcount = 1;


array_push($query_fields, "reports.*");

foreach ($fields as $key => $value) {
 $table_name = "tables" . $fcount++;
 array_push($query_fields, $table_name.".".$value['meta_id']." AS ".$value['display_name']);

 array_push($joins, "INNER JOIN reports_meta_values ".$table_name." ON reports.id = ".$table_name.".report_id AND ".$table_name.".meta_id='".$value['meta_id']."'");
}


$final_sql = "SELECT " .implode(",", $query_fields) . " FROM reports " . implode(" ", $joins). " WHERE 1";

echo "$final_sql";

?>



via Chebli Mohamed

Set up Laravel project to work with multiple Domain Name

enter image description here

I have successfully configured multiple domains to point to my Laravel 5.1 project

<Virtualhost *:80>
  VirtualDocumentRoot "/Users/Sites/project/public"
  ServerName app.com
  UseCanonicalName Off
</Virtualhost>

<Virtualhost *:80>
  VirtualDocumentRoot "/Users/Sites/project/public"
  ServerName app2.com
  UseCanonicalName Off
</Virtualhost>

<Virtualhost *:80>
  VirtualDocumentRoot "/Users/Sites/project/public"
  ServerName app3.com
  UseCanonicalName Off
</Virtualhost>

When I go to

app.com app2.com app3.com

any of them will point to my project and load the log-in screen.


Issue

When I login, regardless when I am from, I kept redirecting my users to

app.com/dashboard


Goal

My goal is, any request from

app.com  --> log-in --> redirect to --> app.com/dashobard
app2.com --> log-in --> redirect to --> app2.com/dashobard
app3.com --> log-in --> redirect to --> app3.com/dashobard


Questions

How would one go about and do this on a Laravel project ?

Is this something that I can do on the application layer or web server ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

How to insert in a translatable field?

Using Lumen 5.1, I'd like to know how to to CRUD on a translatable field, in my case it's name.

This is migration file

class CreateDomainHolidays extends Migration
{

    protected $table = 'domain_holidays';
    protected $app_table = true;

    public function up()

    {
        Schema::create($this->getTable(), function (Blueprint $table) {
            $table->increments('id');

            $table->integer('domain_id')->unsigned()->nullable();
            $table->foreign('domain_id')->references('id')
                ->on(self::getTableName('domains'))->onDelete('cascade');
            $table->string('name')->nullable()->default('')->translatable = true;
            $table->dateTime('start_date');
            $table->dateTime('end_date');
            $table->tinyInteger('half_day_start')->default(0);
            $table->tinyInteger('half_day_end')->default(0);
            $this->parenttable = $table;

        });
        $this->createTableWithTranslation($this->parenttable);

    }

    public function down()
    {
        $this->dropTranslationTable($this->getTable());
        Schema::drop($this->getTable());
    }
}

This is my model

 class Holiday extends BaseModel
    {
        protected $table = 'domain_holidays';
        protected $app_table = true;
        public $timestamps = false;

        protected $translation = true;
        public function translations()
        {
            return $this->hasMany('App\Models\General\HolidayTranslations', 'parent_id');
        }

    }

    class HolidayTranslations extends BaseTranslationModel
    {
        protected $table = 'domain_holidays_i18n';
        protected $primaryKey = 'translation_id';
    }
}

domain_holidays contains

id
domain_id
start_date
end_date
half_day_start
half_day_end

domain_holidays_i18n contains

translation_id
parent_id
lang
name

Something like this is not working

public static function setHoliday($domainId, $name, $startDate, $endDate, $halfDayStart, $halfDayEnd)
{
    Holiday::unguard();
    return Holiday::create([
        'domain_id' => $domainId,
        'name' => $name,
        'start_date' => $startDate,
        'end_date' => $endDate,
        'half_day_start' => $halfDayStart,
        'half_day_end' => $halfDayEnd
    ]);
}

Postman would return an error

SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;name&#039; in &#039;field list&#039;



via Chebli Mohamed

mercredi 24 octobre 2018

Laravel Data change when i pass it from Controller To view

i have relations path has many tags and tags have many tasks and tasks have many tags so task may have one or more tag . My Controller return tasks that have 1 tag only and is working fine

public function task(){

 $Tasks= Path::with(['pathtags' => function ($q) {
  $q->with(['Tasks'=>function($q) {
  $q->has('tasktags', '=' , 1)
 ->with('tasktags'); }]); 
 }])->first();

  return $Tasks;
}

but When I return $Tasks in view I get all tasks in the database

i tried

  return view('task', ['Tasks' => $Tasks);
  return view('box',compact('Tasks'));

but still get all tasks not one that have 1 tag



via Chebli Mohamed

mardi 23 octobre 2018

Laravel Assets Point to Localhost/public instead of localhost/project/public

I recently used git to clone a Laravel 5.1 project from a repository to my local environment. I am using XAMPP, so I placed the project under C:/xampp/htdocs and can access it from localhost/project/public.

I updated the APP_URL variable in the.env file to point to "http://localhost/project".

I also updated the url value in config/app.php to:

'url' => env('APP_URL', 'http://localhost/project')

Right now, the both scripts resolve as http://localhost/public/assets/js/test.js:

I removed "/public" (also "public", just tetsing things) and replaced with so that now the call looks like the following and the script resolved just fine:

<script src="/assets/js/test.js"></script>

However, elixir is also being used:

<script src="."></script>

The page is not loading correctly; an Ajax call that errors out because the URL is is trying to reach is localhost/public/someotherfolder/details?=12345).

The above script seems to be the source of that AJAX call; if I comment it out, then the call doesn't run.

I checked the rev-manifest.json and it specifies "js/app.js". If I try to changed the script call to I get a 404 error. If I try add the path in the elixir call, I get a "file is not defined in manifest". Changing the manifest to use the whole path seems to defeat the purpose.

How can I solve this issue? It seems like I am missing an important step to let my application resolve without using the full path?



via Chebli Mohamed

get tasks where all task tags is in path tags

My code returns tasks where one of Task Tags name ->(tasktags) is in Path Tags->$TagArray .

I want to get Tasks where all Task Tags (tasktags) are in Path Tags array ->$TagArray.

$posts4 = Path::with(['pathtags' => function ($q) use ($TagArray) {
    $q->with(['Tasks'=>function($q) use ($TagArray) { 
        $q->has('tasktags', '=' , 2)->whereHas('tasktags', function ($query) use 
            ($TagArray) {
            $query->whereIn('name',$TagArray);

        })->with('tasktags');
    }]);
}])->first()



via Chebli Mohamed

dimanche 21 octobre 2018

Parsing html, grabbing nodeValue problem with DOMdocument

Trying to parse html page, but having some trouble at grabbing nodeValue's of dt and dd tags.

$outlineUrl = "http://www.sumitomo-rd-mansion.jp/kansai/higashi_umeda/detail.cgi";
foreach ($outlineUrl as $results) {
       $html = file_get_contents($results);
       $DOMParser = new \DOMDocument();
       $DOMParser->loadHTML($html)           

   foreach ($DOMParser->getElementsByTagName('dl') as $tr) {
             $property = trim($tr->getElementsByTagName('dt')[0]->nodeValue);
             $value = trim($tr->getElementsByTagName('dd')[0]->nodeValue);
   }

with this I can't grab the dl's and dt's nodeValue. Is my foreach loops wrong or something? Thanks for helping me out!



via Chebli Mohamed

jeudi 18 octobre 2018

Laravel - Internal Server Error and Forbiden Access

I use cPanel tranfer tool to copy the website from a server to another server, but after that, I got Internal Server Error...

To solve that problem I run the command:

sudo chown -R perica:perica /home/perica/public_html/

after that:

sudo find /home/perica -type f -exec chmod 664 {} \; 

sudo find /home/perica -type d -exec chmod 775 {} \;

but I got again the same error.

I also try to sudo find /home/perica -type f -exec chmod 700 {} \; but then I got error

 Forbidden
You don't have permission to access /admin on this server.
Server unable to read htaccess file, denying access to be safe

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Also, my storage folder and bootstrap permission is 777.

What is the problem? I spend 2 days to solve this problem but no success! Please HELP!

UPDATE: I delete .htaccess file and now I see the Laravel folder structure but when I navigate a browser to domain.com/public folder again I got error.



via Chebli Mohamed

DB data's ID and paging the data differently with Laravel

I've table in DB which has estate datas. Now I'am retrieving those datas on the main blade. But also I want to retrieve those data separatly by their ID on another page. Do I need to create html table in a blade each of every ID? Or can I make it in just one blade? Or any idea?

Thank you!



via Chebli Mohamed

mardi 16 octobre 2018

My pagination not going next page, returns main page

I do pagination to table. But when I click the numbers just return the main page and Url shows like this: http://example/?q=?=大阪&page=2

This how I calling the links for pagination on view.blade



And this is the controller:

$q = $request->q;
        if ($q !== null && trim($q) !== ""){//here

            $estates = \DB::table('allestates')
                ->where("building_name","LIKE", "%" . $q . "%")
                ->orWhere("address","LIKE", "%" . $q . "%")
                ->orWhere("company_name","LIKE", "%" . $q . "%")
                ->orWhere("region","LIKE", "%" . $q . "%")
                ->orderBy('price')->get();


            $showPerPage = 10;

            $perPagedData = $estates
                ->slice((request()->get('page')) * $showPerPage, $showPerPage)
                ->all();

            $estates = new \Illuminate\Pagination\LengthAwarePaginator($perPagedData, count($estates), $showPerPage, request()
                ->get('page'));


            if(count($estates) > 0){
                return view("search", compact('estates'))->withQuery($q);
            }

        }

What am I missing here? My guess is it couldn't find the next page? But why?



via Chebli Mohamed

lundi 15 octobre 2018

Query a list of value of a specific column - Laravel

I'm trying to query a list as an array directly out of a table of my database without having to create another foreach loop and construct one myself.


I try

return Response::json(Skill::select('name')->get());

I get

[{"name":"Vagrant"},{"name":"Docker"},{"name":"Gulp"},{"name":"Heroku"},{"name":"RequireJS"},{"name":"AngularJS"},{"name":"Composer "},{"name":"NPM"},{"name":"MySQL"},{"name":"Sublime Text"},{"name":"Laravel"},{"name":"PyCharm"},{"name":"Mac OS X"},{"name":"Windows"},{"name":"Ubuntu"},{"name":"Cent OS"},{"name":"Photoshop"},{"name":"Illustrator"},{"name":"MobaXTerm"},{"name":"Terminal"},{"name":"iMovie"},{"name":"Final Cut"},{"name":"GitHub"},{"name":"BitBucket"},{"name":"Selenium"},{"name":"Python"},{"name":"Bower"},{"name":"Sass"},{"name":"Digital Ocean"},{"name":"Linode"},{"name":"Siteground"},{"name":"Go Daddy"},{"name":"Shopify"},{"name":"Facebook"},{"name":"Twitter"},{"name":"Salesforce"},{"name":"OAuth 2.0"},{"name":"SAML 2.0"},{"name":"OpenID Connect"},{"name":"PostgreSQL"},{"name":"Bash"},{"name":"PHP"},{"name":"Google Map"},{"name":"Google Translation"},{"name":"Instagram"},{"name":"LESS"},{"name":"Geolocation API"},{"name":"Xcode"},{"name":"Atom"},{"name":"Webpack"},{"name":"AWS Console"},{"name":"Secure Shell"},{"name":"Node"},{"name":"Yarn"},{"name":"Pod"},{"name":"EC2"},{"name":"Amazon ECS"},{"name":"S3"},{"name":"Amazon RDS"},{"name":"Camtasia"},{"name":"Core Data"},{"name":"Realm"},{"name":"VS Code"},{"name":"TextMate"},{"name":"TextWrangler"},{"name":"Laravel Elixir"},{"name":"Virtual Machine"},{"name":"Open  Stack"},{"name":"Redis"},{"name":"Local Storage"},{"name":"Protractor"},{"name":"Jest"},{"name":"Mocha"},{"name":"Chai"},{"name":"SinonJS"},{"name":"AWS"},{"name":"HTML"},{"name":"CSS"},{"name":"Javascript"},{"name":"Sketch"},{"name":"iOS"},{"name":"Express"},{"name":"Angular"},{"name":"React Native"},{"name":"jQuery"},{"name":"Nginx"},{"name":"Apache"},{"name":"PayPal"},{"name":"Square "},{"name":"Disqus"},{"name":"YouTube"},{"name":"Swagger"},{"name":"GitLab"},{"name":"Amazon ECR "},{"name":"Jira"},{"name":"Trello "},{"name":"Evernote "},{"name":"Confluence "},{"name":"Word"},{"name":"CodeBox"},{"name":"Markdown"},{"name":"Noteability"},{"name":"Kamar"},{"name":"Jasmine"},{"name":"Swift"},{"name":"Coda"},{"name":"Postman"},{"name":"Wireshark"},{"name":"Transmit"},{"name":"WinSCP"},{"name":"Navicat Premium"},{"name":"Kaleidoscope"},{"name":"Mind Note "},{"name":"Divvy"},{"name":"Duet"},{"name":"Draw.io"},{"name":"Google Draw"},{"name":"VMWare Fusion "},{"name":"Virtualbox"},{"name":"QuickBooks"},{"name":"Chat.io"},{"name":"FusionCharts"},{"name":"Google Chart"},{"name":"J Player"},{"name":"CKEditor"}]

I was trying to get these

["Vagrant","Docker","Gulp","Heroku","RequireJS","AngularJS","Composer ","NPM","MySQL","Sublime Text","Laravel","PyCharm","Mac OS X","Windows","Ubuntu","Cent OS","Photoshop","Illustrator","MobaXTerm","Terminal","iMovie","Final Cut","GitHub","BitBucket","Selenium","Python","Bower","Sass","Digital Ocean","Linode","Siteground","Go Daddy","Shopify","Facebook","Twitter","Salesforce","OAuth 2.0","SAML 2.0","OpenID Connect","PostgreSQL","Bash","PHP","Google Map","Google Translation","Instagram","LESS","Geolocation API","Xcode","Atom","Webpack","AWS Console","Secure Shell","Node","Yarn","Pod","EC2","Amazon ECS","S3","Amazon RDS","Camtasia","Core Data","Realm","VS Code","TextMate","TextWrangler","Laravel Elixir","Virtual Machine","Open  Stack","Redis","LocalStorage","Protractor","Jest","Mocha","Chai","SinonJS","AWS","HTML","CSS","Javascript","Sketch","iOS","Express","Angular","React Native","jQuery","Nginx","Apache","PayPal","Square ","Disqus","YouTube","Swagger","GitLab","Amazon ECR ","Jira","Trello ","Evernote ","Confluence ","Word","CodeBox","Markdown","Noteability","Kamar","Jasmine","Swift","Coda","Postman","Wireshark","Transmit","WinSCP","Navicat Premium","Kaleidoscope","Mind Note ","Divvy","Duet","Draw.io","Google Draw","VMWare Fusion ","Virtualbox","QuickBooks","Chat.io","FusionCharts","Google Chart","J Player","CKEditor"]


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

jeudi 11 octobre 2018

DOKU Payment Gateway for PHP Integration?

I want to ask about how to make doku payment integration to my website (laravel). Now I'm already have all the credentials needed(mallid, merchant) but i dont know how to start, if there's any refference it will help me, thank you.



via Chebli Mohamed

mardi 9 octobre 2018

Select top from group

I have model Message:

 protected $fillable = [
        'id','text','girl_id','date' ];

How to choose the last message by date for each girl_id?

My code:

   $messages=Message::select(['id','text','girl_id','date'])
                    ->groupBY('girl_id')
                    ->orderBY('date')
                    ->take(1)
                    ->get();



via Chebli Mohamed

lundi 8 octobre 2018

Article, Comment and User relationship in Laravel 5.1

I made a blog where you can CRUD articles and post comments. Everything is fine and working good.

I just want to make Laravel to do the magic when the User posts a comment to an article and instead of hard-coding article_id and user_id.

Comment::create([
    'body' => request('body'),
    'article_id' => $article->id,
    'user_id' => Auth::User()->id]
);

Is it possible to use Laravel's Eloquent relationships to chain up some functions/methods and simplify it a little bit?



via Chebli Mohamed

eager load model ids only

Using Laravel 5.1, I have deeply connected and nested models for my HTML5 game. When the player logs in, it loads their profiles.

Each profile has m:m completed quests, m:m completed tasks, m:m completed minigames, etc.

The quests/tasks/minigames are belongsTo relationship, i.e., Task belongsTo Quest, Minigame belongsTo Task, etc.

Eager loading these on the user->profile then takes a ton of time.

What I need to do instead then is eager load only the IDs of tasks, minigames, etc for the profile. I tried this via $appends:

class Profile extends BaseModel
{
    protected $with = ['game', 'quests'];

    protected $appends = ['task_ids'];

    public function getTaskIdsAttribute()
    {
        return $this->tasks->pluck('task_id');
    }

Still, this loads the models and an array of two null task Id values (The loaded task models eager load with their related children too.):

  • task_ids is an array with two null values.

  • tasks is an array with two eager loads Task models.

enter image description here

I need to speed up login so how can I load IDs only without the rest of the attributes?



via Chebli Mohamed

dimanche 7 octobre 2018

laravel update Has Many Relation for items in invoice

I'm trying to update items in the invoice, and I need and the problem when deleting item or add an item if I delete all item it updates I need help, please

invoice table

  • id
  • invoice _no
  • date
  • sub_total
  • discount
  • total

items table

  • id

  • item_code

  • item_desc

  • unit_price

invoice_items table

  • invoice_id

  • item_id

  • unit_price

  • qty

invoice model

public function items()
    {
        return $this->hasMany(InvoiceProduct::class, 'invoice_id');
    }

my controller update

$invoice = Invoice::findOrFail($id);

        $items = [];
        $itemIds = [];
        $subTotal = 0;

        foreach($request->items as $item) {
            if(isset($item['id'])) {
                InvoiceProduct::where('invoice_id', $invoice->id)
                    ->Where('id', $item['id'])
                    ->update($item);

                $itemIds[] = $item['id'];
               $item ='please re add items';
            } else {
                $items[] = new InvoiceProduct($item);
            }

            $subTotal += $item['unit_price'] * $item['qty'];
        }


        $data = $request->except('items');
        $data['sub_total'] = $subTotal;
        $data['total'] = $data['sub_total'] - $request->discount;

        $invoice->update($data);

        InvoiceProduct::whereNotIn('id', $itemIds)
            ->where('invoice_id', $invoice->id)
            ->delete();

        if(count($items)) {
            $invoice->items()->saveMany($items);
        }
 return response()
            ->json(['saved' => true, 'id' => $invoice->id]);
    }



via Chebli Mohamed

vendredi 5 octobre 2018

no hint path laravel

Hey guys it's my first time deploying my work online.. I have some couple of routes that work perfectly on my local but when I'm on the server I get this error..

View [frontoffice.Sondage.list_sondage] not found

I'm using l5-modular package for modules

it's something like :

app/
└── Modules/
    └── Poll/
        ├── Controllers/
        │   └── PollController.php
        ├── Models/
        │   └── Poll.php
        ├── Views/
        |     └── frontoffice
        │     └── Sondage
        |      └── list_sondage.blade.php
        ├── Translations/
        │   └── en/
        │       └── example.php
        ├── routes
        │   ├── api.php
        │   └── web.php
        └── helper.php

I'm returning this view :

 return view('Poll::frontoffice.Sondage.list_sondage',compact('resultats_groupe','config'));

what can be this error coming from?



via Chebli Mohamed

mercredi 3 octobre 2018

How to Searching between min and max prices in Laravel

I know in mysql query it is something like this

SELECT id 
FROM listings 
WHERE id  IN (
  SELECT id
  FROM listings
  WHERE price between 200 and 500
);

in laravel query I tired

Listing::select('listings.*')
                 ->whereBetween('price', [200, 500])
                 ->groupBy('listings.id')
                 ->orderBy('listings.id', 'desc')
                 ->paginate(1000);

did I wrong somewhere ? It just show only 1 result ?

thank you for your helps!



via Chebli Mohamed

mardi 2 octobre 2018

Autocomplete or Live search in Laravel/app.php

I am planning to develop a database. It's not started yet but I want to know whether it's possible to include autocomplete or Live search options in app.php.

Any ideas regarding this is welcome.

Thanks.



via Chebli Mohamed

Resolve index issue in php laravel [duplicate]

I'm trying to display download links(pdf) on my page but I'm getting an index error

Undefined offset: 6 (View: C:\xampp\htdocs\bluepenlabs\fta\app\Modules\Fta\views\frontoffice\Fta\voir-docs.blade.php)

This is my controller :

 public function docs(){
        $docs = Document::all();
        return view("Fta::frontoffice.Fta.voir-docs",compact('docs'));
 }

this is the view

 <?php
       if(file_exists(public_path('frontoffice/fichiers/docs'))){
         $files = File::allFiles(public_path('/frontoffice/fichiers/docs/'));
       }
       if(!empty($docs)){
               foreach ($docs as $doc){
                     //$fichier = explode("/", $file);
                     $fichier = explode("-", $doc['file']);
                    $ext = explode(".", $fichier[6]);

  ?>
        <span style="font-size: x-large;color: royalblue;"></span>
         <br><br>
         <p style="color: black">{!!  $doc->description !!}</p>
         <a href="/frontoffice/fichiers/docs//" download style="font-size: x-large"></a>

          @if($ext[1]== "pdf")
                <div class="box"><iframe src="/frontoffice/fichiers/docs//" width = "300px" height = "300px"></iframe></div>
           @endif  
           <br>   
           <medium> Crée le :  <br>Modifier le : </medium>
            <hr>
             <?php }
                   }
                  ?>

I tried to dd($fichier) it gives me this :

enter image description here



via Chebli Mohamed

Left Joining with two table does not work properly. It shows error for using max function

$student_classtest_for_sba_mark=DB::table('tbl_student_admission') 
                ->leftJoin('tbl_student_subject_mark', 'tbl_student_admission.student_id', '=', 'tbl_student_subject_mark.student_id')
                ->selectRaw('tbl_student_subject_mark.*, tbl_student_admission.student_id,  tbl_student_admission.student_full_name_english, tbl_student_admission.class, tbl_student_admission.section, tbl_student_admission.roll_no, sum(total_obtained_mark) as total_mark, sum(grade_point) as total_gread_point,
                max(if(tbl_student_subject_mark.exam_title = "'.$exam_list[0]->exam_id.'" , total_obtained_mark, null)) E1,                                               
                max(if(tbl_student_subject_mark.result_status = "Fail" , result_status, null)) result_status')                
                ->where('tbl_student_subject_mark.academic_year', $academic_year)
                ->where('tbl_student_admission.class', $class)                
                ->where('tbl_student_admission.section', $section)                
                ->where('tbl_student_subject_mark.subject_name', $subject_name)
                ->groupBy('tbl_student_admission.student_id')
                ->get(); 

Display the Error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'db_smsfinal1user.tbl_student_subject_mark.student_subject_mark_id' isn't in GROUP BY



via Chebli Mohamed

samedi 29 septembre 2018

Images are not loading after Transferred Laravel Website on server

I have transferred website from local to web server, mean while i changed some scenarios.

1- I have changed folder structure and moved public folder files on root.

2- Image files are being uploaded into store folder while symbolic storage folder is moved on root also.

But after moving public folder files on root images not working. while uploaded images are being stored into main storage folder. but not linked with symbolic storage folder. so help me how can i attach again both storage folders.

Storage folder related code into config/filesystem is shown below:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/pulic/images/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_KEY'),
        'secret' => env('AWS_SECRET'),
        'region' => env('AWS_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

],

main storage folder path is:

Root/Laravel_files/storage/app/public/images

while symbolic storage folder address is:

Root/storage/images



via Chebli Mohamed

jeudi 27 septembre 2018

Laravel: Why does eager loading only keep results for last model?

If I execute the following:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9])
                    ->get();

Then I get the following result:

Illuminate\Database\Eloquent\Collection {#1104
 all: [
   App\Assignment {#1112
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#986
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#945
         all: [
           App\Record {#853
             id: 6624,
             unit_id: 6,
             process_date: "2017-09-19",
             process_hour: 14,
           },
         ],
       },
     },
   },
 ],
}

Note how the loaded unit has a record that matches the query.

Now, if I use the exact same query but add another assignment (49) to my whereIn array:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9,49])
                    ->get();

The record for assignment 49 is shown, but the record for assignment 9 does not show up anymore:

Illuminate\Database\Eloquent\Collection {#1032
 all: [
   App\Assignment {#1014
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#1283
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#1254
         all: [],
       },
     },
   },
   App\Assignment {#1061
     id: 49,
     unit_id: 29,
     start_date: "2017-02-24",
     end_date: "9999-12-31",
     unit: App\Unit {#1279
       id: 29,
       records: Illuminate\Database\Eloquent\Collection {#1131
         all: [
           App\Record {#1284
             id: 6062,
             unit_id: 29,
             process_date: "2017-03-10",
             process_hour: 13,
           },
         ],
       },
     },
   },
 ],
}

The record that matches the criteria for assignment 9 obviously exists, but for some reason it doesn't get loaded when the query finds more than one assignment with a unit/record that matches the criteria.

I tested this with more assignments as well, and in each case the record will only show up for the last assignment in the array.

What's the deal here?



via Chebli Mohamed

mercredi 26 septembre 2018

Laravel-echo socket polling failed

I trying to implement socket connection in my laravel5.1 web application My web app running in docker containers.

I have setup laravel-echo-server using [kylestev/laravel-echo-server][1], and its running as expected

enter image description here

import Echo from "laravel-echo"
window.io = require('socket.io-client');

if (typeof io !== 'undefined') {
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001',
    });
}

window.Echo.channel('test-event')
    .listen('Eventname', (e) => {
        console.log(e);
});

when i load the page in browser the polling request failing with EMPTY_RESPONSE error.

enter image description here

    {
    "authHost": null,
    "authEndpoint": null,
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "redis"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "hms.zuzurooms.local",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}



via Chebli Mohamed

dimanche 23 septembre 2018

why i am getting No query results for model in laravel?

When i search by city name which is available in my database table it will show the result but when i search by unknown city which is not available in my database table it says -No query results for model [App\City]. i am sharing you the code and screenshot see error screenshot actually i want to redirect to 401 page if the city is not found in my database table

Here is my route

Route::get('teacher-jobs-by-city/{city}','TeacherJobsController@by_location');

Here is my function

public function by_location($location_id='') {

$data= array();
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
$items= Subject::orderBy('id','asc')->get();
$data['location']=$location;

      //$subjects = [''=>'Select Subject'] + Subject::lists('subject_title','id')->toArray();
      //$city = [''=>'Select City'] + City::lists('name','id')->toArray();
        $active_class ='Select Subject to see job Openings';
        return view('frontend.teacherjobs.by_location',compact('active_class','data','items'));

    }



via Chebli Mohamed

samedi 22 septembre 2018

Laravel: Sorting Polymophic Relations

REQUIREMENTS

  1. In the Student Controller, the results must be sorted by student name.

  2. The results must be sorted by student's guardian name.



TABLE STRUCTURE

  • taxonomies

    • id
    • entity_type - It contains the class name of the owning model.
    • entity_id - It contains the ID value of the student.
  • students

    • id
    • name
  • guardians

    • id
    • student_id
    • name



CONTROLLER

  • StudentController.php

    public function getStudents()
    {
        return Taxonomy::with([
                'entity', 
                'entity.guardian'
            ])
            ->where('entity_type', 'Student')
            ->get();
    }
    
    



MODEL

  • Taxonomy.php

    public function entity()
    {
        return $this->morphTo();
    }
    
    
  • Student.php

    public function taxonomies()
    {
        return $this->morphMany('App\Taxonomy', 'entity');
    }
    
    public function guardian()
    {
        return $this->hasOne('App\Guardian');
    }
    
    
  • Guardian.php

    public function student()
    {
        return $this->belongsTo('App\Student');
    }
    
    


via Chebli Mohamed

jeudi 20 septembre 2018

Auth.password class is not found

Laravel version: 5.1

This is a project which started in L4.2. I upgraded it to L5.1 and I am trying to fix issues. The app has its own password reset functionality which utilizes laravel reset() function.

I am trying to call Password::reset() but I am getting the error of password reset class is not found. I have the Illuminate\Auth\Passwords\PasswordResetServiceProvider::class and alias password registered in config app file but I am still getting the error auth.password class not found.



via Chebli Mohamed

dimanche 16 septembre 2018

Access user via Authorizer in model definition

In Laravel 5.1 with OAuth2, I want to eager load a model, but place query params (from user model) on the eager loaded model. The easiest way I thought to do this was directly on the model.

More specifically, Activity belongsTo Task. I only want to load activities for the task where they match certain criteria on the user object. Using OAuth2, I attempt to find the user via Authorizer, then access its properties. The route is wrapped in Lucadegasperi's middleware

$router->group(['middleware' => 'oauth'], function(Router $router) {
       $router->get('tasks/{task}', 'Resources\Tasks@show');

And the request header seems to pass along the bearer token just fine.

I'm able to access the user via Authorizer within the controller, but not in the model definition. Why is this?

I'm getting error:

NoActiveAccessTokenException in Authorizer.php line 104: Tried to access session data without an active access token

use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use App\User;

class Task extends BaseModel
{
    protected $with = ['activities'];

    public function activities()
    {
        $user = User::find(Authorizer::getResourceOwnerId());
        return $this->hasMany(Activity::class)->where('id', '=', $user->...);
    }



via Chebli Mohamed

samedi 15 septembre 2018

how to make db in laravel using mysql for multiple users, like in my case Admin, Users, Agents, International Agents

i want to design a db for my project in laravel but confused how to manage tables. I have four entities Admin, Users, Agents and International Agents. Please help me how i manage my db tables. and if i make single table for multiple users then how to identify users. Note: Each of the mentioned entities are different. Please ask if it not sounds clear. Thanks



via Chebli Mohamed

Laravel Problem credentials do not match our records

First of all Sorry for my bad english.

I am new to laravel. I have recently run into some problems with authentication/login system which comes built-in in laravel by the command make:auth.

The registration process is working correctly and after that it logs me in automatically. but when I log out and try to log back in, I get this error:

These credentials do not match our records.

I'm not sure whats wrong! but i tried to search error on google stack overflow and etc. The solution i found is this. These credentials do not match our records, laravel 5.2 but it also didn't work.

This is my code.

Http/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;


class LoginController extends Controller
{

    use AuthenticatesUsers;


    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }


}

This is model

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'user_name', 'email','user_password','user_created_by',
    ];

    protected $hidden = [
        'user_password', 'remember_token',
    ];

    protected $primaryKey = 'user_id';

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

This is View

Views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="">
                        

                        <div class="form-group">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" > Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

This is User Table

User Table



via Chebli Mohamed

vendredi 14 septembre 2018

Hide row when result of spesific column is null in Datatable Jquery automatically?

i want to ask about how to hide one row, in example one row contain 10 columns, the first and second column is filled with right value, but third until end value is null, i want to hide the row that have the condition like that. i've tried to make filter before its rendered but not work, please help. This is my code

oTable = $('#data').DataTable({
   "ordering":true,
   "columns": [
   {data: 'no', name: 'no'},
   {data: 'number', name: 'number'},
   {data: 'action', name: 'action'},
   {data: 'status', name: 'status'},],});
   //Used For Call Data (AJAX)

<table id="data" class="table table-striped table-bordered display" style="width: 100%; overflow-x: scroll" >
  <thead>
  <tr>
    <th style="width: 25px">No</th>
    <th>No</th>
    <th>Action<br></th>
    <th>Current Status</th>
  </tr>
 //Used to make table

Thank you. Any idea and help will much appreciated



via Chebli Mohamed

jeudi 13 septembre 2018

How to sotre an id from a collection on to another collection of MongoDB in Laravel

I have two Collection category and subcategory. One category can have 0 or more subcategories that's why i need relation between them how can i store _id oa document form category collection to subcategory collection's document.

category

{
    "_id" : ObjectId("5b8abe366a44fa2d080065d2"),
    "Title" : "Aptitude",
    "Description" : "Aptitude",
    "Slug" : "aptitude",
    "updated_at" : ISODate("2018-09-01T16:28:38Z"),
    "created_at" : ISODate("2018-09-01T16:28:38Z")
 }

subcategory

{
    "_id" : ObjectId("5b9abbd06a44fa207c001674"),
    "Title" : "Aithmatic Apptitude",
    "Description" : "Aithmatic Apptitude",
    "Slug" : "arithmatic_aptitude",
    "CategoryId" : "5b8abe366a44fa2d080065d2",
    "updated_at" : ISODate("2018-09-13T19:34:40Z"),
    "created_at" : ISODate("2018-09-13T19:34:40Z")
}
{
    "_id" : ObjectId("5b9ac7e86a44fa207c001678"),
    "Title" : "Reasoning",
    "Description" : "Reasoning",
    "Slug" : "reasoning",
    "CategoryId" : "5b8abe366a44fa2d080065d2",
    "updated_at" : ISODate("2018-09-13T20:26:16Z"),
    "created_at" : ISODate("2018-09-13T20:26:16Z")
}

As you can see i am storing the category_id on subcategory collection a string "CategoryId" : "5b8abe366a44fa2d080065d2",

Here is my code for storing

$subcategory = Subcategory::create(
    [
        'Title' => $request->Title, 
        'Description' => $request->Description,
        'Slug' => $request->Slug,
        'CategoryId' =>  $request->CategoryId,
    ]

);

Want to sore it like actual reference"category_id" ObjectId("5b8abe366a44fa2d080065d2") . convert this command db.subcategory.insert({Title:"Example",Description:"Example", Slug:"Example",CategoryId:db.category.find({_id:"5b9abc8cb3562ec4e990ec5b"})._id}) how can it be possible, Please help



via Chebli Mohamed

Whan to Show some data On my view but there is a Error In Laravel

Here I am trying to add, Add Comment feature and it's causing a problem to show data.

public function store(Request $request)
{
    $chatterreply =  new Chatterreply;
    $chatterreply->reply = $request->body;
    $chatterreply->chatter_post_id = $request->chatter_post_id;
    $chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
    $chatterreply->save();
    $chatterreplies = Chatterreply::where('chatter_post_id',$request->chatter_post_id)->get();
     $chatter_editor = config('chatter.editor');

    if ($chatter_editor == 'simplemde') {
        // Dynamically register markdown service provider
        \App::register('GrahamCampbell\Markdown\MarkdownServiceProvider');
    }
    echo "<pre>"; print_r($chatterreplies); die;
    return view('chatter::discussion', compact('chatterreplies','chatter_editor'))->with('chatter_alert','Add Comment Successfully');

}

And Here Is Where I am passing the variable

 $chatter = session()->pull('chatter');
            return view('chatter::discussion', compact('discussion', 'posts', 'chatter_editor'))->with('chatterreplies',$chatter);



via Chebli Mohamed

How to prevent the main Laravel form to submit?

I have 1 main form. I also have a sub form inside that main form.

I can't seem to prevent the main form to stop submitting since the button type submit will submit the main form automatically.

That is my entire form

enter image description here

My subform is my delete of each image

enter image description here

edit.blade.php

@extends('layouts.be.master')
@section('content')

<script type="text/javascript" src="/js/ckeditor.js"></script>
<link rel="stylesheet" type="text/css" href="http://d.biossusa.com/css/root/hover-master/hover.css">

<style type="text/css">
.portfolio-images {
    border: solid 1px silver;
}

._hover{
    padding: 0px;
    position: relative;
    overflow: hidden;
    border: 1px solid #D8D8D8;
    /*border-radius: 10px;*/
}
._hover:hover .caption{
    opacity: 1;
    transform: translateY(-150px);
    -webkit-transform:translateY(-150px);
    -moz-transform:translateY(-150px);
    -ms-transform:translateY(-150px);
    -o-transform:translateY(-150px);
}
._hover img{
    z-index: 4;
}
._hover .caption{
    position: absolute;
    top:150px;
    -webkit-transition:all 0.3s ease-in-out;
    -moz-transition:all 0.3s ease-in-out;
    -o-transition:all 0.3s ease-in-out;
    -ms-transition:all 0.3s ease-in-out;
    transition:all 0.3s ease-in-out;
    width: 100%;
}
._hover .blur{
    background-color: rgba(0,0,0,0.8);
    height: 300px;
    z-index: 5;
    position: absolute;
    width: 100%;
}
._hover .caption-text{
    z-index: 10;
    color: #fff;
    position: absolute;
    height: 300px;
    text-align: center;
    top:-20px;
    width: 100%;

}
</style>


<?php $tags = explode(",", $portfolio->tag ); ?>

<div class="card-body card-padding">
    <div class="row">

        {!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'portfolio/'. $portfolio->id .'/update','files' => true)) !!}


        <div class="col-sm-12">

            
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-10">
                    <input type="text" value="" name="name" class="form-control" id="name" placeholder="Name">
                </div>
            </div>

            
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">Type</label>
                <div class="col-sm-10">
                    <select name="type" class="form-control">
                      @foreach($portfolioTypes as $item)
                      <option value=""></option>
                      @endforeach
                  </select>
              </div>
          </div>


          
          <div class="form-group">
            <label for="email" class="col-sm-2 control-label">Tags</label>
            <div class="col-sm-10">

            </div>

            <input id="tags" name="tag">
        </div>

        
        <div class="form-group">
            <label for="url" class="col-sm-2 control-label">URL</label>
            <div class="col-sm-10">
                <input name="url" type="text" value="" class="form-control" placeholder="URL">
            </div>
        </div>


        


        <div class="form-group">

            <label for="email" class="col-sm-2 control-label">Images</label>


            @foreach($images as $image)

                <?php

                $crop_img = str_replace('full.jpg','crop.jpg',$image->img_path);

                ?>


                <div class="col-sm-2">

                    <div class="_hover " style="background: transparent;">
                        <p style="text-align:center;">
                            <img class="img-responsive" src="" alt="">
                        </p>
                        <div class="caption">
                            <div class="blur"></div>
                            <div class="caption-text">
                                <h6 class="title lighter" style="padding:5px;border-radius: 10px;">
                                    
                                </h6>
                                <p>
                                    <span>
                                        <a data-toggle="modal"  data-target="#delete_image_">
                                            delete
                                        </a>
                                    </span>

                                </p>

                            </div>
                        </div>
                    </div>
                </div>


                <div class="modal fade" id="delete_image_">
                    <div class="model-content" style="margin-top: 200px;">
                        <div class="col-sm-offset-4 col-sm-4 ">

                        {!! Form::model($image, array( 'url' => '/portfolio/image/'.$image->id.'/destroy','method' => 'DELETE')) !!}

                            <button type="submit" class="btn btn-danger btn-lg btn-block">Delete ()</button>
                          <a class="btn btn-primary btn-lg btn-block" data-dismiss="modal" > Cancel </a>

                        {!! Form::hidden('$id', $image->id)!!}
                        {!! Form::close()!!}
                        </div>
                    </div>
                </div>



            @endforeach

            <br><br>

            <input id="images" name="images[]" type="file"  multiple>

        </div>

        
        <div class="form-group">

            <label for="email" class="col-sm-2 control-label">Description</label>
            <div class="col-sm-10">

                <textarea name="description" rows="20" cols="80" id="description">
                    
                </textarea>
                <script>
                    CKEDITOR.replace( 'description' );
                </script>

            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-8">
                <a class="btn btn-default" href="/portfolio"> Cancel </a>
                <button type="submit" class="btn btn-info">Done</button>
            </div>
        </div>

        </div>

        {!!Form::close()!!}


    </div>
</div>


@stop

@section('custom-scripts')

<link rel="stylesheet" type="text/css" href="/css/jquery.tag-editor.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

<script type="text/javascript" src="/js/jquery.caret.min.js"></script>
<script type="text/javascript" src="/js/jquery.tag-editor.js"></script>

<script type="text/javascript">
    $( "select[name*='type']" ).val("");

    function readLogo(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#portfolio-icon').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $( "input[name*='logo_path']" ).change(function(){
        readLogo(this);
    });


    $('#tags').tagEditor({

        autocomplete: {
            delay: 0,
            position: { collision: 'flip' },
            source: [<?php echo '"'.implode('","', $skillList).'"' ?>]
        },
        forceLowercase: false,
        delimiter: ',', /* space and comma */
        placeholder: 'Enter tags ...',
        initialTags: [<?php echo '"'.implode('","', $tags).'"' ?>]

    });

</script>
@stop



Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed