vendredi 31 mars 2017

Binding routes to wrong method controller

I am using laravel 5.1 app. I have the bellow routes:

Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');

Also I use RouteServiceProvider like so:

    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){ 
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first(); 
   }); 

    $router->bind('about', function($about){ 
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail(); 
    });    

    }

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?



via Chebli Mohamed

jeudi 30 mars 2017

sudo composer install vs. composer install

I run sudo composer install I got this warning

Do not run Composer as root/super user! See http://ift.tt/1UioBPp for details

I tried just composer install I got this error

[ErrorException] file_put_contents(/Applications/MAMP/htdocs/code/bheng/vendor/composer/installed.json): faile d to open stream: Permission denied

Here is the current permission set on my Laravel folder

total 1872
-rw-r--r--   1 bheng  staff     777 Feb 27 20:18 phpunit.xml
-rw-r--r--   1 bheng  staff      87 Feb 27 20:18 phpspec.yml
-rw-r--r--   1 bheng  staff     481 Feb 27 20:18 package.json
drwxr-xr-x   3 bheng  staff     102 Feb 27 20:18 note
-rw-r--r--   1 bheng  staff     967 Feb 27 20:18 md-bheng-readme.txt
-rw-r--r--   1 bheng  staff     503 Feb 27 20:18 gulpfile.js
-rw-r--r--   1 bheng  staff      26 Feb 27 20:18 contributors.txt
-rw-r--r--   1 bheng  staff    1635 Feb 27 20:18 artisan
-rw-r--r--   1 bheng  staff      43 Feb 27 20:18 Procfile
-rw-r--r--   1 bheng  staff    5634 Feb 27 20:18 Gruntfile.js
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 tests
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 storage
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 sql
-rw-r--r--   1 bheng  staff     560 Feb 27 20:18 server.php
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 resources
-rw-r--r--   1 bheng  staff     105 Feb 27 20:18 pull.sh
drwxr-xr-x   7 bheng  staff     238 Mar  1 14:46 bootstrap
-rw-r--r--@  1 bheng  staff       0 Mar  1 14:46 Icon?
drwxr-xr-x  22 bheng  staff     748 Mar  2 11:47 app
drwxrwxrwx@ 27 bheng  staff     918 Mar  3 14:55 public
drwxr-xr-x   8 bheng  staff     272 Mar  6 13:25 database
-rw-------@  1 bheng  staff     405 Mar 14 09:29 id_rsa.pub
-rw-------   1 bheng  staff    1766 Mar 14 09:29 id_rsa
-rw-r--r--   1 bheng  staff  126713 Mar 14 10:00 composer.lock
drwxr-xr-x  18 bheng  staff     612 Mar 28 21:24 config
-rw-r--r--   1 bheng  staff    1022 Mar 30 12:21 composer.json
drwxr-xr-x  32 bheng  staff    1088 Mar 30 12:21 vendor


How do I fix this ? Do I need to chmod any folders ?



via Chebli Mohamed

Three select dropdown for school year that hides previous years

How to hide years in select dropdown if not needed. I have 3 select dropdown for school year using php code snippet. Example in the first dropdown:

    2016-2017
    2015-2016
    2014-2015
    2013-2014
    2012-2013
    2011-2012

    If i select 2012-2013, the 2nd dropdown should display:
    2016-2017
    2015-2016
    2014-2015
    2013-2014
   If i select 2014-2015, the 3rd dropdown should display:
    2016-2017
    2015-2016

Is there a possible way using php code snippet alone or do i have to use javascript? The problem is, I'd tried my code in php but no luck and the more if i use javascript since I'm not get used of it.Hope anyone could help me or give me a light on doing the next step base on my present code.

Here is my code:

<label class="control-label">SY 1:</label> 
    <select class="form-control" name="scholar_secondary_school_year" id="test" onchange="educSec(this)">
               <?php 
                $null = 'null';
                $choose = 'Choose SY';
                $Present = 'Present';
          echo '<option value='.$null.'>' .$choose.'</option>';
          echo '<option value='.$Present.'>' .$Present.'</option>';
                  for($i=date('Y');  $i > date('Y')-30; $i--){

                     $x = $i +1;
                     $y = $i;
       echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
                   }?>
    </select>

    <label class="control-label">SY 2:</label> 
    <select class="form-control" name="scholar_secondary_school_year" id="test" onchange="educSec(this)">
               <?php 
                $null = 'null';
                $choose = 'Choose SY';
                $Present = 'Present';
          echo '<option value='.$null.'>' .$choose.'</option>';
          echo '<option value='.$Present.'>' .$Present.'</option>';
                  for($i=date('Y');  $i > date('Y')-30; $i--){

                     $x = $i +1;
                     $y = $i;
       echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
                   }?>
    </select>

    <label class="control-label">SY 3:</label> 
    <select class="form-control" name="scholar_secondary_school_year" id="test" onchange="educSec(this)">
               <?php 
                $null = 'null';
                $choose = 'Choose SY';
                $Present = 'Present';
          echo '<option value='.$null.'>' .$choose.'</option>';
          echo '<option value='.$Present.'>' .$Present.'</option>';
                  for($i=date('Y');  $i > date('Y')-30; $i--){

                     $x = $i +1;
                     $y = $i;
       echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
                   }?>
    </select>



via Chebli Mohamed

mercredi 29 mars 2017

how can i disable check server ip in jwt package?

in laravel and jwt package when create a token, I can't use from token in same app in other server. how can I remove ip check in token auth? any body can help?



via Chebli Mohamed

laravel 5 migration error for creating table

Hi i am using folliwing command to cerate migration and the file generating successfullly.

But i am getting following error :-
[ErrorException]
Creating default object from empty value
My command and code is as below.

Command :- php artisan make:migration create_admin_notavailabel_table

Generated File Code :-

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

class CreateAdminNotavailabelTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
   Schema::create('admin_notavailabel', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('id_location');
        $table->enum('not_avaiblity_type', ['days', 'hours']);
        $table->text('message');
        $table->string('repeat_on',50);
        $table->date('start_date');
        $table->date('end_date');
        $table->time('start_time');
        $table->time('end_time');
        $table->timestamps();

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
     Schema::dropIfExists("admin_notavailabel"); 
}

}



via Chebli Mohamed

mardi 28 mars 2017

Handle SAML POST and still maintaining CSRF in Laravel 5

I use this package = http://ift.tt/1DOh9wB I configured everything in the SP and iDP sections in saml2_settings.php as instructed.


STEPS

I go to : /admin/login I got redirected and landed on my iDP log-in page immediately, it is a correct behavior.

I log-in with the proper username and password.

enter image description here

After successfully authenticated by my iDP, I got the SAML Response from my iDP like this sample

