mardi 29 novembre 2016

Upload file in S3 using Laravel 5.3

Installation Process

I followed this tutorial to install aws Package in Laravel 5.3

My Code is below

$s3 = \App::make('aws')->createClient('s3');

$s3->putObject(array(
    'Bucket'     => 'Bucket_Name',
    'Key'        => 'AWS_ACCESS_KEY_ID',
    'SourceFile' => 'http://domainname/sample.txt',
));

I am trying a txt file with around 50 bytes contents and got below error.

A sha256 checksum could not be calculated for the provided upload body, because it was not seekable. To prevent this error you can either 1) include the ContentMD5 or ContentSHA256 parameters with your request, 2) use a seekable stream for the body, or 3) wrap the non-seekable stream in a GuzzleHttp\Psr7\CachingStream object. You should be careful though and remember that the CachingStream utilizes PHP temp streams. This means that the stream will be temporarily stored on the local disk.

Am I missing something?



via Chebli Mohamed

lundi 28 novembre 2016

Phpunit overriding variable in .env

In my .env file of a laravel 5.1 project i have set the APP_ENV to local, But when i run the test from the terminal the with

vendor/bin/phpunit

the debug and die on

dd(env(APP_ENV));

gives me "testing".

I Have dont a good research on this, tried using the following ways -

  • trying to set the APP_ENV=local pipelining vendor/bin/phpunit form the cli.
  • Trying to add env variable in the phpunit.xml file<env name="APP_ENV" value="local" override="true"> (dosent seem to override though)
  • adding a .env.testing file and setting the APP_ENV=local
  • in the testCase.php file where the application autoloads $app->loadEnvironmentFrom('.env.testing');

none of the above methods give me the expected result rather everytime i run the test give APP_ENV as "testing".

Not able to trace where is phpunit setting this variable from. Pls help out!



via Chebli Mohamed

how can i retrieve username from another collection by using join in laravel

//viewing tickets generated by them $user= Auth::user()->_id; $tickets = ticket::where(function ($query) use ($user) { $query->where('user', '=', $user); })->get();

  //  created ticket by which user
    $atickets = ticket::where(function ($query) use ($user) {
        $query->where('user_assigned', '=', $user);
    })->get();


    return view('ticketviews', compact('tickets','atickets'));

$atickets returns record details such as user_id and ticket details, now i need to display the username for that particular record stored in another collection mongodb. Can anyone suggest me the code to do that.



via Chebli Mohamed

dimanche 27 novembre 2016

Failing to install Laravel/Homestead with VirtualBox via Vagrant

I'm trying to install Laravel / Homestead with VirtualBox via Vagrant. I followed step by step the installation guide but I keep getting this error:

The box 'laravel/homestead' could not be found or
could not be accessed in the remote catalog. If this is a private
box on HashiCorp's Atlas, please verify you're logged in via
`vagrant login`. Also, please double-check the name. The expanded
URL and error message are shown below:

URL: ["http://ift.tt/1KBs0RO"]

I checked that I use latest version of Vagrant(1.8.7).



via Chebli Mohamed

samedi 26 novembre 2016

Passing data from view to controller in Laravel 5.1

i want to pass arguments from a blade view to a function in the controller

index.blade.php

<a href="" class="like">
    Like
</a>

<a href="" class="like">
    Dislike
</a>

PostController.php

  public function getLikePost($post_id, $like_value)
    {
       $post = Post::find($post_id);
       ...
    }

routes.php

Route::get('like', [
        'uses' => 'PostController@getLikePost',
        'as'   => 'like'
      ]);

but i get an error message

ErrorException in PostController.php line 149:
Missing argument 2 for App\Http\Controllers\PostController::getLikePost()

could anyone help me with this issue?



via Chebli Mohamed

Laravel, Image get from storage display correctly but console return status code 404

I'm having this problem where by image get from storage shows in page correctly but console shows status code 404 as shown in the image belowenter image description here



via Chebli Mohamed

Nearby stores in Laravel

i'm try to get neraby store in Laravel 5.1 I have geocoding parser that caluclate coorinate. But i have problem with haversine formulas. Basically i need that from table Aziende (Stores) given a lat, long e category passed trough url, fetch the nearby stores.

I try with this code:

$dove = Input::get('dove');
    $categoria_id = Input::get('id_categoria');
    // 4: check if any matches found in the database table 
    if (!empty($dove)) {
        $response = \GoogleMaps::load('geocoding')->setParamByKey ('address', $dove)->get();
        $response = json_decode($response, true);
        $latitude = $response['results'][0]['geometry']['location']['lat'];
        $longitude = $response['results'][0]['geometry']['location']['lng'];
        $radius = '5';
        $aziende  = DB::table('aziende')
            ->select(
                 ( 'lat * acos( cos( radians(50) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )
                       + sin( radians(37) ) * sin( radians( lat ) ) ) as distance') )->get();




    } else {
    $aziende = DB::table("aziende")->where('categoria', $categoria_id)->get();
 }
 ?>



via Chebli Mohamed

Laravel - group data by created_at field and apply pagination

I need to get previous 10 days activity of a user. In my case i am just getting 10 activity records instead of previous 10 days activity.

*My Code:

$activity   = $this->where('user_id', '=', $userId)->paginate(10);

$activities = collect($activity->items())->groupBy(function($item) {
    return \Carbon\Carbon::parse($item->created_at)->format('d-M-Y');
});

$activity->setCollection($activities);

dd($activity->toArray());

Output:

enter image description here



via Chebli Mohamed

vendredi 25 novembre 2016

Laravel CkEDITOR AND TINYMCE content not post in form issue

I have Laravel 5.1 website developed my domain is http://example.ca I have issue with form submit. I have ck editor integrated in my form if i remove ck editor then form can be submit on correct page if i keep ck editor then form is redirecting on index page. I am sure that issue is because of .ca in domain because in other domains(.com,.in etc...) form works perfect.

I have tried many option but not success i appreciate your help. Thank you



via Chebli Mohamed

How to send Emails in Laravel without using 3rd party tools

I want to send email in laravel without using the 3rd party tool like sendgrid,gmail etc.

I have gone through the various links in forum and google but nothing is upto the mark.

http://ift.tt/2d3DtgC

Can anyone help me out or providing steps to resolve the issue.

Thanks



via Chebli Mohamed

jeudi 24 novembre 2016

Apache 500 error with code 732

I've developed my website and RESTful APIs. Few weeks ago everything was working fine then I found a strange error on my VPS. See the screenshot below:

500 Internal Server Error with code# 732

I'm using:

  • CentOS 6.5
  • Apache 2.2.x
  • PHP 5.6.x with FastCGI
  • Laravel 5.1

The error shows up eventually (not every time), I checked all server logs including Apache access_log.log, error_log.log and domlogs. There was no information about the error.

I also tried to find the issue with top c command and all server resources were free at the time of error. The server was at idle state.

Any help would be great.

Thanks



via Chebli Mohamed

mercredi 23 novembre 2016

Cant mock Cache::rememberForever

using the following code

Cache::shouldReceive('rememberForever')

Gives

Mockery_1_Illuminate_Cache_CacheManager::rememberForever() does not exist on this mock object

The call works (something is cached) but just cant test it.

The others seem ok Cache::get for example

How should this be mocked ?



via Chebli Mohamed

mardi 22 novembre 2016

Laravel 5.1 Logger Timezone

Is there a way I can change the timezone for the Laravel 5.1 logger? I've seen previous discussions where they extended the Monolog class and updated the Service Provider, but that was for an older version of Laravel and it doesn't look like the LogServiceProvider is used anymore.

I see there's a timezone key in the app.php file, but I don't want the whole system to change. I just want to update the timezone for the logs, and keep the rest of the system in UTC.



via Chebli Mohamed

laravel print results to html

i make this style: http://ift.tt/2f3Z8uM

now i need to insert to this html:

   <div class="trading-info">
  <div class="row" data-sameparent="1">
    <div class="col-4">
      <a href="#" class="info-box large" data-samecol="1">
        <div class="holder">
          <h2>Forex trading</h2>
          <h3>LESSON 1</h3>
          <span class="icon-play block"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <div class="row" data-sameparent="true" data-samecol="1">
        <div class="col-6">
          <a href="#" class="info-box small" data-samecol="true">
            <div class="holder">
              <h2>Stocks trading</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6">
          <a href="#" class="info-box small" data-samecol="true">
            <div class="holder">
              <h2>CFD’S trading</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6 locked">
          <a href="#" class="info-box small lightbox-open" data-samecol="true">
            <div class="holder">
              <h2>Forex trading strategies</h2>
              <h3>LESSON 1</h3>
              <span class="icon-lock small"><img src="images/icon8.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-6 locked">
          <a href="#" class="info-box small lightbox-open" data-samecol="true">
            <div class="holder">
              <h2>Airsoft trading platform</h2>
              <h3>LESSON 1</h3>
              <span class="icon-lock small"><img src="images/icon8.png" alt="play"></span>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="row" data-sameparent="true">
    <div class="col-4">
      <a href="#" class="info-box" data-samecol="true">
        <div class="holder">
          <h2>Social trading </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <a href="#" class="info-box alt" data-samecol="true">
        <div class="holder">
          <h2>Psychology of trading </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play block"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
  </div>
  <div class="row" data-sameparent="1">
    <div class="col-4">
      <a href="#" class="info-box" data-samecol="1">
        <div class="holder">
          <h2>Sirix &amp; BX8 trading platforms </h2>
          <h3>LESSON 1</h3>
          <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
        </div>
      </a>
    </div>
    <div class="col-8">
      <div class="row" data-sameparent="true" data-samecol="1">
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Techfinancials trading platform</h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Market <br> analysis </h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
        <div class="col-4 no-padding">
          <a href="#" class="info-box" data-samecol="true">
            <div class="holder">
              <h2>Binary Options Trading </h2>
              <h3>LESSON 1</h3>
              <span class="icon-play small"><img src="images/icon7.png" alt="play"></span>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

the result from the SQL i have there: title, number lessons.

how i can do it? i have different codes in every row and col tags.

im use laravel framework version 5.1



via Chebli Mohamed

Laravel 5.1 - Session regenerate every refresh

I run a laravel app, and storing the session on redis. Every time I refresh the page - a new session is generated (I can see it using keys *) and the cookie of the session also changes accordingly.

  • I checked the cookie's expiration date, and it's a valid future date.
  • I run this on my localhost with php -S, and also on a CentOS server, the problem exists in both of them.

My 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', 'file'),

    /*
    |--------------------------------------------------------------------------
    | 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' => '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,

];

on .env,SESSION_DRIVER=redis



via Chebli Mohamed

Trying to get property of non-object laravel 5.1 on DB::first()

I'm using Laravel 5.1 on a project, and I'm getting "Trying to get property of non-object" error on this code:

$eval = DB::table('control_eval_risk_temp')
                        ->where('control_id','=',$control->id)
                        ->where('created_at','=',$max_date)
                        ->select('result')
                        ->first();
if ($eval->result  == 1)
{
     $cont += 1;
}

I have this error specifically on the "if sentence", but if I try this:

echo getType($eval);

That returns "object", and if I try:

echo $eval->result;

This returns 1 (so it have a value), and after return the message "Trying to get property of non-object", so I don't understand where is the mistake since the var $eval is an object and $eval->result have a value.

Thank's in advance!.



via Chebli Mohamed

Laravel - Using `SQL_CALC_FOUND_ROWS` with relationship

In my Laravel app I was doing an ordinary query on a model (ModelA) whilst making use of SQL_CALC_FOUND_ROWS and then performing SELECT FOUND_ROWS() afterwards to retrieve the count of all records since the first query used LIMIT and OFFSET.

This worked perfectly fine, but now that I've added a relationship to the model I was querying above, if I do the same query but using with->('modelB'), this query is performed after the initial query and before SELECT FOUND_ROWS() so I get the count of the ModelB results instead of ModelA as I was expecting.

Is there a way to make this work as desired where I get the count of the first query and not the relationship?

e.g. This works fine:

$query = ModelA::select([DB::raw("SQL_CALC_FOUND_ROWS *")])
    ->where('active', 1);

    // conditional ->where()'s

$query->skip(intval($skip))
    ->take(intval($take))
    ->orderBy($column, $dir);

$results = $query->get();

$total = DB::select(DB::raw("SELECT FOUND_ROWS() AS 'total';"))[0]->total;

but changing the first line to this doesn't:

$query = ModelA::with('modelB')
    ->select([DB::raw("SQL_CALC_FOUND_ROWS *")])
    ->where('active', 1);



via Chebli Mohamed

lundi 21 novembre 2016

How to pass PHP variable into Laravel DB::unprepared query

working with Laravel 5.1. I have this query below. It works fine in phpMyAdmin. It will also work if I hard code the $category and the $value. But no number of concatenations and / or escaping of the variables gets the query to run in my controller. I am using use Illuminate\Support\Facades\DB; I have tried encapsulating the query with single quotes and double quotes, to no effect. I am using PHPStorm and it even says the query is correct, but it is not. What am I doing wrong ??

public function addNode(Request $request)
{

$category = $request->input('parent_category');
$value = $request->input('new_category');


$result = DB::unprepared("
LOCK TABLE nested_categories WRITE;
SELECT @myLeft := lft FROM nested_categories
WHERE name =  '.\'$category\'.';
UPDATE nested_categories SET rgt = rgt + 2 WHERE rgt > @myLeft;
UPDATE nested_categories SET lft = lft + 2 WHERE lft > @myLeft;
INSERT INTO nested_categories(name, lft, rgt) VALUES( '.\'$value\'.', @myLeft + 1, @myLeft + 2);
UNLOCK TABLES;");

return redirect('nested_categories');
}

TKS !!



via Chebli Mohamed

missing images and home page when moving laravel 5.2 project to live server

images works fine in localhost as src="/lr/public/bootstrap/images/photo.jpg" but don't work on live server

error messages on live server is failed 404 not found http://ift.tt/2ffkQXK

note : when i remove /lr/public images works on live server

my cpanel root directory is /home/ad

in /home/ad >> i have folder'lr' that containe my project and i deleted folder public in it

in public_html >> i have contents of folder public >> bootstrap - uploads - index.php ..... etc

second prob

when i try access www.mysite.com it show my 404 page

but when i try access www.mysite.com/home it works fine and show my home page

i want when access www.mysite.com show home page directly

my public_html/index.php

require __DIR__.'/../lr/bootstrap/autoload.php';
$app = require_once __DIR__.'/../lr/bootstrap/app.php';



via Chebli Mohamed

dimanche 20 novembre 2016

App Domain when using localhost for facebook authentication laravel 5.1

hello so im using socialite in laravel 5.1 and using it in localhost still and in also using xampp. When i click the login button i created it has an error just like this enter image description here

do i have to change the settings in my facebook dev settings? right now it looks like this enter image description here

do i need to have changes on this? on my .env file

FACEBOOK_CLIENT_ID=xxxxx
FACEBOOK_CLIENT_SECRET=xxxxxxx
CALLBACK_URL=http://localhost/<my projectname>/public/auth/facebook/callback

any ideas what im doing wrong? thanks in advance



via Chebli Mohamed

Trying to render Anchor using Blade and Angular Js

I am using Angular Js with Blade and Laravel 5.3.15

Code in Blade.



Code in Route.

Route::get('/', function() {                    
    return view('Account.Login');
});

When i check the output in web page, it displays the code which I wrote in Blade. i.e

I am trying to render Anchor tag, Am I missing something?



via Chebli Mohamed

facebook authentication using laravel 5.1 socialize

hello im using localhost so i have recently switched to laravel 5.1 and im trying to use 'socialite' it provides so i have updated my config , services and the .env files so in my routes i also added these codes

Route::get('/', function () {
return view('welcome');
 });
 Route::get('auth/facebook', 'Auth\AuthController@redirectToProvider');
 Route::get('auth/facebook/callback','Auth\AuthController@handleProviderCallback');
Route::get('home', array('as' => 'home', 'uses' => function(){
return view('home');
}));

then in my AuthController i have these codes enter image description here

in my view the button 'login with facebook' has the href of auth/facebook but what happens is facebook is giving me an error saying enter image description here

im still confused on where my error is. any idea what im doing wrong? thanks for advices.



via Chebli Mohamed

Laravel - Failed oci8 connection to Oracle 10g database but success with 11g

I have a laravel 5.1 which use Oracle Instant Client 11.2 and Using yajra/laravel-oci8 to connection to Oracle Server. My development work fine with Oracle 11g .

But we when try to connect to production serve which is oracle 10g. It failed. When I use Oracle SQL Developer application, I can connect to both database. So now I cannot migrate my application to production.

The error from laravel is ORA-12505: TNS:listener does not currently know of SID given in connect descriptor

Appreciate any suggestion



via Chebli Mohamed

Online Chat - Approach to keep History

I am working on Online Chat first time in Hire and Work Website where Employer will post project, it's a kind of getting work done from Freelancer. I am told to keep Chat history also. So far I though to keep it using below two approaches.

  1. Save Messages in Database
  2. Save Messages in Xml file

Below were the reasons for keeping things in XML.

  1. There will be always 1-1 chat.
  2. Get rid of millions of messages in single Database Table. It may cause performance issue to load filtered data from millions of records.
  3. Each time an Employer will do discussion for their new Project. So previous chat will have nothing to do with old project.

Am I doing it correctly? or there could be another approach also?



via Chebli Mohamed

samedi 19 novembre 2016

SQLSTATE[42S22]: Column not found: 1054 Unknown column laravel 5.1

I have this QueryException

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into `comentarios` (`NombreUsuario`, `CorreoUsuario`, `TelefonoUsuario`, `Asunto`, `Mensaje`, `FecComentario`, `updated_at`, `created_at`) values (Andres, poc@dw.xom, 124422432, Andres es genial, vffgdf, 2016-11-20 03:34:45, 2016-11-20 03:44:18, 2016-11-20 03:44:18))

and this is my sql for laravel 5.1

public function store(Request $request)
    {

        \JuanSapo\ContadorT::create([
            'NombreUsuario' => $request['nombres'],
            'CorreoUsuario' => $request['email'],
            'TelefonoUsuario' => $request['numContacto'],
            'Asunto' => $request['asunto'],
            'Mensaje' => $request['mensaje'],
            'FecComentario' => $request['fecha']

            ]);

            return view('contacto');
    }

i can see, i have two dates more just in the end and this look on my sql's mistake,

This is my auth.php

<?php

return [

    'driver' => 'eloquent',

    'model' => JuanSapo\User::class,
    'model' => JuanSapo\ContadorT::class,

    'table' => 'users',
    'table' => 'comentarios',

    'password' => [
        'email'  => 'emails.password',
        'table'  => 'password_resets',
        'expire' => 60,
    ],

];

this is my User.php

<?php

namespace JuanSapo;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];
}

This is my contadotT.php

<?php

namespace JuanSapo;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class ContadorT extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;


    protected $table = 'comentarios';

    protected $fillable = ['NombreUsuario', 'CorreoUsuario', 'TelefonoUsuario','Asunto','Mensaje','FecComentario'];

    protected $hidden = ['contador'];
}



via Chebli Mohamed

syntax error, unexpected '}' in Anchor Laravel

My Anchor Tag is like below

<a href="">Login</a>

I tried to change it to Laravel like below

", 'log in')}}

It says syntax error, unexpected '}'

Am I missing something?



via Chebli Mohamed

vendredi 18 novembre 2016

View [errors.404] not found

I am opening a page which is not present in my application and in order to get rid of 404 error, I wrote below code.

public function report(Exception $exception)
{
    if($this->isHttpException($exception)) {
        switch ($exception->getStatusCode()) {
            case '404':
                return \Response::view('errors.404');
        }
    }
    parent::report($exception);
}

Directory structure is like below and you could see there is 404 Blade inside errors directory

My Directory Structure here. Please click it to view the details

When I run the above code, it shows below error.

View [errors.404] not found

Am I missing something?

Thank you very much in advance for any suggestion.



via Chebli Mohamed

jeudi 17 novembre 2016

Sometime Email not working using (mandrill account) laravel 5.1

I am using paid mandrill account to send mail over the internet using laravel 5.1 . It works fine while sending to gmail,yahoo accounts but problem is- sometimes it stopped sending email to domain email accounts like ledernytt.no, globdig.com sometime works fine.

I could not figure out the problem exactly, whether the problem in mail provider or on receiver side.

I am looking for long term solution, currently while rewrite the same code and works fine till next turn to be stopped.



via Chebli Mohamed

Get route list from parent route group in laravel

Here is the simple routing code: (i take it from official site just for example)

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function ()    {

    });

    Route::get('user/profile', function () {

    });
});

Is it possible to get all routes from this group programmatically? Thank you.



via Chebli Mohamed

Laravel 5.1 Searching encrypt not working for me

I'm working on this model with name field encrypted using Crypt class, i can display data into decrypted in view. but when searching for the value in the model that is encrypted. my controller returns null.

//heres my code: validator model. //validator->validate($code)

return $this->validator
            ->where('name', '=', $code)
            ->where('date_end', '>=', $dateToday)
            ->where('availability', '=' ,0)
            ->first();

//and note, im using traits for auto encryption and decryption for my model

trait Encryptable {

    public function getAttribute($key){
        $value = parent::getAttribute($key);

        if(in_array($key, $this->encryptable)){
             $value = Crypt::decrypt($value);
        }

        return $value;
    }

    public function setAttribute($key, $value)
    {
        if(in_array($key, $this->encryptable)){
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }

}

please help.



via Chebli Mohamed

Transmitting Laravel event to angularjs on the frontend?

I have a Laravel 5.1 app with Angularjs on the frontend. The app has got a single sign on interface based on Active Directory Federation service(ADFS). The ADFS login is integrated into the app using laravel-saml2 package. Whenever a ADFS login happens, the laravel-saml2 package will fire an event with the logged in user's details. This handled using an event listener and the based on the user's details, a user is manually authenticated in the app. My question is, how can I pass this event to my angularjs frontend so that the authentication happens on the frontend as well? In short, how can I pass an event from the server to the client browser?



via Chebli Mohamed

Why Laravel keeps on using .env for testing?

I am using Laravel 5.1 for my app. I am trying to create custom .env file for my testing env. I have called it .env.testing

Here are the internals:

APP_ENV=testing
APP_DEBUG=true
APP_KEY=sQy8pV7uVnVtQrL3wBIPESJXhVCYGVyE

DB_HOST=localhost
DB_DATABASE=larabor_testing
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

MAIL_DRIVER=log
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Here is my phpunit.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">app/</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_DEFAULT" value="mysql_testing"/>
    </php>
</phpunit>

Here is the database.php settings for mysql_testing:

 'mysql_testing' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'larabor_testing',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => 'zabor_t_',
        'strict'    => false,
 ],

The problem is that during the tests it still keeps on reading the normal .env file and utilizes the database from there even though I have specifed database 'larabor_testing' in both database.php and .env.testing and have set it up as default in phpunit.xml file



via Chebli Mohamed

mercredi 16 novembre 2016

Laravel Clockwork middleware dumps a ~120kb json into laravel_app/storage/clockwork on every request (196946 files and counting)

I wouldn't rise this ticket but yesterday by accident I saw that my storage/clockwork contains (fasten your seat belt):

19,490,265,152 bytes (19.92 GB on disk) for 196,946 items

Almost 197k of JSON files.

drwxr-xr-x  11 matthew  staff   374B 17 Nov 09:30 .
drwxr-xr-x   8 matthew  staff   272B 16 Nov 16:35 ..
-rw-r--r--   1 matthew  staff     7B 22 Feb  2016 .gitignore
-rw-r--r--   1 matthew  staff   109K 16 Nov 16:41 1479278489.8054.916823584.json
-rw-r--r--   1 matthew  staff   126K 16 Nov 16:41 1479278491.0863.854264907.json
-rw-r--r--   1 matthew  staff   126K 16 Nov 16:45 1479278731.1254.1964585753.json
-rw-r--r--   1 matthew  staff   126K 16 Nov 16:49 1479278959.9298.732557005.json
-rw-r--r--   1 matthew  staff   109K 17 Nov 09:28 1479338888.0561.518691365.json
-rw-r--r--   1 matthew  staff   126K 17 Nov 09:28 1479338889.3253.2010023624.json
-rw-r--r--   1 matthew  staff   109K 17 Nov 09:30 1479339012.8483.682005478.json
-rw-r--r--   1 matthew  staff   126K 17 Nov 09:30 1479339014.0917.223972419.json

The problem can be solved temporarily by calling php artisan clockwork:clean. It does clean that junk but once I will refresh the page, new JSON is being created.

Another solution is to comment the Clockwork middleware in Kernel.php

public function __construct(Application $app, Router $router)
{
    if (env('APP_ENV', 'production') === 'local') {
        // $this->prependMiddleware('Clockwork\Support\Laravel\ClockworkMiddleware'); // <--- this
    }

    parent::__construct($app, $router);
}

but that's not the way how I would like to deal with that issue. In terms of the content of those files, it looks like a dump of request, db queries etc. I assume it's useful when using Clockwork in Chrome Dev Tools to preview queries or that sort of things but shouldn't this directory be auto cleaned etc.?



via Chebli Mohamed

Paging in laravel 5.1 using stored procedure sql

could you please help me to achieve laravel pagination with the results of a stored procedure and display them in a view. I have the following code which works fine, but when I click on a page number of the paginate, I redirect to the home page:

$data = DB::select(DB::raw('EXEC CUST_MIS_EMPLEADOS ' . $condicion));

$page = \Illuminate\Support\Facades\Input::get('page', 1);
$paginate = 16;

$offSet = ($page * $paginate) - $paginate;
$itemsForCurrentPage = array_slice($data, $offSet, $paginate, true);
$data = new LengthAwarePaginator($itemsForCurrentPage, count($data), $paginate, $page);
if (count($data) > 0) {
  return view('client.activEmployees', compact('data'));      
} else {
  Session::flash('message', 'No se encontraron resultados sobre la búsqueda');
  return view('client.activEmployees', ['message' => 'Si']);
}



via Chebli Mohamed

dimanche 13 novembre 2016

Password reset in laravel 5.1

Kindly tell me how to implement the password reset functionality in my Laravel 5.1 application. I am using the JWT to give a user access to the system. Please, tell me how to implement 'forgot passsword' functionality. My web API is consumed by a mobile device and the user will follow the steps given below when a user understands that he has forgotten the password

1) In the login screen user will click 'Forgot password'

2) In the next step, the user will enter the email address and submits.

3) server side code compares the email with all the email registered within the system. If a match is found a link(self-destructing) to reset password is sent to the email address.

4) The user checks his email account to find the link and use it to reset a password.

Right now the code I have in user table is given down below

<?php

namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


     public function events()
    {
        return $this->hasMany(Event::class);
    }


      public function request()
    {
        return $this->hasOne(Request::class);
    }



}



via Chebli Mohamed

vendredi 11 novembre 2016

Laravel 5.3 Broadcast using Laravel Echo via Pusher using Models Creating, Saving Etc events

Is there a way to implement this

as documented in this link Event of Models

How can i extend those events to fire broadcast pusher data, rather than making separate events for the model



via Chebli Mohamed

How to know cron job status?

I'm running cron jobs using laravel daily in that i'm sending messages to every client using clickatell api and saving the message status in the database. Here i want to get email when cron job started how many messages are sent, how many are pending and how many are failed.

Iam running my cron jobs like below

protected function schedule(Schedule $schedule)
{       
    $path = public_path().'/cron-jobs/jobs.php';         
    $schedule->command('sms:note')->cron('0 8,16 * * *')->sendOutputTo($path);
}

And path in unix server to run cron job every day.

* * * * * php /var/www/{domain}/artisan schedule:run 1>> /dev/null 2>&1

How can i do this, i have searched for this but i didn't get any idea.

Please help me out!



via Chebli Mohamed

jeudi 10 novembre 2016

Laravel Facebook Login : Error app_id is required

I'm using laravel 5.1, I want to add facebook social login to my page, but it is returning error

The parameter app_id is required

routes.php

Route::get('/redirect', 'UserController@redirect');
Route::get('/callback', 'UserController@callback');

UserController

public function redirect(){
    return Socialite::driver('facebook')->redirect();
}

Composer.json

"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.1.*",
     "laravel/socialite": "^2.0",
}

Config/Services.php

'facebook' => [
    'client_id' => '222221956976734',
    'client_secret' => 'a5acf8e8e01745d47rer829a0094vfvf',
    'redirect' => 'http://localhost/myproject/public/callback',
],

HTML

<a href="" style="background-color : rgb(59,89,152)" class="btn blue_btn_big">Login via Facebook</a>

What I have missed here..Any help is much appreciated..



via Chebli Mohamed

Store IP Address in database during sign up in laravel 5.1

Hii i want to store ip addresss in database in laravel 5.1.I have searched in google to store ip address and they suggest me to store ip address like Request::ip(); or other method $request->ip();.when i used this and keep this line as $request->ip(); then it print the ip address.But I have used array $data in auth controller during sign up.

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
           'ip' => $data->ip(),
        ]);
    }

the main problem is when i use this line as storing ip like this 'ip' => $data->ip(), it cause error
FatalErrorException in AuthController.php Call to a member function ip() on a non-object.The error is in this line 'ip' => $data->ip(). Can you please help me.



via Chebli Mohamed

Laravel 5.3 Different Fields Per User Role Type how to implement this using polymorphism?

Title says it all

For example

I want the main laravel User Model to have different kinds of roles and every role

has different fields

Example

User has a role of Employee

Where that role will have different fields for the user



via Chebli Mohamed

mercredi 9 novembre 2016

Laravel form - show file upload progress, then redirect to view when uploading finishes

I have a laravel application which successfully uploads files. I need to show a progress bar when the files are uploading since users might upload videos and then redirect to a certain view when uploading finishes. I have tried a few solutions which actually worked but not to my taste. For example, i tried DropZone but i only upload one file and i don't need the drag and drop feature. The solution that worked and came close to what i wanted is using jquery.form plugin. But the problem with it was, i still want the form to submit and redirect to the next page when the file upload finishes. Meaning, when uploading finishes, i still want the next line to be executed

return redirect()->action('PostController@edit', $post->PostID);

Here is my Controller (PostController)

public function attachstore(Request $request, $PostID)
{

$post = Post::findOrFail($PostID);

if ($request->hasFile('TextFile')) {
    $TextName = "";

    $now = \DateTime::createFromFormat('U.u', microtime(true));
    $nowStr = $now->format("m-d-Y-H-i-s-u");

    $TextName =  $nowStr . '.' . $request->file('TextFile')->getClientOriginalExtension();
    $request->file('TextFile')->move(base_path() . '/public/textuploads/', $TextName);
    $post->PostText = $TextName;  
}  


if ($request->hasFile('VideoFile') and $request->input('StoryUploadType') == 3) {
    $VideoName = "";
    $now = \DateTime::createFromFormat('U.u', microtime(true));
    $nowStr = $now->format("m-d-Y-H-i-s-u");

    $VideoName =  $nowStr . '.' . $request->file('VideoFile')->getClientOriginalExtension();
    $request->file('VideoFile')->move(base_path() . '/public/videouploads/', $VideoName);
    $post->PostVideo = $VideoName; 
}  

$post->Save();

return redirect()->action('PostController@edit', $post->PostID);

}

Here is my view (attach.blade.php)

   {!! Form::open(array('route' => array('posts.attachstore', $post->PostID), 'files' => true)) !!}
   <div class="col-md-12">    
    <div class="form-group">     
      {!! Form::file('TextFile', null, array('class'=>'form-control')) !!}
    </div>
  </div>

  <div class="col-md-12">    
    <div class="form-group">     
      {!! Form::file('VideoFile', null, array('class'=>'form-control')) !!}
    </div>
  </div>

  {!!Form::button('Next', array('type' => 'submit', 'class' => 'btn btn-primary finish col-md-4'))  !!}
  {!! Form::close() !!}

I don't know whether this could be done without using ajax, but i'd prefer a solution which uses ajax only to report how much file the server has received or the client has sent. I don't want to upload the files using ajax, only an estimate of the transferred file size.



via Chebli Mohamed

Laravel 5.3 Polymorphic Relations using Role Type with different fields for user

this is my first time asking a question on stackoverflow

So I want to implement a role based user based on my Multiple Store POS project

For Example:

User -> has a role of -> Manager

So every manager has assets and assets -> for example is a store

This Snippet of Code is inserted on my User.php file in laravel as an Eloquent Model

public function roles()
{
    return $this->belongsToMany(Role::class);
}

public function assets() {
    return $this->hasMany(Asset::class);
}

This snippet of code is based on the Asset.php file

protected $fillable = ['name','description','image_url'];

public function user() {
    return $this->belongsTo(User::class);
}

public function assetable()
{
    return $this->morphTo();
}

snippet for the Role.php

protected $fillable = ['name'];

public function users()
{
    return $this->belongsToMany(User::class);
}

im using this trait for polymorph purposes

trait Assetable
{
public function assets()
{
    return $this->morphMany(Asset::class, 'assetable');
}
}

and this is a sample of an asset as i said before snippet for Store.php

class Store extends Model
{
use Assetable;

protected $timestamps = false;

public function stocks() {
    return $this->hasMany(Stock::class);
}

}

So my problem is i want to separate the assets based on the role or this design for database is a bad IDEA?



via Chebli Mohamed

Payfast payment gateway ITN request not working in Laravel 5.1

I have integrate payfast payment gateway in our Laravel 5.1 website, it is working perfect on our development server but when we move site on live server it give error in ITN request step, here is the error which I am getting:

HTTP/1.1 500 Internal Server Error
Date: Wed, 09 Nov 2016 14:10:09 GMT
Server: Apache
Cache-Control: no-cache, private
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

When I am searching for solution I got below option to enable ITN request without CSRF token

protected $except = [
//
'/itn'
];

but this also not working, I put sample code folder on my website root folder and try to do payment and that will working.

Also when I try to write notify response in text file it print success in response to the file.



via Chebli Mohamed

Laravel mail error `Swift_TransportException in StreamBuffer.php line 269: Connection could not be established with host smtp.gmail.com [ #0]`

I am developing a website with a contact-us page where guest users can send me an email using Gmail. But anytime I try send the mail using the contact-us form, I get this error Swift_TransportException in StreamBuffer.php line 269: Connection could not be established with host smtp.gmail.com [ #0]

This is my mail.php

 return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => 587,
    'from' => ['address' => '', 'name' => ''],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env(MAIL_PASSWORD),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => env('MAIL_PRETEND', false),
  ];

This is my mail.php

  MAIL_DRIVER=smtp
  MAIL_HOST=smtp.gmail.com
  MAIL_PORT=587
  MAIL_USERNAME=afecjaped@gmail.com
  MAIL_PASSWORD=********
  MAIL_ENCRYPTION=tls

This is the UserController.php

 public function sendMail()
{
    $input = Request::all();

    $data = [
      'name' => $input['name'],
      'email' => $input['email'],
      'subject' => $input['subject'],
      'message' => $input['message']
    ];

    $rules = User::$mailRules;

    $validator = Validator::make($input, $rules);
    if ($validator->fails()) {
      return redirect()->back()->withErrors($validator)->withInput($input);
    } else {
      Mail::send('emails.send', $data, function($message) use ($data) {
        $message->from(Input::get('email'))
                ->to('afecjaped@gmail.com')
                ->subject(Input::get('subject'));
      });
    return 'Email Successfully sent';
    }
}



via Chebli Mohamed

Datatables ColVis search hidden columns

When I use the search box in Datatables it automatically search through the invisible columns.

Is there a possibility to disable this? I only need to filter the visible columns.

Datatables filter



via Chebli Mohamed

Laravel 5 socket.io event message not displaying

I am implementing socket.io with redis and nodejs. I have done with event and data is coming to the node server, but i am not receiving that data on my laravel 5 blade page.

Efforts

**blade page for receiving**
<script>
    var socket = io('http://localhost:3000');
        socket.on("test-channel:App\\Events\\MyEvent", function(message){
            // increase the power everytime we load test route
            console.log(message.data);
        });
</script>

Above code which is running on client side and not displaying data.

socket.js file

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('redis');
var redis = Redis.createClient();

redis.subscribe('test-channel', function(err, count) {
    // console.log(err,count);
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

Above code which is running on server side and displaying data in terminal.

I don't understand where i am doing wrong. Please friend help me.



via Chebli Mohamed

mardi 8 novembre 2016

Data not showing ng-repeat

My Html code is here

<div ng-controller="ServiceAreaController">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="ServiceArea in ServiceAreas">
                <td></td>
            </tr>
        </tbody>
    </table>
</div>

API request

app.controller('ServiceAreaController', function($scope, $http, API_URL) {
    var ServiceAreaUrl = API_URL + "apiServiceAreas";
    $http({
        method:         'POST',
        url:            ServiceAreaUrl,
        async:          true,
        contentType:    "application/json; charset=utf-8"
    }).success(function(response) {
        if(response["Status"]) {
            $scope.ServiceAreas = response["Data"];
        }
    }).error(function(response) {
        console.log(response);
    });
});

response["Data"] is like below

"Data": [
    {
      "ServiceAreaID": 67,
      "ServiceArea": "116123"
    },
    {
      "ServiceAreaID": 68,
      "ServiceArea": "101708"
    },
    {
      "ServiceAreaID": 69,
      "ServiceArea": "101708"
    }
]

It generates total three tr but td is not showing any data. Am I missing anything?



via Chebli Mohamed

lundi 7 novembre 2016

How to write this query in laravel 5

I'm experiencing difficulty in writing this query in laravel 5.1,

select * from `host_requests` where `host_id` = 5 and (`email` LIKE "%v%" or `request_url` LIKE "%v%")

The purpose of this query is to fetch records that are associated with host_id = 5, also email and request_url are optional if they set then LIKE clause should be used. I wrote the query in laravel like this

$searchname = "v";
$hostid = "5";
$data = HostRequest::where('email', 'LIKE', '%' . $searchname . '%')
                ->where('host_id', $hostid)
                ->orwhere('request_url', 'LIKE', '%' . $searchname . '%')
                ->latest('id')
                ->paginate($size);

It is fetching all the records that are also not associated with host_id = 5.

Any help is much appreciated..Thanks



via Chebli Mohamed

Laravel 5.3 does not Angular Js files

I have good knowledge in Laravel 5.3 but never worked on Angular.js

We can create the new Laravel project using command

composer create-project laravel/laravel ProjectName

But this does not include any Angular Js files. I checked on Google if there is any way on command prompt to download any directory structure. After many hours search, I posted the questions

Can you kindly suggest?



via Chebli Mohamed

laravel 5.1 phpspec command not found

I'm trying to run phpspec but when I do a command phpspec run inside root project folder it just prints:

-bash: phpspec: command not found

But when I do composer show -i it shows it's installed (because it's in package.json):

phpspec/php-diff                      v1.0.2             A comprehensive li...
phpspec/phpspec                       2.5.3              Specification-orie...
phpspec/prophecy                      v1.6.1             Highly opinionated...

What's wrong?



via Chebli Mohamed

dimanche 6 novembre 2016

Ionic / Angular.js- Converting Binary Image Data to Image

In my Ionic App, I have a Laravel webservice that is pulling an image file from AWS S3. The S3 bcuket is secured with an IAM user. Therefore just by simply pointing to the http://S3URL/bucket/imagename.jpg would not work. Instead my API returns a binary stream. I tried converting the binary stream into an image that can be displayed by using the following:

 $scope.receiptdata = response.data; // (response from My web service)
 var basestring = "data:image/png;base64,";
 $scope.newreceipt = basestring + $scope.receiptdata;

And then in my view

However, I received a blank view. I have tested the view with another static image by pointing to a remote url and I know for a fact that it works. Is there a way to display the the image. I am trying not to do away with all the security in my S3 bucket as the images are specific to the users and I don't want other than the user who owns it to own it.



via Chebli Mohamed

Laravel eloquent model funtion returns empty

In my project, LedgerModel.php has functions like below:

public function entries(){
    return $this->hasMany('App\Models\AccountingModule\EntryItemModel','ledger_id');
}

public function debit()
{
    return $this->entries()->selectRaw('sum(amount) as debit')->where('dc','D');
}

In My controller:

$ledger = LedgerModel::with('entries')->with('debit')->where('id',81)->get(); 

Entries give the correct values but debit returns empty. I have printed query. It gives:

array:3 [▼
"query" => "select sum(amount) as debit from `entry_items` where `dc` = ? and `entry_items`.`ledger_id` in (?)"
"bindings" => array:2 [▼
  0 => "D"
  1 => 81
]
"time" => 0.79

I have executed the following query by pesting from print in sql and it gives value.

select sum(amount) as debit from `entry_items` where `dc` = "D" and `entry_items`.`ledger_id` in (81)

Please help me to find out my mistake.



via Chebli Mohamed

Trying to pass js value in Route Parameter : Laravel 5

Below is my code in Laravel.

<script language="javascript">
    $(document).ready(function() {
        var $_token         =   "{!! csrf_token() !!}";

        var data = {
            "_token"        : $_token, 
        };
        $.ajax({
            url:            '',
            method:         "POST",
            async:          true,
            data:           JSON.stringify(data),
            contentType:    "application/json; charset=utf-8",
            success: function (result) {
                $.each(result.Data, function( key, ServiceArea ) {
                    var URL = '{!! route("ServiceAreaDetails", ["ID" => 1]); !!}';
                });
            }
        });
    });
</script>

What is the point in discussion?

Value = 1 in this code is static. Can we make it dynamic? var URL = '{!! route("ServiceAreaDetails", ["ID" => 1]); !!}';

What's the problem?

Route function is server side coding. Is there any way to pass js value inside loop to this server side function parameter?

Js value will be ServiceArea.ID



via Chebli Mohamed

vendredi 4 novembre 2016

delay() notification seems not working

I am following this to delay notification. http://ift.tt/2fqkAFY

From localhost, I tried to send notification with Gmail credentials. It sends email but sends immediately and also it takes around 10 seconds to send email. My code is below.

$when = \Carbon\Carbon::now()->addMinutes(10);

$user->notify((new Notification($notification))->delay($when));

Was that due to Gmail or I missed something?



via Chebli Mohamed

Error while creating trigger from Schema Builder

<?php

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

class CreateTriggerUserDelete extends Migration
{
    public function up()
    {
        \DB::unprepared('DELIMITER //
                CREATE TRIGGER DeleteUserDependency
                BEFORE DELETE
                   ON tbluser FOR EACH ROW
                BEGIN 
                    Delete from tblticket where ModuleID = 1;

                END');
    }
}

I am facing Error. Details are here: Syntax error or access violation: 1064 You have an error in your SQl syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DELIMITER //

Am I missing something?



via Chebli Mohamed

How to edit Laravel Package?

I need to edit Laravel package for change the extended class and need to add use somename at the top of the file. I read this and seems it is not a solution for my requirement. Can I do it by anthor way? Thank you.



via Chebli Mohamed

jeudi 3 novembre 2016

Magic gets and sets for Laravel 5

I know there exists the magic gets and sets in PHP to each attribute of a class:

 public function __get( $key ){
   return $this->values[ $key ]; 
}

public function __set( $key, $value )
{
    $this->values[ $key ] = $value;
}

However, I do not know how to use it with Laravel. I noted that Laravel considers only not null fields (according to the migration) to execute the __get and __set. I want to apply a mask to some fields, so I tried:

public function __get($key)  {
   if($key == 'note1')
     return $this->maskFloat($this->attributes[$attr]);    
 }

But there is no 'note1' field because it is nullable in the migration.

Any help. please?



via Chebli Mohamed

Explain Query in Laravel

Is there a way to use explain query for mysql in laravel? Everything that I found online just talks about straight mysql syntax.

Thanks for the help!



via Chebli Mohamed

using Where in views Laravel 5.1

I'm relative new in laravel, in my first app I have a method in the controller that pass a list of links to the view, but in the view I only need some of those links so in the view I have this:

$links->where('menu_id', 2)

This works in my developer environment but don't work in production server.

Someone knows why? or knows another way to filter the results in the view?



via Chebli Mohamed

Laravel display data from one database table by using the id of that row

So I have a table pages, that looks like this:

public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name');
            $table->integer('category')->unsigned();
]        });

        Schema::table('pages', function($table) {
            $table->foreign('user_id')->references('id')->on('core_users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('category')->references('id')->on('ecommerce_payment_pages_categories')
                ->onUpdate('cascade')->onDelete('set null');

        });
    }


    public function down()
    {
        Schema::drop('pages');
    }

And a table categories looking like this:

public function up()
    {
        Schema::create('ecommerce_payment_pages_categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('core_users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('categories');
    }

The pages model looks like this:

class Pages extends Model
{

    protected $table = 'pages';


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

    protected $fillable = [

    ];

    protected $casts = [

    ];

    public function categories() {
        return $this->belongsTo("\App\Models\Categories");
    }
}

And the categories model looks like this:

class PaymentPagesCategories extends Model
{
    protected $table = 'categories';

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

    protected $fillable = [

    ];

    protected $casts = [

    ];

    public function pages_categories() {
        return $this->hasMany("\App\Models\\Pages");
    }
}

So in my pages table I save in the column category the id of the category that the user selects from a dynamic select that echoes the category id as value and category names as options. But I cannot save it as simple string because in another menu the user has the option to delete categories, so I want that when a category gets deleted to get deleted from the category column in the page table as well. Right now I display the data from the database like this:

public function getGet()
{
    return response()->json(['success' => true, 'payment_pages' => \Auth::user()->payment_pages()->orderBy('id', 'ASC')->get()]);
}

So for the currently authenticated user I display all the data from the page database table.



via Chebli Mohamed

mercredi 2 novembre 2016

Laravel 5.1 S3 Secure Image access via Restful API

I am using token based auth for a Restful API on Laravel 5.1. I am using S3 as the file storage to upload user specific images. I would like to limit the access only to the user who has uploaded the image(s). They should be able to view the images in a mobile API. Is there are a way to do that with Laravel 5.1 and S3 without making the S3 directory public?



via Chebli Mohamed

How to handel automatic urls in laravel

how can i make automatic Urls with Middleware and prefix ? for example

Route::grouo(['prefix'=>'dashboard','middleware'=>'auth'],function(){
    // Witch urls with this prefix entered connect to that view .
});

laravel have any options to use it for this ?



via Chebli Mohamed

mardi 1 novembre 2016

click on link then page data come in body, url change and chat window not go out

Greeting of the Morning !

I am working a web application in which, left side bar and body, has chat module like facebook. My problem is when click on any link of the left side bar then page refresh then chat gone. I tried then show page without redirecting and change url but ping chat gone. I have used nodejs for the chat.

I do want click on link then page data come in body, url change and chat window not go out.

routes.php

Route::get('/geturl', function(){
return view('geturl');
});

geturl.blade.php

<script src="http://ift.tt/2eBd7UN"></script>

<script type="text/javascript">

$(function(){
$("a[rel='tab']").click(function(e){
//code for the link action
return false;
});
});

$(function(){
$("a[rel='tab']").click(function(e){
//e.preventDefault();


//get the link location that was clicked
pageurl = $(this).attr('href');

//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl+'?rel=tab',success: function(data){
$('#content').html(data);

}});

//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
});



/* the below code is to override back button to get the ajax content without page reload*/
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#content').html(data);
}});
});
</script>

<body><div id="menu">
<a href="/dashboard" rel="tab">menu1</a> |
<a href="/profile/edit" rel="tab">menu2</a> |
<a href="/contact-support" rel="tab">menu3</a>
</div><div id="content"></div></body>



via Chebli Mohamed

update and delete record in laravel

I'm learning so I'm a beginner in laravel. I finally wrote my function that adds a record in mySQL database. Now I tried to update and delete based on this function but construct a correct one. public function add(Request $resquest) {

    if ($resquest->isMethod('post')) {

        $newmaid = New Product();
        $newmaid->name = $resquest->input('name');
        $newmaid->price = $resquest->input('price');
        $newmaid->save();

    }
    return view('add');

}

the function I wrote will show a form when click on submit it adds record to database and returns to same page.



via Chebli Mohamed