{
"SAMLResponse": "PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6\r\nU0FNTDoyLjA6cHJvdG9jb2wiIERlc3RpbmF0aW9uPSJodHRwczovL3Rlc3RzZXJ2\r\nZXIuYmVudW5ldHMuY29tL2FkbWluL3NlY3VyZS9kYXNoYm9hcmQiIElEPSJpZC1C\r\nNlBFSnhLNFhGWUg3T1hzbGZLU2trbGt0YmMtIiBJblJlc3BvbnNlVG89Ik9ORUxP\r\nR0lOXzIxNjFiNTA1OTFmNjc1ZmUzZGM0MmZlYzRlZDJkOGU1MWRlZmQ2ZmQiIElz\r\nc3VlSW5zdGFudD0iMjAxNy0wMy0yOFQxOTozMzo1M1oiIFZlcnNpb249IjIuMCI+\r\nPHNhbWw6SXNzdWVyIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1M\r\nOjIuMDphc3NlcnRpb24iIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6\r\nMi4wOm5hbWVpZC1mb3JtYXQ6ZW50aXR5Ij5UZWxlbmV0PC9zYW1sOklzc3Vlcj48\r\nc2FtbHA6U3RhdHVzPjxzYW1scDpTdGF0dXNDb2RlIFZhbHVlPSJ1cm46b2FzaXM6\r\nbmFtZXM6dGM6U0FNTDoyLjA6c3RhdHVzOlN1Y2Nlc3MiLz48L3NhbWxwOlN0YXR1\r\ncz48c2FtbDpBc3NlcnRpb24geG1sbnM6c2FtbD0idXJuOm9hc2lzOm5hbWVzOnRj\r\nOlNBTUw6Mi4wOmFzc2VydGlvbiIgSUQ9ImlkLThvWVBULWlwVFZhR2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\r\nZXJ2ZXIuYmVudW5ldHMuY29tPC9zYW1sOkF1ZGllbmNlPjwvc2FtbDpBdWRpZW5j\r\nZVJlc3RyaWN0aW9uPjwvc2FtbDpDb25kaXRpb25zPjxzYW1sOkF1dGhuU3RhdGVt\r\nZW50IEF1dGhuSW5zdGFudD0iMjAxNy0wMy0yOFQxOTozMzo1M1oiIFNlc3Npb25J\r\nbmRleD0iaWQtWEVRcWVNZFRiRHRaLXNhaFN4ZnNYdVA2MWlJLSIgU2Vzc2lvbk5v\r\ndE9uT3JBZnRlcj0iMjAxNy0wMy0yOFQyMDozMzo1M1oiPjxzYW1sOkF1dGhuQ29u\r\ndGV4dD48c2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj51cm46b2FzaXM6bmFtZXM6\r\ndGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZFByb3RlY3RlZFRyYW5zcG9y\r\ndDwvc2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj48L3NhbWw6QXV0aG5Db250ZXh0\r\nPjwvc2FtbDpBdXRoblN0YXRlbWVudD48L3NhbWw6QXNzZXJ0aW9uPjwvc2FtbHA6\r\nUmVzcG9uc2U+\r\n",
"RelayState": "http://ift.tt/2o8l8bK"
}


kernel.php

I can only see this response only because I comment out my CFRF token on my app/Http/kernel.php

// \App\Http\Middleware\VerifyCsrfToken::class,


ROUTE

Route::post('admin/secure/dashboard', 'SAMLController@post');

CONTROLLER

 public function post(){
    return Input::all();
}


What is the best practice to deal with SAML POST and still maintaining CSRF protection ?

Should I create a middleware or anything similar to that ?



via Chebli Mohamed

Auth session killed after redirect | laravel 5.1

When I call:

Auth::loginUsingId($user->id, true);
print_r(Auth::user());

...It's ok. But when I have this function after that:

return redirect('/');

Now in mydomain.com I called print_r(Auth::user()); and it return null;

Here is my Kernel.php

class Kernel extends HttpKernel
{

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth'           => \App\Http\Middleware\Authenticate::class,
        'auth.basic'     => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest'          => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'admin'          => \App\Http\Middleware\AdminMiddlware::class
    ];

}

Laravel version: Laravel Framework version 5.1.46 (LTS)



via Chebli Mohamed

Allow others to make a HTTP POST to your Laravel 5 App

I'm testing my post route right now because I need to allow this route to be posted by other application.

I declare my route like this :

Route::post('/api/obj/post', 'DashboardController@post');

I'm trying to post this data to my route via cURL

{"test":"123"}

curl -X POST -H "Content-Type:application/json" -d '{"test":"123"}' http://ift.tt/2nwuexN

Here is my controller function

public function post(){
    dd(Input::all()); <--------- I should see all the inputs that submit to me. Shouldn't I ?
}

I keep getting redirecting back to home page instead

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://127.0.0.1" />

        <title>Redirecting to http://ift.tt/2od9c5E;
    </head>
    <body>
        Redirecting to <a href="http://127.0.0.1">http://ift.tt/2nwDjXd;.
    </body>
</html>


Questions

How do I prevent that redirect, and instead grab those data and continue my tasks so on and so forth ?

How would one go about and debug this further ?


I'm opening to any suggestions at this moment.

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



via Chebli Mohamed

lundi 27 mars 2017

SSO in laravel and node application

My application(mobile app)'s backend is done in laravel. I am trying to implement common authentication server using node js. Node js is used only for authentication .All other api are done in laravel. How can i implement sso in this application? Thanks in advance



via Chebli Mohamed

Laravel displaying elements distinctly

public function employeebanvisitor(Request $request) { 
    $vis = bookingmodel::distinct('visitorname')
        ->select(
            'id',
            'visitorname',
            'visitorphonenumber',
            'compname',
            'designation'
        )
        ->where('empmail',Auth::user()->email)
        ->get(); 
    return view('employee.employeebanvisitor',compact('vis')); 
}

In the above query i need to display the list distinctly where the the distinct element is visitorname.But this command does not return elements distinctly.Any Help or suggestion is most welcomed.



via Chebli Mohamed

dimanche 26 mars 2017

Postman Oauth2 call works, however same call in Jquery fails (web extension)

I have been using Oauth2 using Postman and it works just fine. I get the token as expected.

Postman Oauth

However when I try this in code, it makes everything but I am never returned the code to use (the code is in my database, but it isn't returned from the jquery call).

function validate(redirectURL) {
  console.log('start validate function');


  var clientID2 = "CLIENTID HERE";
  var redirectURL2 = browser.identity.getRedirectURL();
  let m = redirectURL.match(/[#\?](.*)/);
  if (!m || m.length < 1)
    return null;
  let params = new URLSearchParams(m[1].split("#")[0]);
    let tokenurl = "http://localhost:8000/oauth/access_token";
  // tokenurl += `?client_id=${clientID2}`;
  // tokenurl += `?client_secret=${clientSecret}`;
  // tokenurl += `&grant_type=authorization_code`;
  // tokenurl += `&code=${params.get("code")}`;
  // tokenurl += `&redirect_uri=${encodeURIComponent(redirectURL2)}`;
  console.log('validate function tokenurl '+ tokenurl);
  $.ajax({
    method: "POST",
    url: tokenurl,
    async: true,
    crossDomain: true,
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      "cache-control": "no-cache"
    },
    data : {
      client_id : clientID2,
      client_secret : "CLIENT ID SECRET",
      redirect_uri : redirectURL2,
      grant_type : "authorization_code",
      code : params.get("code"),
    }
  })
    .done(function( msg ) {
      console.log('Done return for validate call');
      // console.log( "Token Save Called: " + msg );
    })
    .fail(function(jqXHR, textStatus, errorThrown){
      console.log('Fail return for validate call');
      if(textStatus){
        console.log('validate call returned textStatus-' + textStatus);
      }
      if(errorThrown){
        console.log('validate call returned errorThrown-'+errorThrown);
      }
      console.log('Fail return for validate call Finish');
    })
    .always(function( xhr, status ) {
       console.log('finish validate call ajax request');
     });
}


function authorize() {
  console.log('authorize2');
  const redirectURL = browser.identity.getRedirectURL();
  console.log('redirectURL');
  console.log(encodeURIComponent(redirectURL));
  console.log(redirectURL);
  const clientID = "CLIENTID HERE";
  const scopes = ["openid", "email", "profile"];
  let authURL = "http://localhost:8000/oauth/authorize";
  authURL += `?client_id=${clientID}`;
  authURL += `&grant_type=authorization_code`;
  authURL += `&client_secret=4c7f6f8fa93d59c45502c0ae8c4a95b`;
  authURL += `&response_type=code`;
  authURL += `&redirect_uri=${encodeURIComponent(redirectURL)}`;
  // authURL += `&scope=${encodeURIComponent(scopes.join(' '))}`;

  console.log('redirectURL');
  console.log(redirectURL);
  console.log('authURL');
  console.log(authURL);

  return browser.identity.launchWebAuthFlow({
    interactive: true,
    url: authURL
  });
}


function getAccessToken() {
  console.log('call authorize');
  return authorize().then(validate);
}

console.log('call getAccessToken');
getAccessToken();

I get no data returned and the console logs put out the word error. The functions are getting called and getting to my backend because it is making and storing the final code in the database.

I am using this laravel oauth package http://ift.tt/17O1EK3 with version 5.1

I am using this in a firefox webextension on Firefox Developer Edition running version 54 which supports Oauth2 calls (based on documentation).



via Chebli Mohamed

Accessing Function Variable

    public function acceptpersonalvisitupdate(Request $request)
    {  $employeeinfo=$request->input('employeeinfo');
       $id=$request->input('id');
       $visitoremail=$request->input('visitoremail');
       $visitorname=$request->input('visitorname');
       $visitorphonenumber=$request->input('visitorphonenumber');
       $visitortype=$request->input('visitortype');
       $empname=$request->input('empname');
       $empdept=$request->input('empdept');
       $date=$request->input('date');
       $from=$request->input('from');
       $noofhours=$request->input('noofhours');


       Mail::send('mails.acceptedpersonalvisit',     
        ['visitorname'=>$visitorname,'visitorphonenumber'=>$visitorphonenumber,
                                              'visitoremail'=>$visitoremail,'id'=>$id,'visitortype'=>$visitortype,
                                              'empname'=>$empname,'empdept'=>$empdept,'date'=>$date,'from'=>$from,
                                              'noofhours'=>$noofhours,'employeeinfo'=>$employeeinfo],function($message)
   {
     $message->to($visitoremail,$visitorname))->subject('Personal Visit Request Accepted');
   });
   DB::update('update bookingtable set employeeinfo=?,staus="Approved" where id=?',[$employeeinfo,$id]);
   return Redirect::to('acceptedpersonalvisits')->with('success','Successfully Accepted Personal Book Request!!!');
}

In The Above Code i have a acceptpersonalvisitupdate post function.Its variables are those list of variables defined.From that variables i want to access $visitoremail and $visitorname in mail function.when i normally represent the variable it shows error as undefined variable $visitoremail.how to access that variable inside mail function.Any Help and suggestions are most welcome.Thank You.



via Chebli Mohamed

vendredi 24 mars 2017

I can't install doctrine/dbal dependency on composer laravel

I am searching for help, but I don't finded

I can't install doctrine/dbal dependency on composer. I already tried by

composer require doctrine/dbal

And appeared "[Composer\Downloader\TransportException] The "http://ift.tt/2nMYANi" file could not be downloaded (HTTP/1.1 302 Found)"

really, when i acess the adress the page shows:

"Oh noes, 404! It looks like you requested a page that was not found. Go back to the homepage or use the search above to find the package you want."

I tried by composer.json file writing

"doctrine/dbal": "v2.4.2"

and then (in command line)

composer update

The same error occurs.

My laravel: laravel/framework": "5.1.*"

Can somebody help me? thanks



via Chebli Mohamed

Get the latest record of a particular id in a table

    ScholarCard
    scholar_card_id         grade       scholar_id
    1                       grade-1         1
    2                       grade-1         2
    3                       grade-2         1
    4                       grade-2         2
    5                       grade-3         1

$scholar_cards = ScholarCard::orderBy('scholar_card_id','DESC')->get();

I have a table for a card of grades and i want to display the latest created card. Like for example for scholar_id 1,there are three 1 on the column.How do you display only the scholar_id 1 with the latest or last creation.This table has only few record for simplicity.



via Chebli Mohamed

Laravel Database storing only value not array

$visitorphonenumber=DB::select('select phonenumber from visitortable where email=?',[Auth::user()->email]);

$booking=new bookingmodel(); $booking->visitorphonenumber=$visitorphonenumber; this stores the value like [{"phonenumber":"9874589608"}] in database but i want to store only the 9874589608



via Chebli Mohamed

jeudi 23 mars 2017

Updating child table in Laravel relation

Hope someone could help me updating my child table.I need to update need_status with a static value from Available to Taken.I must be missing something out here since I am new to laravel. Thank you in advance.

scholar_need_id  |  scholar_id | need_id  |  need_status

5                       1             2      Available 
6                       1             2      Taken

class Scholar extends Model { protected $primaryKey = 'scholar_id';     protected $fillable = [];

    public function needDetails(){
        //return $this->hasMany('App\ScholarNeed','scholar_need_id','scholar_id');
         return $this->hasMany('App\ScholarNeed','scholar_id','scholar_id');
    } }

--------------

class ScholarNeed extends Model {       protected $primaryKey = 'scholar_need_id';
    protected $fillable = ['scholar_id','need_id','need_status'];


    public function getNeedInfo(){
       // return $this->belongsTo('App\Scholar','scholar_id','scholar_need_id');
         return $this->belongsTo('App\Scholar','scholar_id','scholar_id');
    } }

------  public function update(Request $request,$recommend_id)
    {
       $id =  $request['scholar_id'];
     // $scholar = Scholar::find($id)->with('needDetails')->get();
      $scholarID = Scholar::with('needDetails')->find($id);
       $scholarID->needDetails()->need_status = 'Taken'; 
       $scholarID->save(); }



via Chebli Mohamed

mercredi 22 mars 2017

CentOS iptables and port configuration for using external SMTP server

I have a web server running CentOS and a separate mail server running Microsoft Exchange. I have the web server connecting to the mail server via SMTP on port 587 to send emails.

Sometimes the connection to the mail server refuses, but it's rare. Could an intermittent failure be related to port settings? I would have thought it's all or nothing.

For the CentOS web server, what rules should I be looking to configure in the iptables if any? Do I need to add an entry for port 587 on this server? Or do I just need to allow incoming connections on the mail server for 587?

Thanks in advance.



via Chebli Mohamed

mardi 21 mars 2017

Laravel - Guzzle: Getting GuzzleHttp\Exception\ConnectException: cURL error 6 Could not resolve host randomly

This is probably the weirdest situation that I ever seen. Basically I have a system built in Laravel 5.1 which needs to make a request to an external system. The thing is, sometimes it works but sometimes I get

GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: hosthere

Absolutely nothing changes, in terms of code. I run the application with exactly the same parameters and sometimes I get the error, sometimes I get the right response.

Any ideas?

Thanks in advance



via Chebli Mohamed

Not duplicate id of scholar resulte

Hi can anyone help me about my problem. i creating a criteria of my project, If the id is ['1','2'] it will search possible scholar that matched with the needs of scholarship. If the need_status of the scholar searched by the scholarship was "taken" it will not be included in the list.

ScholarshipNeed
id              scholarship_id      need_id
1                   2                   1
2                   2                   2

ScholarNeed
id              scholar_id              Need_id             need_status
1                   1                       1                   Available
1                   1                       2                   Available
1                   3                       1                   Available
1                   3                       2                   Taken
1                   4                       1                   Available

$scholarship_needs = ScholarshipNeed::where('scholarship_id','=',$scholarship_id)->get();            
$all_need_id = [];
foreach ($scholarship_needs as $id6) {
    array_push($all_need_id, $id6->need_id);
}
$scholar3 = array();
$scholarNeed = ScholarNeed::whereIN('scholar_id',$Scholar2)->whereIn('need_id',$all_need_id)->where('need_status','Available')->get();     
foreach ($scholarNeed as $all) {
    array_push($scholar3, $all->scholar_id);
}   

dd($scholar3);

This is the result right now

array:1 [▼
0 => 1
1 => 1
2 => 3
3 => 4
]

This is what i want to be result:

array:1 [▼
0 => 1
1 => 4
]



via Chebli Mohamed

Laravel 5.1 asset() not working in ssl enabled ec2 instance

I am using aws EC2 instance for my laravel project and installed ssl certificate using load balancer for website. After activating ssl on ec2 instance for my website, laravel asset() for javascript and css taking http not https. Beacuse of this website unable to find js and css files and website looks completely weird. I know that secure_asset() is available for https but in localhost it will not work. When I was hosting same website in Godaddy VPS with ssl it was not showing any error for asset() but in ec2 its taking incorrect path. Laravel asset() takes both http or https based on the url.

I am using ubuntu OS with nginx server installed and php 7.0. Is there any extra steps we have to perform for laravel in ec2 or nginx for ssl to work properly. I will be happy if somebody helps me get solution. Thank you in advance.



via Chebli Mohamed

samedi 18 mars 2017

Redirect to homepage if page is a directory listing in Laravel

I'd like to able able to redirect users (either to a 404 page or back to the homepage) if the page they're at is a directory listing, like so:

enter image description here

Here is my .htaccess file:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L] 
</IfModule>

Is this possible with Laravel?



via Chebli Mohamed

forgetParameter not working with Resources

I'm working with Laravel 5.1.

Let's say that I have a route group defined like this:

Route::group(array('prefix' => 'item/{itemId?}', 'middleware' => ['itemStrip']), function(){

And within the Middleware itemStrip, I want to work with the item passed, then remove it from the URI before moving onto a resource within the group. The Resource would be defined like this, for example:

Route::resource('itemA.itemB',
    'ItemController',
    ['only'=>['index']]);

So, this resource has one variable that it needs to access, which is held between itemA and itemB.

I find that, even if I use

$request->route()->forgetParameter('itemId');

within the itemStrip middleware, the parameter still ends up making it to the actual resource. Which is to say, when we finally hit:

public function index($itemAId)

within the resource controller, it is grabbing the parameter itemId as opposed to the parameter between itemA and itemB. Why is this, after I stripped the Parameter from the route in the Middleware? Is there anyway to fully remove itemId, in order to keep it from hitting the resource?

A little more information, I'm finishing the Middleware with this:

return $next($request);



via Chebli Mohamed

vendredi 17 mars 2017

How to use Laravel elequent model to get data with mutiple where condition

I am new to Laravel and currently working on Laravel 5.1. I am trying to authenticate user by its email and password. To get this, I am using the below code to find the user:

First Method: Using Elequent Model

$result = user_model::where('email', $data['email'])->where('password', \Illuminate\Support\Facades\Hash::make($data['password']))->first();  

Second Method: Using with() Method:

$result = user_model::where('email', $data['email'])
        ->where(function($q) use($data) {
            $q->where('password', '=', Hash::make($data['password']));
        })->first();  

Third Method: Using query Builder:

$result = DB::table('users')->where('email', $data['email'])->where('password', Hash::make($data['password']))->get();  

Each of the above method is returning null even the the user is exist into database.

If I use single where condition either for email or password then First method returns user object with data.

Can anyone help me for How can i get the result of query having multiple where conditions.



via Chebli Mohamed

jeudi 16 mars 2017

laravel 5.2 custom login

I try to create custom login page but I got an error

Undefined index: password

my controller code

$this->validate($Request, [
        'Email' => 'required',
        'password' => 'required',
        ]);
         $email    = $Request['Email'];
         $password     =  md5($Request['password']);
         $login    = new login();
         $login    = login::where('Email', $email);
         if(empty($password))
         {
            return('404');
         }
         if(Auth::attempt(['Email' => $Request->input('Email'), 'Password' =>$password]))
         {
            return ('ok');
         }
         return ('no');

any one help my to create custom login



via Chebli Mohamed

mercredi 15 mars 2017

LARAVEL 5.1 stripe create plan

im working on laravel 5.1 cashier and is thinking a way to create a plan without going to my stripe account.

5.1 documentation doesn't include creating plan but stripe has a documentation on creating one. i'm new to laravel and have no idea on what to require and use to make it work.



via Chebli Mohamed

how get all records using wherein?

this is my code , this code get only color and size without subcategory_id $products=Product::whereIn('color',array($request['color1'],$request['color2'],$request['color3'],$request['color4'],$request['color5'],$request['color6'],$request['color7'],$request['color8'],$request['color9'],$request['color10'],$request['color11'],$request['color12'])) ->whereIn('size',array($request['size1'],$request['size2'],$request['size3'],$request['size4'],$request['size5'])) ->whereIn('subcategory_id',array($request['type1'],$request['type2'],$request['type3'],$request['type4'])) ->get();



via Chebli Mohamed

Stripe Cashier ErrorException in StripeGateway.php line 71:

im using laravel 5.1 and followed the steps in http://ift.tt/1ZYkHtS

except for the provider need to 2 keys

'key'    => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),

i set it in my .env file as

STRIPE_KEY=@my_stripe_test_publishable_key
STRIPE_SECRET=@my_stripe_test_secret_key

my controller code is

$creditCardToken = $request->stripeToken; //from stripe documentation
//because the documentation didnt include how to get this variable

$user = User::find(1);

$user->subscription('monthly')->create($creditCardToken);

$user->trial_ends_at = Carbon::now()->addDays(14);

$user->save();  

an error appears everytime i try to subscribed. even without the $creditCardToken variable

ErrorException in StripeGateway.php line 71:

Argument 1 passed to Laravel\Cashier\StripeGateway::__construct() must be an instance of Laravel\Cashier\Contracts\Billable, instance of App\User given, called in C:\wamp\www\lifesaver\vendor\laravel\cashier\src\Laravel\Cashier\Billable.php on line 58 and defined



via Chebli Mohamed

Ajax doesn't work in laravel

ajax does't work in laravel

View/message.php 
<html>
<head>
  <title>Ajax Example</title>

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


  <script type="application/javascript">
     function getMessage(){
        $.ajax({
           type:'POST',
           url:'/getmsg',
           data:'_token = ',         dataType: 'json',
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script>

  <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>     

  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>

in above code i just click in button (Replace Message) and call ajax

Routes.php

Route::get('/ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');

AjaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use ajax;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AjaxController extends Controller {
public function index(){
  $msg = "This is a simple message.";
  return response()->json(array('msg'=> $msg), 200);
}
}

but it doesn't work it show error some like this POST http://localhost:8000/getmsg 500 (Internal Server Error)

Tutorial link



via Chebli Mohamed

mardi 14 mars 2017

Difficulties in creating update with Laravel 5.1

I'm trying to create an update with Laravel 5.1 but it shows the error:

I have 2 updates in this method and I noticed that the error already happens in the first one

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::update() must be of the type array, null given

My Controller

 public function update($id)
{


        $dadosForm = $this->request->except('_token');
        $dadosForm = $this->request->offsetUnset('fat_cnpj');
        $dadosForm = $this->request->offsetUnset('vatendimento');
        $dadosForm = $this->request->offsetUnset('integra');
        $dadosForm = $this->request->offsetUnset('material'); 

    $proposta = $this->proposta;

        $proposta->cliente_id = $this->request->get('cliente_id');
        $proposta->contato = $this->request->get('contato');
        $proposta->email = $this->request->get('email');
        $proposta->telefone = $this->request->get('telefone');
        $proposta->fatcnpj = $this->request->get('fatcnpj');
        $proposta->atendimento = $this->request->get('atendimento');
        $proposta->dt_solicitacao = $this->request->get('dt_solicitacao');
        $proposta->dt_vigencia = $this->request->get('dt_vigencia');
        $proposta->vendedor = $this->request->get('vendedor');
        $proposta->coleta = $this->request->get('coleta');
        $proposta->dt_integracao = $this->request->get('dt_integracao');
        $proposta->hr_integracao = $this->request->get('hr_integracao');
        $proposta->frete_material = $this->request->get('frete_material');
        $proposta->status_id = $this->request->get('status_id');  

        $this->proposta->where('id', $id)->update($dadosForm);




        $proposta_id = $id;

        $count = $this->ensaios->max('id');


        for($i=1;$i<=$count;$i++){ //Save Ensaios

        $proposta_ensaios = new PropostaEnsaios();

        $proposta_ensaios->id_proposta = $proposta_id;
        $proposta_ensaios->id_produto = $i;
        $proposta_ensaios->quantidade = $dadosForm['quantidade_'.$i];
        $proposta_ensaios->valor= $dadosForm['valor_'.$i];
        $proposta_ensaios->total = $dadosForm['total_'.$i];

        $proposta_ensaios->where('id', $id)->update($dadosForm);

        } 


    $this->request->session()->flash('alert-success', 'Dados Alterados com Sucesso!');
    return redirect()->route('manage-content');
}



via Chebli Mohamed

i just want to pass mail from my gmail account in laravel but it generate error

i just want to pass mail from my gmail account in laravel but it generate errors

my code:
Routes.php
Route::get('/sendbasicemai','MailController@basic_email');

i change in .env file as below
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=abx.xyz@gmail.com
MAIL_PASSWORD=******
MAIL_ENCRYPTION=null

and in config.php
array (
    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => '465',
    'from' => 
     array (
      'address' => NULL,
      'name' => NULL,
    ),
    'encryption' => NULL,
    'username' => 'abc.xyz@gmail.com',
    'password' => '*********',
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,
    ),

 MailController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MailController extends Controller
{
public function basic_email(){
   $data = array('name'=>"Virat Gandhi");

  Mail::send(['text'=>'mail'], $data, function($message) {
     $message->to('abc@xyz.in', 'Tutorials Point')->subject
        ('Laravel Basic Testing Mail');
     $message->from('abc.xyz@gmail.com','Virat Gandhi');
  });
  echo "Basic Email Sent. Check your inbox.";
  }
}

Mail.blade.php 
<h1>Hi, </h1>
<p>Sending Mail from Laravel.</p>

i am fresher in laravel and i just refere this link tutorial

but it generate bunch of errors: Whoops, looks like something went wrong. 1/1 Swift_TransportException in AbstractSmtpTransport.php line 383: ...... and much mor



via Chebli Mohamed

mb_internal_encoding() error after enabling in php.ini in Windows 10

I have php verison 5.6.8. I enabled php_mbstring.dll from php.ini. I have also php_mbstring.dll in extension folder. I enabled and restart apache and windows also. But I still get an error like this:

Call to undefined function Illuminate\Foundation\Bootstrap\mb_internal_encoding() in ..\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\LoadConfiguration.php on line 43

on Laravel 5.1 project. Also, I still not get mbstring section in phpinfo()? How can this be solved? Thanks in Advance.



via Chebli Mohamed

lundi 13 mars 2017

Missing Laravel Storage Folder

I'm currently in the process of trying to deploy a Laravel 5 application to an AWS Ec2 instance. I'm using Jenkins CI with the AWS Code Deploy plugin, but I seem to be having issues. It looks like the Storage folder is being completely excluded from the projects directory. IE completely missing. I decided to follow up and launch a base Laravel 5 app just to test. It still drops off the Storage folder. Anyone have any idea why the Storage Dir is being dropped from the build?



via Chebli Mohamed

dimanche 12 mars 2017

Save data with limit to 3 only?

Accessing database data and limit to 3 rows only.

I am new to laravel and i dont know how to limit access the rows.Anyone has idea how to get the result the ids 1-3 so that i will save it to my other table?

Sample range of grade to save. Only grades within this range should be save but limiting to 3 data only.

84 to 90

Scholar
id          grade
1            90
2            85
3            85
4            82
5            86
6            84
7            83
8            87
9            88
10           89


public function AddOrgaRequest(Request $request){

$test = new List;
some code   
$test->save();

return redirect()->back();
}



via Chebli Mohamed

Accessing email from MySQL db to be use for sending email

I have a problem with my message notification using email.Why is that it generates an error inside the foreach. The error is this part "$all_ngo" Undefined variable: all_ngo.

$pend = AddRequest::where('ship_id','=',$ship_id)->get();   
$all_ngo = [];
foreach ($pend as $id) {
    array_push($all_ngo, $id->ngo_id);
}

$orga_email  =  Auth::User()->orgainfo->orga_email;
$staffName  =   Auth::User()->orgainfo->inchargelname.' '. Auth::User()->orgainfo->inchargefname;  
$name = $scholars->scholar_fname.' '.$scholars->scholar_mname.' '.$scholars->scholar_lname;
$input =  array(
    'name' => $staffName,
    'email' => $orga_email,  
    'msgs' => 'asd' .' '. $name.'. '.'Hoping for your favorable response. Thank you!'
);
Mail::send('emails.mailMessage', $input,  function($message){
    $message->from('Somename@gmail.com');
    foreach ($all_ngo as $id3) {<-------Undefined variable: all_ngo
        $user = User::find($id3);
        $ngo_email2 = $user->ngo_email;
        $message->to($ngo_email2)->subject('Request For Sponsorship');
    }   
});



via Chebli Mohamed

How To make Validation URL contain foreign language Like Arabic symbols with Laravel

How To make Validation URL contain foreign language Like Arabic symbols with Laravel Like this http://ift.tt/2nirL7H



via Chebli Mohamed

samedi 11 mars 2017

Fetch contacts email address in Laravel

I am learning how to view gmail contacts and following this tutorial. http://ift.tt/2mvimcZ

As per the article below code fetches the contacts.

Url = 'http://ift.tt/2mwNjzb';
$result = json_decode($googleService->request(Url), true);
$emails = []; // initialize the new array
foreach ($result['feed']['entry'] as $contact) {
    if (isset($contact['gd$email'])) { // Sometimes, a contact doesn't have email address
        $emails[] = $contact['gd$email'][0]['address'];
    }
}

Here the problem is, it shows me even those email addresses to whom I sent emails. is there url that picks only contacts?



via Chebli Mohamed

How do I make a referral program in Laravel?

I am trying to create a program where other users can sign up using links of other already registered users. So, when one is referred, this is how the url would look like

http://ift.tt/2mczwKE // ref_id is existing user id

I am using the default Laravel auth. There is a hidden input value which would contain the value of ref_id if it exists. My database has a column called referred_by which is an INTand set to null by default. When someone registers using the link with ref_id, that id will get saved into that user row. But the problem is it's getting saved as null everytime.

This is how the validator looks like in Auth/RegisterController.php

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|max:40',
        'last_name' => 'required|max:40',
        'email' => 'required|email|max:255|unique:users',
        'account_name' => 'required|max:80',
        'account_number'=> 'required|max:15',
        'bank_name'=> 'required|max:30',
        'phone_number' => 'required|max:15',
        'ref_id' => 'nullable|numeric',
        'username' => 'required|max:15|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

and this is how the create method look like

protected function create(array $data)
{
    return User::create([
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'email' => $data['email'],
        'account_name'=> $data['account_name'],
        'account_number' => $data['account_number'],
        'bank_name'=> $data['bank_name'],
        'phone_number'=> $data['phone_number'],
        'username' => $data['username'],
        'referred_id' => (int)$data['ref_id'],
        'password' => bcrypt($data['password']),
    ]);
}

Since ref_id is saved in the hidden input field as a string, I tried converting it into an integer before putting into the database but I am not able to get it to work. I am really confused on how I can achieve this. Please help me. Thanks in advance.



via Chebli Mohamed

In laravel how to open webcamera and capture image and store it in database

In laraval I know how to upload a image by browsing In our system then by pressing a button the image was stored in the database. But now what I need is when a button is pressed I want my web camera to open then I want to capture a image when I press capture button and store it in database. Any help is most welcome.



via Chebli Mohamed

Unable to get data on Weekly Basis in Laravel 5.1

i am trying to get data from a table on Weekly basis, like i want to get total number of records registered on Monday, Tuesday an so on..
I am able to create a script in mysql and it works fine, i am also attaching the screen shot with this description,
but when i try to do the same in laravel then it throws an error:

Mysql Query (works fine):

SELECT HOUR(`created_on`) AS Hour, COUNT(*) AS calls
FROM  `buy_credits_requests`
GROUP BY HOUR(`created_on`)

Laravel Query (doesn't work)

$credits = \DB::table('buy_credits_requests')->where('status', '=', 1)->groupBy('Hour', 'ASC')
->get(['HOUR(created_on) AS Hour', 'COUNT(*) AS calls', 'state']);

Here is the screenshot.
Please help me to sort out this issue.

Thanks.



via Chebli Mohamed

vendredi 10 mars 2017

How to save bash_aliases profile when provisioning vagrant?

I am running Laravel's Homestead platform, with a Vagrant virtual machine. I have a bash_aliases file that has some custom aliases I would like to keep, however whenever I'm setting up a new project, it seems as though it gets erased back to default when you provision the machine. I would like to know how to get around this problem. I'm not sure if it's relevant, but I'm running macOS Sierra on a MacBook Pro.



via Chebli Mohamed

Update .env value via Laravel

Example, if my .env is

APP_ENV=local
APP_URL=http://localhost:8888/
APP_DEBUG=true

I know in Laravel we can do access our .env file by doing this

echo env('APP_ENV'); --> 'local'
echo env('APP_URL'); --> 'http://localhost:8888/'

but I wonder if there is a way to programmatically set it

Ex. env('APP_ENV') == 'production';



via Chebli Mohamed

Laravel exception handler not triggered in tests

I have inherited a large legacy app which has a laravel package written in Laravel 5.1. I am writing tests that use

$this->call('GET', 'my_route')

The tests execute fine but the exceptions being thrown in the tests are not being handled by the exception handler (which catches them and returns a JSON response). The exception handler is handling the exceptions correctly when using Postman.

The exception handler is being loaded in the base test file that my tests are extending using

$app->singleton(LaravelExceptionHandler::class, CustomExceptionHandler::class);

within the getEnvironmentSetUp function. This is the same line of code being used in another packages service provider that is using this same exception handler in the same app. (again Postman requests work fine)

This same setup is working nicely in an unrelated non-legacy Laravel 5.1 project so I am thinking there is either another package interfering or there is some laravel function that is messing up the testing/console environment such as

set_error_handler();
set_exception_handler();

Im trying to locate the functions / env variables that can interfere with testing and the test environment as they could have been tampered with.



via Chebli Mohamed

Can't access values of Laravel's JSON response object

This might be one of the strangest bugs I've encountered.

In my controller, when a user makes a reply (through AJAX), I return a JSON response in an attempt to get the ID of that reply.

$reply = Status::create([
    'body' => $replyText,
])->user()->associate(Auth::user());

$status->replies()->save($reply);

$replyID = $reply->id;

return response()->json([
    'replyID ' => $replyID
]);

This works fine. I get a JSON reponse with what I asked for. Great.

enter image description here

Now here's the problem. For WHATEVER reason, I can't access the values of the object JSON is returning.

x = response.replyID;
console.log(x);

or

x = response["replyID"];
console.log(x);

or any variation of that will ALWAYS returned undefined.

To illustrate how stupid this is, let me demonstrate with the following:

success: function(response) {
    myObj = { "age":30 };
    console.log(response);
    console.log(myObj);
    x = myObj.age;
    y = response.replyID;
    console.log(x); 
    console.log(y);             
},

This returns:

enter image description here

What could POSSIBLY be causing this?



via Chebli Mohamed

jeudi 9 mars 2017

Middleware in laravel does not works properly

when i am trying to apply middleware on my routes like:

Route::get('twitterlogin','TwitterController@gettwitterlogin'); Route::post('twitterlogin','TwitterController@posttwitterlogin'); Route::group(['middleware'=>'auth'],function() { Route::get('twitternewsfeed','TwitterController@gettwitternewsfeed'); Route::post('postimage','TwitterController@postimage'); Route::post('posttweet','TwitterController@posttweet'); Route::get('twitterlogout','TwitterController@gettwitterlogout'); Route::post('editprofilepic','TwitterController@posteditprofilepic'); Route::post('searchuser','TwitterController@postsearchuser'); Route::post('edittweet{id}','TwitterController@postedittweet'); Route::get('deletetweet{id}','TwitterController@getdeletetweet'); Route::post('editprofile','TwitterController@posteditprofile'); Route::get('userprofile{email}','TwitterController@getuserprofile'); });

And when i am trying to submit my login form it does not bring me on next page it again opens the login page....what is the exact problem in this.My authenticate middleware is as follows....

namespace App\Http\Middleware;

use Closure; use Illuminate\Contracts\Auth\Guard;

class Authenticate { /** * The Guard implementation. * * @var Guard */ protected $auth;

/**
 * Create a new middleware instance.
 *
 * @param  Guard  $auth
 * @return void
 */
public function __construct(Guard $auth)
{
    $this->auth = $auth;
}

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('twitterlogin');
        }
    }

    return $next($request);
}

}



via Chebli Mohamed

Send recently saved data from controller to DOM in Laravel

On my website, users can reply to statuses.

$reply = Status::create([
        'body' => $replyText,
    ])->user()->associate(Auth::user());

status->replies()->save($reply);

The request is sent through AJAX. If the request succeeds, the reply is generated automatically on the DOM without a page redirect.

And that's cool and all, but I also want users to be able to delete/edit replies they just made! And for that, I would need the ID in my status table of the newly created reply.

Something like...

$reply = Status::create([
        'body' => $replyText,
    ])->user()->associate(Auth::user());

$status->replies()->save($reply);

$replyID = ID of the status I just saved to database;
return response()->json($replyID);



via Chebli Mohamed

mercredi 8 mars 2017

Order collection of array objects

After making some queryes i have a collection of array objects. But after orderByDesc the data transform in hole objects, instead of how it was (array of objects), what it happened? Is like the method orderByDesc tranform the collection in another type.

Ex: some logic code, queries...etc in the end

return $total->sortByDesc('date');

After using sortByDesc:

enter image description here

Before to sortByDesc: enter image description here

Now that is in type of objects is giving some issues working with it in my javascript application (angularjs), it not a array of objects how should it be.



via Chebli Mohamed

Create a new and custom collection

In my app im getting a array of objects, from the table, and in the table i get the information regarding each object, but i need to create a new collection with specific name properties but with the values from the collection i went and get. How can i create a new custom collection from the old one i got from DB?

my code:

$conditions = collect($user->conditions()
->withTrashed()
->orderBy('updated_at', 'desc')
->get());

Example of how i was trying do do:

$newCollection =  $conditions->map(function ($condition) {
           unset($condition['condition_privacy']);
           unset($condition['condition_privacy_id']);
           unset($condition['discount_type']);
           unset($condition['id']);
           unset($condition['condition_privacy']);
           unset($condition['proponent']);
           unset($condition['simplified_laboratory']);
           unset($condition['simplified_laboratory_id']);
           $condition['new_property'] = 'some data';
            return $condition;
        });

But this way above is not quite good, i prefer in instead removing the properties from the original, i wish to create a new collection with new properties and getting values from the old collections.

note: Im using laravel 5.1.



via Chebli Mohamed

Laravel Cashier Call to Undefined Method onGracePeriod()

So I recently upgraded from Laravel 5.1 -> 5.4 and Cashier from 5.0 -> 7.0. In my blade I am using this check to see if a user is in their grace period

<?php if(Auth::check() && Auth::user()->onGracePeriod()): ?>

However now this code throws an exception

Call to undefined method Illuminate\Database\Query\Builder::onGracePeriod()

As per the documentation my user model has the import

use Laravel\Cashier\Billable;

and the use statement inside of the class itself

class User extends Model implements AuthenticatableContract, 

CanResetPasswordContract
{
     use Authenticatable, CanResetPassword, Billable;
    /**
     * The database table used by the model.
     *
     * @var string
...

Is there anything else that could cause this error? Searching through the code it looks like the function is within the Subscription.php within cashier but I cannot seem to find a fix. I also have the included dates that is often referenced in the documentation

protected $dates = ['trial_ends_at', 'subscription_ends_at'];

But I had that and my DB using that before back on 5.1 so I doubt that is related. Any ideas? The only thing I can think of is that when moving from 5.1 -> 5.4 I had to remove the "BillableContract" since it appears that it is no longer being used, is there something I have to replace that with? Thanks!



via Chebli Mohamed

What to choose to use to determine the relationship?

I have 3 tables 1) table city (500 000 records) 2) table post (A city can have many posts) 3) table post_text (To store the text of the post)

table city has fields ID, NAME table post has fields ID, CITY_ID, POST_ID table post_text has fields TITLE, TEXT

What to use? Polymorphic? Through? Something else?



via Chebli Mohamed

mardi 7 mars 2017

Laravel - Sending Emails Through Exchange Server

For my Laravel 5.1 app, I have an on-premise Exchange server and user account that I want to sent emails through. Below are the values in my .env file:

MAIL_DRIVER=smtp
MAIL_HOST=[IP ADDRESS]
MAIL_PORT=587
MAIL_USERNAME=[USERNAME]
MAIL_PASSWORD=[PASSWORD]
MAIL_ENCRYPTION=null

I get an error when using tls as the encryption value and just for the sake of testing, I've been using null for now. But then I get the error of Failed to authenticate on SMTP server with username "*******" using 1 possible authenticators

I'm unsure of where I should start for troubleshooting. It seems that it's using NTLM Authentication for verifying the credentials. Should I check the Exchange server to see if it's set up for that? The credentials I used are correct. Or is there something wrong with my config?

Thanks in advance.



via Chebli Mohamed

I am trying to insert loop data into database but it is giving an error

i am trying to insert loop data into database with laravel but it is giving the following error:

ErrorException in Grammar.php line 118: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\laravel\App\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 678 and defined

View:

<input name="product_id[]" type="hidden" class="rid" value="13">
<input type="hidden" name="product_name[]" value="Popins"><input type="hidden" name="product_code[]" value="2323">
<input name="unit_price[]" type="hidden" value="170">
<input name="quantity[]" type="text" value="2" id="" >

Controller

for($i=0; $i<count($product_name);$i++){
$newSafety = new saleItems;
        $newSafety->product_id = $request->unit_price;
        $newSafety->sale_id   = $request->unit_price;
        $newSafety->product_code   = $request->product_code;
        $newSafety->product_name   = $request->product_name;
        $newSafety->quantity   = $request->quantity;
        $newSafety->unit_price   = $request->unit_price;
        $newSafety->gross_total= $request->unit_price;
        $newSafety->save();

        }



via Chebli Mohamed

lundi 6 mars 2017

Upgraded Laravel 5.1 to 5.2, CSRF and Sessions not persisting on request

So I decided to upgrade from Laravel 5.1 to 5.2 and in the process my user authentication has broken. I use database sessions and I upgraded them as per the instructions from Laravel. (See "Sessions" section) and it is saving to the DB. However when I try and login it resets my CSRF and erases my session. In fact I have noticed that every time any request happens (even ajax) it will update with a new session. Attempting to login creates 5 sessions for me and does not log me in, any ideas?



via Chebli Mohamed

Add custom 500 error page only for production in Laravel

I want to have a custom 500 error page. This can be done simply by creating a view in errors/500.blade.php.

This is fine for production mode, I no longer get the default exception/ debug pages when in debug mode.

Therefore, my question is: how can I have a custom 500 error page for production, but the original 500 error page when debug mode is true?



via Chebli Mohamed

dimanche 5 mars 2017

two integer column merge and sortBy using laravel 5.1

in laravel 5 how to sortBy and merge two column i have column "price" and "price_sale" both are integer. i want to ascending or descending price and price_sale together return as collection. thanks you



via Chebli Mohamed

samedi 4 mars 2017

simplexml_load_file() error is showed some every X hours

I have an Ubuntu 16.04 server, there I installed PHP7+Nginx+MySQL. Also I have a web application developed in Laravel 5.1 in which I take some uploaded files (by the user, they content XML) and read them, I use xml_load_file() to do this, in my local environment everything work great! Then, in the server when I just cloned the project there I noticed than that function was not working, instead it returned this error:

simplexml_load_file(): I/O warning : failed to load external entity &quot;/tmp/phpSFeOBP&quot;

So, I researched and noticed that I had to enable allow_url_fopen in the php.ini file, so I did it and restarted the server using:

sudo systemctl restart php7.0-fpm

And then it started to work great, but, something strange it happening now, every some hours the server gives the error, and I have to be restarting the php7.0-fpm over and over again, and the php.ini file is the same, it's not modified, so I don't really know what is,what should I do or even why is happening.

To be more especific, this is the code that I have in my project to read the file (and the file exist,so it's not the problem):

ini_set('allow_url_fopen', 'on');//I set this to ensure,but nothin happens
$xml = simplexml_load_file($file);



via Chebli Mohamed

Generating a report in Laravel times out - make it more efficient

Lately I've been having to download the database and run this script locally in order to make it work. I could probably get into the server and allocate more memory but I'd rather improve the script if possible. There must be a more efficient way.

I have a table of invoices with orders which contain have items. I need to pull up all invoices in a certain date range that have orders which have items where tax was collected. The script below works, but takes forever and times out on the live server, only runs on my dev machine.

        $invoices = \App\Invoice::whereHas('orders', function($q)
        {
            $q->whereHas('items', function($q)
            {
                $q->where('tax_billed', '>', '0');
            });
        });             
        $invoices->whereBetween(session('report.datesearch'), [session('report.search_date_start'), session('report.search_date_end')]);
        $invoices = $invoices->get();

I thought maybe I can go the other way, and find all items where tax_billed > 0, but then how do I pare that down by the invoice date, which is stored two tables up the parental chain in the invoices table?

Relationships:

class Invoice extends Model {
    public function orders()
    {
        return $this->hasMany('App\Order', 'invoice_id') -> orderBy('created_at', 'asc');
    }
}

class Order extends Model {
    public function items() {
        return $this -> belongsToMany('App\Item', 'order_item', 'order_id', 'item_id')-> withPivot('id','variant_id','quantity','quantity_received','quantity_delivered','notes', 'createdby_user_id', 'weight', 'cost_billed', 'tax_billed', 'tax_rate', 'calc_by_weight', 'track_units')->orderBy('name');
    }
}

and the obvious reverse: ITEMS belongsTo ORDERS belongsTo INVOICES



via Chebli Mohamed

vendredi 3 mars 2017

Created_at or updated_at not displaying full dateTime

In my laravel app i need to compare 2 dateTime, the created_at and the updated_at, but i notice that when i call this properties of the record is not disaplayed the seconds, onlu hour and minutes, i need to get the seconds, what i need to change or include to show all info? I beend checking on the documentation and didnt found anything.

Ex:

$calculation->created_at

output:

2017-03-03 21:03

And in database is:

2017-03-03 21:03:22



via Chebli Mohamed

Response to preflight request doesn't pass access control check Laravel and Ajax call

I have a REST api made in Laravel 5.1 hosted in a remote server. Now, I', trying to consume that API from another website (that I have in local).

In Laravel I set the required lines to send the CORS headers. I also tested the API using Postman and everything seems to be ok!

In the Frontend

Then, in the website I sent the POST request using ajax, with this code:

var url="http://ift.tt/2mUN9Py";
var data=$("#my-form").serialize();
    $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    headers: { 'token': 'someAPItoken that I need to send'},
                    success: function(data) {
                        console.log(data);
                    },
                    dataType: "json",
                }); 

Buy then I get this error in the console:

XMLHttpRequest cannot load http://ift.tt/2mUN9Py. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

In the Backend

In the API I set this (using a Laravel Middleware to set the headers):

return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

So, I'm confused about where is exactly the problem.

  1. In the server? but then why with Postman work fine?
  2. Is in the Ajax call? so, then what should I add?


via Chebli Mohamed

Rearrange columns in a Laravel migration file

How do I re-arrange a column in a Laravel migration file for a MySQL database?

So far I have the following:

$table->date('foo')->after('bar')->change();

However, it does not seem to re-arrange the column.

Why not and how can I fix this?



via Chebli Mohamed

laravel Expected response code 250 but got code "530"

Im trying to Mail in Laravel 5.1

my mail.php code is

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

 ];

my .env file is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=null

my function to email is

public function sendEmailVerification()
{
    $user = $this->user;//retrieved by $request->user() in __construct

    Mail::send('emails.verifyemail', ['user' => $user], function ($m) use ($user) {
        $m->from('myemail@gmail.com, 'sample');

        $m->to($user->email, $user->name)->subject('Verify Email');
    });
}

Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. l188sm21749863pfl.28 - gsmtp" error appears every time i call my function.



via Chebli Mohamed

jeudi 2 mars 2017

Method save does not exist occur after lockForUpdate Laravel 5.1

Laravel Cannot Save data to DB after Pessimistic Locking

I am facing the problem that cannot update data to db while using save method with Laravel 5.1.

I am trying to update data with locking to avoid concurrency data and below is my code.

Please help me.

namespace App\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
class Recharge extends Model
{
public function processSuccess($orderId, $type, $amount) {
        $query = [
            ['status', '<=', 1],
            ['order_abm', '=', $orderId],
            ['type', '=', $type],
            ['amount', '=', $amount],
        ];

        \DB::beginTransaction();
        $concur_up = Recharge::where($query)->lockForUpdate()->get();
        $concur_up->status = 5;
        $concur_up->amounted = $amount;
        $concur_up->date    = time();
        $res =$concur_up->save();
        if (!$res) {
            return "fail";
        }
        \DB::commit();
        return true;
    }
}

error shown in my editor

enter image description here

error shown in my browser

enter image description here

My using table

enter image description here



via Chebli Mohamed

I Think there is a Bug with Laravel 5.4?

i'm trying to send a email with Attachment File , It Work Perfectly when i'm using an externale link like :

public function build() 
{ return $this->view('email.test') ->attach("http://ift.tt/2ljrDaY"); }

But when i try to send Files that stored on my Storage Folder like :

public function build() 
{ return $this->view('email.test') ->attach("http://ift.tt/2lF2Jyr"); }

, it Thrown an Eroor :

Swift_IoException in FileByteStream.php line 144: Unable to open file for reading

i had already generated a Storage:LINK , that allow to me to access to Storage Folder and i can access to it via url ( http://ift.tt/2ljrCnq ) ,

Please Help me What should i do ? it's been 3 days i'm trying to resolve this problem and nothing Found :/



via Chebli Mohamed

mercredi 1 mars 2017

how get views number for my website in laravel 5.1?

my code : but always views number are 1 public function getLandPage() {

    if(is_null(Session::get('views_number'))){
        Session::put('views_number',1);
    }else{
        $c=Session::get('views_number');
        $c++;
        Session::put('views_number',$c);
    }

    return dd( Session::get('views_number'));
}



via Chebli Mohamed

Laravel blank white screen after modification

My laravel site working well. But after modification i faced with a blank white screen and no logs.

If I run below command :

php -cli artisan clear-compiled

I have this error :

Fatal error: Uncaught exception 'ReflectionException' with message 'Class log does not exist' in /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php:734 Stack trace: #0 /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php(734): ReflectionClass->__construct('log') #1 /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php(629): Illuminate\Container\Container->build('log', Array) #2 /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(697): Illuminate\Container\Container->make('log', Array) #3 /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php(849): Illuminate\Foundation\Application->make('Psr\Log\LoggerI...') #4 /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php(804): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter)) #5 /data/devPhp/workspac in /data/devPhp/workspace/adhesion/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 734



via Chebli Mohamed

TokenMismatchException in VerifyCsrfToken.php line 53

i made a page view/maessage.php
http://ift.tt/1yCEpkO">

  <script>
     function getMessage(){
        $.ajax({
           type:'POST',
           url:'/getmsg',
           data:{'_token': ''},
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script>   
  <body>
   <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>
  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>
  </body>

in routes.php

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

Route::post('/getmsg','AjaxController@index');

in AjaxController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

class AjaxController extends Controller
{
   public function index(){
  $msg = "This is a simple message.";
  return response()->json(array('msg'=> $msg), 200);
   }
}

when i ran http://localhost:8000/ajax http://localhost:8000/getmsg generate below error

Whoops, looks like something went wrong.

1/1 MethodNotAllowedHttpException in RouteCollection.php line 218: in RouteCollection.php line 218 and buch of error.....

but when i saw in consol it show below error TokenMismatchException in VerifyCsrfToken.php line 53: in VerifyCsrfToken.php line 53

i can't understand error .i am fresher in laravel. and i aactually don't know the meaning of '_token': '' in message.php. pls. help to solve this error.



via Chebli Mohamed