lundi 25 décembre 2017

laravel5.4 I can't get login , when i try to login it always redirect to same login page

Web.php

Route::get('/' , ['as' => '/' , 'uses'=> 'loginController@getlogin']);
Route::post('/login', ['as' => 'login', 'uses'=> 'loginController@postlogin']);

Route::group(['middleware' =>['authen']],function (){
Route::get('/logout' ,['as'=>'logout', 'uses'=> 'loginController@getLogout']);
Route::get('/dashboard',['as'=>'dashboard', 'uses'=> 'dashboardController@dashboard']);});

dashboardController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class dashboardController extends Controller
{
   public function __construct(){
    $this->middleware('web');
   }
   public function dashboard(){
    return view('layouts.master');
   }
}

loginController

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
class LoginController extends Controller{
     use AuthenticatesUsers;
     protected $username = 'username';
     protected $redirectTo = '/dashboard';
     protected $guard = 'web';

     public function getLogin(){
        if(Auth::guard('web')->check()){
           return redirect()->route('dashboard');
        }
        return view('login');
     }

     public function postLogin(Request $request){
         $auth = Auth::guard('web')->attempt([
            'username' => $request->username,
            'password' => $request->password,
            'active' => 1
          ]);

          if($auth){
             return redirect()->route('dashboard');
           }
           return redirect()->route('/');
     }

     public function getLogout(){
        Auth::guard('web')->logout();
        return redirect()->route('/');
     }
}

Authen.php

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authen
{
public function handle($request, Closure $next ,$guard ='web'){
    if (!Auth::guard($guard)->check()){
      return redirect()->route('/');   
    }
      return $next($request);
    }
}

CheckRole

<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
     public function handle($request, Closure $next){
         $roles = $this->getRequiredRoleForRoute($request->route());
         if($request->user()->hasRole($roles) || !$roles){
            return $next($request);
         }
          return redirect()->route('noPermission');
      }

      private function getRequiredRoleForRoute($route){
          $actions = $route->getAction();
          return isset($actions['roles']) ? $actions['roles'] : null;     
      }
}

when i try to login it redirect to the same page i.e login page , i spent lots of hour to solve this problem but i can't please someone help me . i want to redirect dashboard through login page . but it is not happen . there is no error shown and i cant go on dashboard page too.Please help me to solve this problem. Thanks so much.



via Chebli Mohamed

dimanche 24 décembre 2017

sending error message laravel required inputs

so i wanted to make validation to my register form so i made all my inputs required so i can test my validation that it works or not, so this is what i used in my controller

$Message = [
        'required' => 'This input is required',
    ];
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required',
        'password' => 'required',
        'UserName' => 'required',
        'Phone' => 'required',
        'SSN' => 'required',
        'SDT' => 'required',
        'Country' => 'required',
        'InsuranceAmount' => 'required',
        'City' => 'required',
        'Location' => 'required'
    ], $Message);

    if ($validator->fails()) {


        return redirect('/admin/users/create')
            ->withErrors($validator)
            ->withInput();
    }

    $user = new User;
    $user->name = Input::get('name');
    $user->email = Input::get('email');
    $user->password = bcrypt(Input::get('password'));
    $user->UserName = input::get('UserName');
    $user->Phone = input::get('Phone');
    $user->SSN = input::get('SSN');
    $user->SDT = input::get('SDT');
    $user->Country = input::get('Country');
    $user->City = input::get('City');
    $user->Location = input::get('Location');
    $user->save();
    return Redirect::to('/admin/users')->with('message', 'User Created');

Now if theres no errors it works fine and redirect to user list, but if a input is empty it will just redirect to the creation page whict is what i wanted but the problem is it won't send the error message with the redirect i tried dd the validator and it has all the messages fine heres my view

<form class="form-horizontal" role="form" method="POST" action="">
                    {!! csrf_field() !!}

                    <div class="form-group">
                        <label class="col-md-4 control-label">الاسم</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="name" value="">

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

                    <div class="form-group ">
                        <label class="col-md-4 control-label">اسم المستخدم</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="UserName" value="">
                            @if ($errors->has('UserName'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group ">
                        <label class="col-md-4 control-label">رقم الجوال</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="Phone" value="">
                            @if ($errors->has('Phone'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif

                        </div>
                    </div>

                    <div class="form-group ">
                        <label class="col-md-4 control-label">الرقم الوطني</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="SSN" value="">
                            @if ($errors->has('SSN'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group ">
                        <label class="col-md-4 control-label">نوع الوثيقة</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="SDT" value="">
                            @if ($errors->has('SDT'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group ">
                        <label class="col-md-4 control-label">الدولة</label>

                        <div class="col-md-6">
                            <select class="form-control" name="Country">

                                <option>الاردن</option>
                            </select>

                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label">المدينة</label>

                        <div class="col-md-6">
                          <select class="form-control" name="City" >
                              <option>عمان</option>
                          </select>

                        </div>
                    </div>

                    <div class="form-group ">
                        <label class="col-md-4 control-label">اسم الشارع</label>

                        <div class="col-md-6">
                            <input type="text" class="form-control" name="Location" value="">
                            @if ($errors->has('Location'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group ltr-input">
                        <label class="col-md-4 control-label">البريد الإلكتروني</label>

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

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

                    <div class="form-group ltr-input">
                        <label class="col-md-4 control-label">كلمة المرور</label>

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

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

                    <div class="form-group ltr-input">
                        <label class="col-md-4 control-label">تأكيد كلمة المرور</label>

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

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

                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary pull-right">
                                <i class="fa fa-btn fa-user"></i> تسجيل
                            </button>
                        </div>
                    </div>
                </form>

and btw this is laravel 5.1



via Chebli Mohamed

samedi 23 décembre 2017

Laravel Has anyone been able to use GMAIL API, OUTLOOK API and Yahoo Mail API together?

I am looking to build an email reading and message sending app with Laravel 5.1. I don't want to use IMAP or POP3. Instead, I would like to use GMAIL API, OUTLOOK API and Yahoo Mail API for both logins using Oauth and accessing user email accounts. Is there a Laravel module or a service that can do that?



via Chebli Mohamed

vendredi 22 décembre 2017

Need help in optimising Laravel Mysql query

Can anyone help me out in explaining this below query in detail? This is part of my project which i got to debug. i need help to understand it and optimise this.

$query = seller::selectRaw("seller.name, seller.group_id,seller.group_id_string, seller.pay,( 
    SELECT SUM( IF( t.retail_cost >0
    AND t.submitted_group_plan >1, 1 , -1 ) ) AS trans_number
    FROM money AS t
    JOIN  `seller` AS d ON  `t`.`submitted_group_plan` =  `d`.`group_id` 
    WHERE 
    (
        (
        t.`claim_date_and_time` >=  '01-01-2015'
        AND t.`claim_date_and_time` <=  '01-01-2016'
        AND t.commissionable =  'Y'
        AND t.`submitted_group_plan` = d.group_id
        )
        OR 
        (
            (t.commissionable IS NULL)
            AND 
            (t.claim_type_code IS NULL)
            AND
            (t.claim_date_and_time IS NULL)
        )
    )
    AND d.id = seller.id)
    as trans_number");  

MYSQL VERSION OF ABOVE QUERY:

SELECT seller.name,
       seller.group_id,
       seller.group_id_string,
       seller.pay,

  (SELECT SUM(IF(t.retail_cost >0
                 AND t.submitted_group_plan >1, 1, -1)) AS trans_number
   FROM money AS t
   JOIN `seller` AS d ON `t`.`submitted_group_plan` = `d`.`group_id`
   WHERE ((t.`claim_date_and_time` >= '01-01-2015'
           AND t.`claim_date_and_time` <= '01-01-2016'
           AND t.commissionable = 'Y'
           AND t.`submitted_group_plan` = d.group_id)
          OR ((t.commissionable IS NULL)
              AND (t.claim_type_code IS NULL)
              AND (t.claim_date_and_time IS NULL)))
     AND d.id = seller.id) AS trans_number
FROM `seller`



via Chebli Mohamed

mercredi 20 décembre 2017

How to calculate between hours from current date to pickupdate in Laravel

How to calculate between hours from current date to pickupdate. I have pickup date and pickup Time from Input. below function returns wrong value.

$bookingtime=strtotime($request->input('pickupdate_submit')." ".$request->input('pickuptime_submit') );

        $curentdate=date('Y-m-d HH:i');
        $curenttime=strtotime($curentdate);

        $betweenhours = abs($bookingtime - $curenttime) / 3600;



via Chebli Mohamed

lundi 18 décembre 2017

Change Login Table in Laravel 5.5

I have two table one is "clUser" in which i am storing email id, another table name "clLogin" in which i am storing Password. How to change laravel default login with these two table.



via Chebli Mohamed

mardi 12 décembre 2017

Update form only if there is some change in the input fields

How to determine in update() method of a controller in a laravel project if there is any change in the input? I need to update form only if there is any change in the input fields.



via Chebli Mohamed

lundi 11 décembre 2017

Laravel 5.1 I cant update model $user

I have this function where I want to update user background image so I write:

public function updateBg(Request $request)
    {
        $user = Auth::user();
        $this->validate($request, [
            'background' => 'image|max:10000',
            // validate also other fields here
        ]);
        // checking file is valid.
        if (!$request->file('background')->isValid()) return redirect()->back()->withErrors(["background" => "File is corrupt"]);

        // file is valid
        $destinationPath = public_path().'/images/Custaccounts/'.$user->id; // upload path
        $extension = $request->file('background')->getClientOriginalExtension(); // getting image extension
        $ran = str_random(5);
        $photo  = $ran.'.'.$extension;

        $request->file('background')->move($destinationPath, $photo); // uploading file to given path

        $bg = $user->id.'/'.$photo;
dd($bg);
        $user->update(['background' => $bg]);

        return Redirect::back();

            }

this line wont work: $user->update(['background' => $bg]); dd($bg) give me right string and image is uploaded just I cant update my 'background; field ...

also when I write:

    $user->update(['background' => $bg, 'name'=>'John']);

name is updated but background not... at user model background field is fillable of cource



via Chebli Mohamed

dimanche 10 décembre 2017

How to access passed data inside a redirect route from blade template

I have a method that redirect to a route like this with a data passed inside it:

return redirect('vendors')->with('vendor',$allvendors);

and i want to access the data that i passed from a blade template that the redirect is pointing to, so i did something like this:

@foreach($vendor as $vendors)

but i am getting this error:

Undefined variable: vendor (View: /opt/lampp/htdocs/easyhire-web/resources/views/vendor/vendors.blade.php)

I rely don't know what i am doing wrong, but when i return a view with that same data, it will work but if i change it to redirect, it will give error. any help out there?



via Chebli Mohamed

jeudi 7 décembre 2017

Laravel 5: Store artisan console table output in a variable

In Laravel 5 console commands, you can output a table like so:

$this->table($headers, $tableData);

This is described here: http://ift.tt/2j4EAW2

However this outputs it straight to the console.

How can I store it in a variable without sending the data to the console.



via Chebli Mohamed

mercredi 29 novembre 2017

In laravel eloquent create method i am not able to save the data in database

I have Three model -> Language-> Article-> Category.. Article table has two Foreign Key category_id & Language_id, Language-Model has "One to Many" Relationship with Article-Model, Similarly Category-Model has "One to Many" Relationship with Article-Model.

Category- Model

class Category extends Model
            { 

            protected $fillable = [
                 'category_name', 
            ];

            public function articles(){

                return $this->hasMany('App\Article');
             }
           }

Language-Model

class Language extends Model
    {
         protected $fillable = [
            'language_name'
        ];

         public function articles(){

            return $this->hasMany('App\Article');
        }

    }

Article _model

class Article extends Model
{
 protected $fillable = [

   'language_id','category_id','category_name','article_title',
   'article_desc','source_from','source_url','video_link',
   'audio_url','author_name','article_image_url','like_count'
    ];

    public function languages(){

        return $this->belongsTo('App\Language');
    }

    public function categories(){

        return $this->belongsTo('App\Category');
    }

}

How to insert in the database using laravel Eloquent

 $Article = new Article (
                 [
                   'article_image_url' => $img_url ,
                   'audio_url' => $audio_url,
                   'category_name'=>$category_name ,
                   'article_title'=>$request->article_title,
                   'article_desc'=>$request->article_desc,
                   'source_from'=>$request->source_from,
                    'source_url'=>$request->source_url,
                    'video_link'=>$request->video_link,
                    'author_name'=>$request->author_name,
                    'like_count'=>'0',

                  ]
            );

            $language = new Language;
            $category = new Category;
            $language->articles()->save($Article);

since language_id doesn't have a default value it is foreign key please help me out with this



via Chebli Mohamed

mardi 28 novembre 2017

output only updated after second form submit

I have a from with an input that filters a database query by a string. Often, but strangely enough not always, I have to send this form twice to get updated data after changing the filter string. The filter string is updated upon sending the form in because I flash the request. So that part works.

In between sending the forms there is also an ajax call to the same route (json return). Maybe that is mixing something up with the csrf tokens?

Why is the data not updated? It seems it is cached? I followed the basic tutorial. (I know the code is not perfect, it's my first laravel project)

Here is the route: (I change the real name of the model to "Model")

Route::get('myRoute', ['as' => 'myRoute', function (\Illuminate\Http\Request $request) {
    $request->flash();
    $model = new \App\Model();

    if($request->accepts('text/html')) {
        if($request->has('filter')) {
            $searchString = $request->filter;
        } else {
            $searchString = '';
        }
        return view('myView', [
            'searchString' => $searchString,
            'models' => $model->getModels()
        ]);
    } elseif($request->accepts('application/json')) {
        return response()->json($model->getModels());
    }
}]);

And here the relevant part of the Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Model extends Model
{
    public function getRequests()
    {

        if (request()->has('filter')) {
            return $this->searchByFilter();
        }

        if (request()->has('email')) {
            return $this->searchByEmail();
        }
    }

    private function searchByFilter()
    {
        $filter = request();
        if (is_null($filter)) {
            return $this->orderBy('created', 'asc')->get();
        }
        return $this->selectRaw(
            "*, MATCH(
                    something
                ) AGAINST ('{$filter}' IN NATURAL LANGUAGE MODE) as relevance")
            ->whereRaw("MATCH(
                            something
                        ) AGAINST ('{$filter}' IN NATURAL LANGUAGE MODE)")
            ->orderBy('relevance', 'desc')
            ->limit(25)
            ->get();
    }
}

The view is very simple:

@if (!is_null($models))
    @forelse ($models as $key => $model)
        <div></div
    @empty
        <p>no results.</p>
    @endforelse
@else
    <p>please filter something.</p>
@endif



via Chebli Mohamed

lundi 27 novembre 2017

Dynamic Bootstrap-date-picker-sandbox highlight specific date

Currently in a Calendar i am setting background color on static date. In my for loop i am getting array:

// BookeData loop 
@if(!empty($BookeData))
        @foreach($BookeData as $key => $value)
            // getting single venue booked date 
            // Flag : 1 - for 1st half, 2 - for 2nd half and 3 - for full day 
        @endforeach
@endif

On below script i want to set it dynamically , on a booked date and $value->session == 1 then apply gradient css red and green..if session value 2 vice versa css apply..if 3 apply full colour css.

My Script which is working on static date is

<script type="text/javascript">
var booked_date = ["27-11-2017","27-11-2017"]; 
$("#datepicker").datepicker({
 format: "dd/mm/yyyy",
 autoclose: true,

    beforeShowDay: function(date){
    var d = date;
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    var formattedDate = curr_date + "-" + curr_month + "-" + curr_year
    if ($.inArray(formattedDate, booked_date) != -1){
       return {
          classes: 'activeClass'
       };
     }
  return;
}
});

Active class css

.activeClass{
  background: -webkit-linear-gradient(red, yellow); 
  background: -o-linear-gradient(red, yellow); 
  background: -moz-linear-gradient(red, yellow);  
  background: linear-gradient(red, yellow);  

}

How can i do this dynamically on my array.!! Thanks in advance.



via Chebli Mohamed

L5.1 - Command with localization not working (not in Ubuntu but yes on Mac)

I have a command called SendReminders, when I change the locale with App::setLocale('locale') it looks like is working because when I do App::getLocale() returns the correct one, but when I call for a translation returns always the default localization.

This is my SendReminders class:

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;

use App;
use Exception;
use Storage;
use Lang;

class SendReminders extends Command
{

    protected $signature = 'send:reminders';

    public function __construct(){
        parent::__construct();
    }

    public function handle(){

        App::setLocale('EN');
        echo App::getLocale()."\n"; // <= Shows correctly 'EN'
        echo Lang::get('general.contact')."\n"; // <= Shows correctly 'Contact'

        App::setLocale('DE');
        echo App::getLocale()."\n"; // <= Shows correctly 'DE'
        echo Lang::get('general.contact')."\n"; // <= Doesn't show the correct value

    }

}

I'm missing something to make the localization work?

EDIT:

Some estrange behavior is happening because on my Mac is working but on Linux (Ubuntu) is not, looks like is not finding my folder /resources/lang/de/



via Chebli Mohamed

vendredi 24 novembre 2017

i am trying to show affiliate program banner in laravel 5.1 with widgetify liabrary, but it is not showing banner

I am just trying to show banner of affiliate program in laravel 5.1. But its not showing that banner.As per google search i found widgetify package and implemented it successfully but still unable to view banner with this html and script code.

This is my code to show banner:

<div data-WRID="WRID-151136341816463865" data-widgetType="productBanner" data-class="affiliateAdsByFlipkart" height="240px" width="120px"></div>
<script async src="//affiliate.flipkart.com/affiliate/widgets/FKAffiliateWidgets.js"></script>

and when i am print it in wordpress its working fine.



via Chebli Mohamed

jeudi 23 novembre 2017

response with appropriate mime type requested with accept

Say I have a route:

Route::get('list',...);

If I call that route with Accept: text/html it should return a view with all the blade hoopla. If I call that route with Accept: application/json it should return json, Accept: application/xml it will return xml. And so on...

How do I realise that with Laravel 5.1?



via Chebli Mohamed

mercredi 22 novembre 2017

post image to webservice using cURL in laravel

I want post $data and $fileData to the webservice using cURL

Any one can help.

This is my code :

$data = $request->bodyData;
$fileData = image file;

$postfields = array();
$postfields['data'] = $data;
$postfields['fileData'] = $fileData;


 $ch = curl_init();

 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $output = curl_exec($ch);

 curl_close($ch);



via Chebli Mohamed

'Yajra\Datatables\DatatablesServiceProvider' not found

Hi guys I am trying to fix this about 1 week and I am stucked here. I try a lot of things like: composer-dumpload, clearing cache, capitalizing service provider like this: Yajra\Datatables\DatatablesServiceProvider I run multiple versions of Yajra like 5 and 6.

Here is my app.config

Providers
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    Yajra\Datatables\DatatablesServiceProvider::class

Alias
    'Datatables' => Yajra\Datatables\Facades\Datatables::class,

So I don't know what more have to do. I have Laravel 5.1 version and must be this version and not a new one.

If we can help me with this I will be very happy.

Thanks



via Chebli Mohamed

laravel where not in

this is my mysql code

SELECT name,lastname FROM employee WHERE employee.id_employee
NOT IN (SELECT assistancea.id_employee FROM assistance WHERE assistance.id_meeting=3)

where I'm waiting for a value in number 3
3 is the id_meeting of meeting

table employe  
|id_employe|name|lastname

table assistance  
|id_employe|id_meetign|

table meeting  
|id_metting|description|date

You could help me make a query from laravel



via Chebli Mohamed

mardi 21 novembre 2017

Powerpoint charts needs repair

i'm currently working on a project where I need to create powerpoints online. I'm using http://ift.tt/1RIak9x for this. Almost everything works perfectly, besides generating charts. When I open the powerpoint, it says it needs repairing. After the repair all the content is lost.

I wondered if anybody else had the same problem and could help me solve this problem.

Code i tried:

    $oPHPPresentation = new PhpPresentation();
    $currentSlide = $oPHPPresentation->createSlide();
    $currentSlide->setName('Title of the slide');
    $lineChart = new Line();


    $seriesData = array('Monday' => 18, 'Tuesday' => 23, 'Wednesday' => 14, 'Thursday' => 12, 'Friday' => 20, 'Saturday' => 8, 'Sunday' => 10);
    $series = new Series('example', $seriesData);
    $series->setShowValue(false);
    $series->setShowPercentage(true); // This does nothing
    $series->setDlblNumFormat('0.00%'); // This does nothing

    $lineChart->addSeries($series);
    $shape = $currentSlide->createChartShape();
    $shape->getPlotArea()->setType($lineChart);

    $oWriterPPTX = IOFactory::createWriter($oPHPPresentation, 'PowerPoint2007');
    $oWriterPPTX->save(__DIR__ . "/sample.pptx");

Package: http://ift.tt/1RIak9x
framework: Laravel 5.1
php version: 7.0

Thanks in advance



via Chebli Mohamed

lundi 20 novembre 2017

how to highlight string in a string in a laravel blade view

Somewhere in my template I have this:



Now in this text I want to highlight all words that are in the string



So I thought I create a new blade directive:



Blade::directive('highlightSearch', function($input, $searchString)...

error: missing argument 2

Found out that directives do not except 2 arguments. I tried every workaround that I could find but none worked. They always return the arguments as a plain string, not even passing the actual values.

I tried adding a helper function like explained here: http://ift.tt/2zXcYGl. Did not work:

error: unknown function "highlightSearch"

So how do I do this super easy task in laravel? I don't care about the highlighting function, that's almost a one-liner.



via Chebli Mohamed

samedi 18 novembre 2017

linux server Creates cache and laravel project gone down

I have stuck in a problem that my laravel project deployed in linux server and server is creating cache in var directory. I run 'yum clean all' command but again creates cache. I run command php artisan cache:clear, php artisan route:clear but no result. is there any way to manage server cache? I face, the error is...

ErrorException in Filesystem.php line 81:
file_put_contents(): Only 0 of 255 bytes written, possibly out of free disk space

my project size is 120 mb.



via Chebli Mohamed

vendredi 17 novembre 2017

Laravel Redis Queue - Reserved jobs not removed on failure

I'm using redis as the queue driver for Laravel 5.1. It seems that when a job fails due to a fatal error, such as an exceeded execution time, the reserved job is not removed from the queue. I can check in the redis-cli on the queues:default:reserved key that it's still there. And the job is reattempted over and over again instead of being deleted. I have two workers on the queue and retries are set to 1.

My artisan command is: artisan queue:listen --tries=1

The failed() method on the job is not called, nor is the Queue::failing() listener with the redis driver. These are not issues if I'm using the database driver.

Does anyone have any suggestions on what I should be looking for to solve this?



via Chebli Mohamed

jeudi 16 novembre 2017

Pass variable from custom Laravel Helpers to Blade file

I'm trying to create a helper to centralize a complicated Form::select.

My helper:

namespace App\Helpers;
use Log;
use App\Countries;

class Address {
    public static function country() {
        $countries = Countries::orderby('name_zh','asc');
        $form = "Form::select('countries', \$countries);";
        return $form;
    }
}

My View:

{!! Address::country() !!}

I would like to have this select form with $countries variable from this helper and show a Dropdown list on my view. How do I do it?



via Chebli Mohamed

mardi 14 novembre 2017

Error 500 when post data to database

I'm new in php and Laravel. I get error code 500 when I post my data.

this my form code in my blade :

    <form method="post" class="form-horizontal" id="form"
            action="">
            

and this is my method in my controller :

    public function store(Request $request)
{
    if($request->ajax()){
        $data = collect($request->all())
            ->except(['_token'])
            ->all();

        $akun = SetLinkAkunCoa::create($data);

        if($akun){
            $response = $this->returnSuccess('', trans('messages.success.update'));
            return response()->json($response);
        }else{
            $response = $this->returnData('', trans('messages.error.update'));
            return response()->json($response);
        }
    }
}

Please someone help me to solve this. thank's anyway



via Chebli Mohamed

dimanche 12 novembre 2017

FatalThrowableError in ServiceProvider.php line 49: Class 'Dompdf\Dompdf' not found

can i get some help to solve this problem, it works perfectly in my local, but in heroku i keep getting this error.

i tried:

heroku run php artisan cache:clear heroku run php artisan config:cache

But it did not work.

enter image description here

My providers, i am following the instructions to use Barryvdh\DomPDF:

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Routing\ControllerServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    //Para configurar laravel Collective
    Collective\Html\HtmlServiceProvider::class,
    //Generar pdfs en la aplicacion
    Barryvdh\DomPDF\ServiceProvider::class,

    /*
     * Application Service Providers...
     */
    noMasTattut\Providers\AppServiceProvider::class,
    noMasTattut\Providers\AuthServiceProvider::class,
    noMasTattut\Providers\EventServiceProvider::class,
    noMasTattut\Providers\RouteServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Gate'      => Illuminate\Support\Facades\Gate::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
    //terminando configurar laravel collective
    'Form' => Collective\Html\FormFacade::class,
    'Html' => Collective\Html\HtmlFacade::class,
    //Facade para generar PDFs
    'PDF' => Barryvdh\DomPDF\Facade::class,

],

And my composer.json:

"require": {
    "php": "^7.0",
    "laravel/framework": "5.1.*",
    "laravelcollective/html": "5.1.*",
    "guzzlehttp/guzzle": "~5.3|~6.0",
    "barryvdh/laravel-dompdf": "^0.8.1",
    "doctrine/dbal": "^2.5"

},



via Chebli Mohamed

vendredi 10 novembre 2017

"A non-numeric value encountered" laravel5.1 php7.1 dompdf 0.8

I understood that this error was already solved but i don't manage to fix it, so sorry and thanks for your advises: I'm working on a Laravel 5.1 project (FusionInvoice) and use dompdf to create pdf files. My aim is to use php7.1 for this project.

After enable php7.1 I had the "A non-numeric value encountered" error so i did the easy installation procedure of dompdf, with composer method (http://ift.tt/13J3PJw) to fix it using the dompdf 0.8.1 release. My requierements seems ok.

Now i have this error:

FatalThrowableError in domPDF.php line 30: Class 'DOMPDF' not found

we are talking about this file "app/Support/PDF/Drivers/domPDF.php" and this function:

private function getPdf($html)
    {
        $pdf = new \DOMPDF();
        $pdf->set_paper($this->paperSize, $this->paperOrientation);
        $pdf->load_html($html);
        $pdf->render();

        return $pdf;
    }

I understood that the "new \DOMPDF();" is calling this file '/vendor/dompdf/dompdf/src/Dompdf.php' to build his object. so i tried this : "new \Dompdf\Dompdf();"

and i'm back to the first place:

ErrorException in Page.php line 499: A non-numeric value encountered

Does someone knows how i can solve this issue ? Thanks...



via Chebli Mohamed

lundi 6 novembre 2017

TokenMismatchException in VerifyCsrfToken.php line

i am using laravel 5.1 its working on localhost but not working on server getting error

TokenMismatchException in VerifyCsrfToken.php line 53:

here is my code link

http://ift.tt/2h7AGai

help me



via Chebli Mohamed

samedi 4 novembre 2017

Cannot upload image in Laravel 5.2

I make input data with an upload image, my code

$name   = $request->input('name');
$images = $request->file('image');
$name_img = $images->getClientOriginalName();
$ext = $images->getClientOriginalExtension();
// Move Uploaded File
$destinationPath = 'img/';
$images->move($destinationPath,$name_img);
$path = $destinationPath.'/'.$name_img;

then put them in array, then insert in database

$data = array(
'name' => $name,
'image' => $path, );
DB::table('daftar')->insert($data);
return json_encode(array('status' =>true));

That code works in Laravel 5.1, but it doesnt work in Laravel 5.2.

Anything wrong with that code for Laravel 5.2?

Thank You. :)



via Chebli Mohamed

vendredi 3 novembre 2017

Maatwebsite/Laravel-Excel issue with more data

im using Maatwebsite/Laravel-Excel for exporting data in a xls format. How ever its not responding for 20000+ records. Download request ended up in response.

There is a known issue in here. They have suggest to chunk the records, but in my case i used .blade files in laravel for generating the xls.

How can i use chunk with .blade?



via Chebli Mohamed

if else statement running like what i need something went wrong in laravel

i have 2 button accept and reject
when i die dump request is coming fine with accept id 2 and reject id 3 but i try to add if statement its bring me only accept skip reject

here is my code

 $interview = Interview::find($request->id);
    $user = Currentuser::where('id', $interview->CompanyID)->first();
    if ($request->Status = '2') {


                 $data = []; // Empty array

                Mail::send('email.useracceptjob', $data, function($message) use ($user){

                    $message->to($user->Email)->subject('Your Job Accepted By user');

                });
             }
             elseif ($request->Status = '3') {


                 $data = []; // Empty array

                Mail::send('email.userrejectjob', $data, function($message) use ($user){

                    $message->to($user->Email)->subject('Your Job Rejected By user');

                });
             }
             else{
                return response()->json(['code' => 500]);
             }

do i doing something wrong? Help me Please



via Chebli Mohamed

jeudi 2 novembre 2017

Laravel: Allow soft deleted models in a hasManyThrough relationship

I have a has many through relationship like this:

class Venue {
    public function orders()
    {
        return $this->hasManyThrough(Order::class, Offer::class);
    }
}

However the Offer model can be soft deleted: http://ift.tt/2iVGxUj

This means the function, will not return any orders that have a soft deleted offer.

How can I allow the function to return orders that have soft deleted offers.

Note that I am using Laravel 5.1 (although solutions in newer versions is appreciated).



via Chebli Mohamed

mercredi 1 novembre 2017

preg_match(): No ending delimiter '/' found Laravel

I'm doing a validation by regex from a request, this validation is to check that the parameter that is sent is an IP.

My rules are as follows:

  <?php

namespace App\Http\Requests\usuarios;

use Illuminate\Foundation\Http\FormRequest;

class storeVPN extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [            
            'segmentwan' => 'http://regex:/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',
            'segmentlan' => 'http://regex:/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',

        ];
    }

the debugger shows me that the error is in this line

the debugger shows me that the error is in this line

return preg_match($parameters[0], $value) > 0;

y el error completo es el siguiente

 * @return bool
     */
    public function validateRegex($attribute, $value, $parameters)
    {
        if (! is_string($value) && ! is_numeric($value)) {
            return false;
        }

        $this->requireParameterCount(1, $parameters, 'regex');

        return preg_match($parameters[0], $value) > 0;
    }

    /**
     * Validate that a required attribute exists.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @return bool
     */
    public function validateRequired($attribute, $value)
    {
        if (is_null($value)) {
            return false;
        } elseif (is_string($value) && trim($value) === '') {
            return false;
        } elseif ((is_array($value) || $value instanceof Countable) && count($value) < 1) {
            return false;
        } elseif ($value instanceof File) {
            return (string) $value->getPath() !== '';
        }



via Chebli Mohamed

Connection could not be established with host on custom server

i am using laravel 5.1 & i am trying to send email after login but it show me error

Connection Could not be established with host mail.jobnow.com.sg

also try another host like gmail and other still same problem


How can i fix this



via Chebli Mohamed

mardi 31 octobre 2017

Guzzle Error - cURL error 6: Couldn't resolve host

Description

If I have this in my class

class CURL {

public static function get($url) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //<------ Note HERE 
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    $result =  json_decode($result, true);
    return $result;

}

My page load fine.

enter image description here


If I have this in my class

<?php
namespace App;

use Request,Auth;
use App\Log, App\Helper;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;



class CURL {

    public static function get($url) {

        $client = new Client();
        $result = $client->request('GET',$url, ['http_errors' => false, 'verify' => false ]);
        $result = (string) $result->getBody();
        $result = json_decode($result, true);
        return $result;

    }
    ...

}

As you can see, I tried set 'verify' => false already.

My page show this error.

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString

I want to write an if statement to show timestamp in diffForHumans format for timestamps less than less than 5 days old and in toFormattedDatesString for anything older than that.

For example today is 31/10/17, so timestamp for 28/10/2017 should show - 3 days ago and timestamp for 20/10/2017 should show Oct 20, 2017.

Can someone please tell any logic to achieve this? Thanks in advance for the help.



via Chebli Mohamed

dimanche 29 octobre 2017

How to get full url of image after amazon s3 upload

I need to get full url of a image which is uploaded to amazon s3. I tried following functions. I am using laravel 5.1.

Storage::disk("s3")->url($filename);
Storage::url($filename);
Storage::temporaryUrl('file1.jpg', Carbon::now()->addMinutes(5));
$filesystem->getAdapter()->getClient()->getObjectUrl($bucket, $key);

all are showing undefined function url (or) temporaryUrl (or) getObjectUrl.



via Chebli Mohamed

samedi 28 octobre 2017

How to place a range in the model::list method for combo in laravel?

I would like you to help me, to solve my question, and I would like to know what is the way to range my combo of charges, which comes from the database in the description field, but It list all the records , and I just need to show some of them, so I need to know how to set a range for the mentioned combo, This is where my combo is that gives me all the charges that are registered in the database, to pass them to a View to a select tag:

//VIEW TO REGISTER USERS
  public function VistaRegistraUsuario()
{

  $id_franquicia_usuario = Session::get('id_franquicia');
  $charges = charges_users::lists('descripcion', 'id'); //COMBO OF CHARGES

  return view('auth.register', compact('charges', 'id_franquicia_usuario'));
}// END VIEW



via Chebli Mohamed

laravel 5.1 check if a session is expired

I'm working on a laravel 5.1 application and I want to check if a user session has expired after each request, in order to redirect the user to the login page. in order to do so I have created a middleware that runs on every request, the handle function looks like this

public function handle($request, Closure $next)
{
     if(session_status() === PHP_SESSION_NONE)
     {
          return redirect()->guest('login');
     }
     return $next($request);
}

this does not seem to work correctly, because when I type 'localhost:8000' in google chrome it says 'localhost redirected you too many times', I guess it is because the session have not been started since the user is not logged in, so... is there any better way to do this checking?



via Chebli Mohamed

vendredi 27 octobre 2017

Laravel 5.1: migrate command doesn't work 'unknown database'

Good day!

I am facing problems with my laravel project built with laravel 5.1.

So I developed a reservation system with laravel, it works on my local server.

Then I uploaded it to my live server and started an SSH session.

But when I ran php artisan migrate command, this error showed up

[PDOException] SQLSTATE[HY000] [2005] Unknown MySQL server host 'sddb0040291787.cgidb' (0)

So, what I did so far is I wrote a php script to create the tables and other database related stuff and then run the php script on my server.

This works actually, my CRUD functions are working but I know this is just a temporary solution.

What I am looking for is a permanent solution. Plain PHP scripts seem to be able to connect to the database host. but when I migrate using laravel, the error always shows up. Any ideas?



via Chebli Mohamed

jeudi 26 octobre 2017

Rewriting laravel 5.1 controller action route on the Request object

I have many modules my source code organized into subfolders inside the App\Http\Controllers e.g App\Http\Controllers\ModuleOne.

The base controllers are in App\Http\Controllers and the module controllers extend these base controllers. A module controller might not exist if I don't want to customize the base controller when using that particular module.

I want to write a logic where a route checks if the module controller exists. If the route does not exist, it should route the action to a BaseController.

I have tried to make a middleware and other solutions but can't seem to get this done.

I want to have the routing inside all the controllers done with the same name (thus ignoring the module name - which will be defined by an env variable). So, to simplify code I want to call:

Route::get('apple','AppleController@view')

and from this route it should check if:

App\Http\Controller\module1\module1_AppleController.php

exists.

If it does, use it. If not, it should route to the base controller action i.e. App\Http\Controller\AppleController.

Can't seem to figure out where to do this with efficient code. Can the rewrite be done in RouteServiceProvider in middleware or other?

Also, if the newer version of Laravel could present a solution not found in 5.1, I am willing to upgrade, so don't limit answers to 5.1.



via Chebli Mohamed

Laravel 5.1. cannnot run artisan commands

I am using Laravel 5.1 and I cannot run any artisan commands.

I uploaded my project to our live server with PHP5.5.22 CLI version.

everytime I run artisan commands I am getting this error SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (146)

I changed the configuration on my .env and config/database.php files to point to our MySQL server.

.env file

DB_CONNECTION=mysql
DB_HOST=****.sddb0040291787.*****
DB_PORT=3306
DB_DATABASE=sddb0040291787
DB_USERNAME=sddbMTcyNjEy
DB_PASSWORD=**********

config/database.php

'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '****.sddb0040291787.*****'),
        'database'  => env('DB_DATABASE', 'sddb0040291787'),
        'username'  => env('DB_USERNAME', 'sddbMTcyNjEy'),
        'password'  => env('DB_PASSWORD', '**********'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

even php artisan config:cache command doesn't work and returns same error.

Appreciate any help. Thanks guys!



via Chebli Mohamed

mardi 24 octobre 2017

Are there altenatives for Redis - spiritix/lada-cache in the Laravel 5.1 framework

We have a laravel 5.1 app that we set up to use Redis, along with spiritix/lada-cache. We went this route because it gave really good performance on App Engine. Then, during testing one of our users complained that items were missing on a page whereas they showed up on another page. When we ran the same code with a remote connection to the same db we didn't get the same results. This led us to consider that lada-cache was an issue. We flushed the cache and could then see the same data from different the different pages.

Subsequent net searches brought us to this: Queries build by Eloquent\Builder instead of Query\Builder and this:Eloquent Models not updating / flushing Cache correctly. Both huge issues (assuming there hasn't been a fix).

First, are there any alternatives aside from Laravel's out of the box memcache which is not so fast? Second, if Redis is the way to go, are there any go arounds that we can use that bypass the above issues?



via Chebli Mohamed

laravel download excel file from s3 is not working

I am using laravel 5.1 I need to download excel from amazon s3 storage. I done all process correctly and if it is pdf format file means it downloading correctly but for excel file download it is downloading zip format. Can please anyone help me to fix this issue.

$filePath = "CIS/download/format/upload_format.xlsx";
if ( Storage::disk('s3')->has($filePath)) {
$file = Storage::disk('s3')->get($filePath);
$getMimeType = Storage::disk('s3')->getMimetype($filePath);
return Response::make($file, 200, [
'Content-Type' => $getMimeType,
'Content-Disposition' => 'attachement; 
filename:upload_format.xlsx',
]);
}



via Chebli Mohamed

lundi 23 octobre 2017

cURL error 28: Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received

Description

I'm using Guzzle in my Laravel project. I had a memory crash when I make a request to an API that return a huge payload.

I have this on the top of my CURL.php class. I have get() that I use guzzle.

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use GuzzleHttp\FORCE_IP_RESOLVE;
use GuzzleHttp\DECODE_CONTENT;
use GuzzleHttp\CONNECT_TIMEOUT;
use GuzzleHttp\READ_TIMEOUT;
use GuzzleHttp\TIMEOUT;

class CURL {

    public static function get($url) {

        $client = new Client();
        $options = [
            'http_errors' => true,
            'force_ip_resolve' => 'v4',
            'connect_timeout' => 2,
            'read_timeout' => 2,
            'timeout' => 2,
        ];
        $result = $client->request('GET',$url,$options);
        $result = (string) $result->getBody();
        $result = json_decode($result, true);
        return $result;

    }

    ...

}

When I call it like this in my application, it request a large payload (30000)

$url = 'http://site/api/account/30000';
$response =  CURL::get($url)['data'];

I kept getting this error

cURL error 28: Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received (see http://ift.tt/1mgwZgQ)

How do I avoid this?


Should I increase these settings?

'connect_timeout' => 2,
'read_timeout' => 2,
'timeout' => 2,


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Set preference for Laravel 5.1 Queues

I am using laravel 5.1 for my application. And for event handlers i am using shoudque as below

class QuizCreatedHandler implements ShouldQueue
{
   /**
     * Create the event listener.
     *
     * @return void
     */
     public function __construct()
     {
     }

  /**
    * Handle the event.
    *
    * @param  QuizCreated  $event
    * @return void
   */
    public function handle(QuizCreated $event)
    {
       //codes here
    }
}

But the thing when i comment shouldqueue, events working perfectly. But if i use shouldqueue, the event is not getting even after 1 hour. Is there any way to check it? Or is there any way to set high priority to this queue ?

Appreciate any Help.



via Chebli Mohamed

Laravel excel import date format issue in windows

I am using laravel 5.1 I need to import excel to process some data. I have to process date which is entered in excel. For ubuntu os its working fine. For windows os date column interchanging while loading the excel. For example If I upload excel with date 20-11-2017 means the loaded value will be 11-20-2017 it is wrong. Can please anyone help me to fix this issue. My code given below. I am using "maatwebsite/excel": "~2.0.0".

Excel::load($file, function($reader) {
        $details = $reader->formatDates(true)->toArray();
    });



via Chebli Mohamed

samedi 21 octobre 2017

Laravel data is not saving in user table .and also not going postRegister function. please help me

am registering use through Auth controller (the auth controller use use AuthenticatesAndRegistersUsers, ThrottlesLogins). when is click on register function it go

use toAuthenticatesAndRegistersUsers 

then authcontroller but not going in postRegister. :( also not showing any error.please help me. here is AuthController

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Models\Employee;
use App\Role;
use Validator;
use Illuminate\Support\Facades\Hash;
use Eloquent;
use Mail; 
use Session;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    public function showRegistrationForm()
    {
        $roleCount = Role::count();
        if($roleCount != 0) {
            $userCount = User::count();
            if($userCount == 0) {
                return view('auth.register');
            } else {
                return redirect('login');
            }
        } else {
            return view('errors.error', [
                'title' => 'Migration not completed',
                'message' => 'Please run command <code>php artisan db:seed</code> to generate required table data.',
            ]);
        }
    }
       public function showLoginForm()
        {
            $roleCount = Role::count();
            if($roleCount != 0) {
                $userCount = User::count();
                if($userCount == 0) {
                    return redirect('register');
                } else {
                    return view('auth.login');
                }
            } else {
                return view('errors.error', [
                    'title' => 'Migration not completed',
                    'message' => 'Please run command <code>php artisan db:seed</code> to generate required table data.',
                ]);
            }
        }

        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array  $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        protected function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255',
                'password' => 'required|min:6|confirmed',
            ]);
        }

        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return User
         */
        protected function create(array $data)
        {
            // TODO: This is Not Standard. Need to find alternative
            Eloquent::unguard();

            $employee = Employee::create([
                'name' => $data['name'],
                'designation' => "Admin",
                'mobile' => "85888",
                'mobile2' => "",
                'email' => $data['email'],
                'gender' => 'Male',
                'dept' => "1",
                'city' => "Lahore",
                'address' => "Pakistan",
                'about' => "About user / biography",
                'date_birth' => date("Y-m-d"),
                'date_hire' => date("Y-m-d"), 
                'date_left' => date("Y-m-d"),
                'salary_cur' => 0,
            ]);

            $user = User::create([
                'name' => $data['name'],
                 'firstname' => $data['firstname'],
                  'lastname' => $data['lastname'],
                   'address' => $data['address'],
                    'mobile_number' => $data['mobile_number'],
                     'deals' => $data['deals'],
                       'city_id' => $data['city_id'],
                         'plaza_id' => $data['plaza_id'],
                'email' => $data['email'],
                 'pin_code'=>date('U'),
                'password' => Hash::make($data['password']),
                'context_id' => $employee->id,
                'type' => "ADMIN",
            ]);
            $role = Role::where('name', 'ADMIN')->first();
            $user->attachRole($role);
                 //  email for  Shop Owner
            Mail::send('emails.email', ['user' => $user], function ($m) use ($user) {
             //   $m->from('hello@app.com', 'Your Application');

              $m->to($user->email,$user->name)->subject('Welcome at Classified!');
           });

    // email for administration
        /* Mail::send('emails.email', ['user' => $user], function ($m) use ($user) {
             //   $m->from('hello@app.com', 'Your Application');

              $m->to($user->email,$user->name)->subject('Welcome at Classified!');
           });
    */

         Session::flash('success', "Your request has been sent for verification by Master Networks !!!");

            return $user;
        }
    }

here is may route

Route::get('/registers', 'Frontend\RegisterController@index');
    Route::post('/registers', 'Auth\AuthController@postRegister');

here is RedirectsUsers

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
    use RedirectsUsers;

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getRegister()
    {
        return $this->showRegistrationForm();
    }

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        if (property_exists($this, 'registerView')) {
            return view($this->registerView);
        }

        return view('auth.register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request)
    {

        return $this->register($request);
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        Auth::guard($this->getGuard())->login($this->create($request->all()));

        return redirect($this->redirectPath());
    }

    /**
     * Get the guard to be used during registration.
     *
     * @return string|null
     */
    protected function getGuard()
    {
        return property_exists($this, 'guard') ? $this->guard : null;
    }
}



via Chebli Mohamed

vendredi 20 octobre 2017

Laravel use dynamic mutators in where clause

So i have two columns - SizeX & SizeY. For front end users I use Laravel mutator

public function getSizeAttribute(){
    /**
     * Set Size
     */
    $size = $this->SizeX. " x ". $this->SizeY;
    /**
     * Return
     */
    return $size;
}

To format the sizes like this SizeX x SizeY. The column Sizes does not exists because its dynamic. Is it possible to use mutators or alternative within the Elaquent model to detect that this is a dynamic attribute, and use some sort of method to convert the SizeX x SizeY to individual columns? Once the user submits the attribute Size back to laravel application for filtering?

Edit:

Right, this is the method I'm using to retrieve filtered Items

public function scopeFilteredMaterials($query,$params = array()){ 
    /**
     * Get filters
     */
    $filters = array();
    /**
     * Extract Info
     */
    if(!empty($params) && is_array($params)){
        /**
         * Get Available Filters
         */
        $filters = $this->getAvailableFilters();

        foreach ($filters as $key => $filter){
            if(isset($params[$filter])){

                $filters[$filter] = $params[$filter];

                unset($filters[$key]);
            }else{

                unset($filters[$key]);
            }
        }
    }

    foreach ($filters as $key => $filter){

        $query->whereIn(key ,$filter);
    }

    $result = $query->get();
}

This is the filters variable which holds available filters for user to see

protected $filters = array( "Name", "url", "Size", );

I'm using the above to show the specific values to the user. Once the user selects those values I'm using the same array to check against those filters and fire the query. My problem is the Size attribute is made up of two columns which I have not problem using the following Mutator and $appends variable to automatically bring the value to the user.

/**
 * Get Size Attribute
 */
public function getSizeAttribute(){
    /**
     * Set Size
     */
    $size = $this->SizeX. " x ". $this->SizeY;
    /**
     * Return
     */
    return $size;
}

But i ca't figure out a way to convert the Size variable back to SizeX & SizeY



via Chebli Mohamed

jeudi 19 octobre 2017

Laravel avoid running out of memory

Im trying to use laravel excel to create an excel sheet. Because my database is expanding the memory limit is reached and I get the error:

FatalErrorException in Connection.php line 321: Allowed memory size of 134217728 bytes exhausted (tried to allocate 196605 bytes)

I already raised the memory limit a few times but I would like to improve the function so it uses less memory so I dont need to raise the memory limit everytime. I already use chuncking to try and lower the memory using but to no avail.

My function:

public function exportExcel($year)
{

    $datum = date("d-m-Y");


    Excel::create('Sales export '.$datum, function($excel)use($year) {


        $datum = date("d-m-Y");

        // Chain the setters
        $excel->setCreator('author name')
            ->setCompany('company name')
            ->setDescription('sales export.')
            ->setTitle('sales export '.$datum);

        $excel->sheet('sales '.$datum, function($sheet)use ($year) {

            $sheet->appendRow(array(
                "merk","product","artikel nr","afbeelding","categorie","collectie","maat","omschrijving","inkoopprijs","verkoopprijs","prijs betaald","aantal verkocht","verkocht aan",  "totaal","dag","maand","jaar","kwartaal","reseller","verkoper","bestel naam", "status"
            ));
            Order::whereYear('created_at', '=', $year)->orderBy('billed_at','desc')->chunk(1, function($orders)use ($sheet){
                foreach($orders as $index => $order)
                {

                    foreach($order->products as $p)
                    {

                        $sizeLink = $p->productSize;
                        $productLink = $sizeLink->product;


                        // Append row as very last
                        $sheet->appendRow(array(
                            //Merknaam  Artikelnr.  Soort   Kleur   Maat
                            //Omschrijving  Geboekt aantal  Basiseenheid
                            //inkoopprijs   verkoopprijs    aant stuks verkocht
                            //Maand Jaar    Kwartaal


                            $productLink->brand->name, //merknaam
                            $productLink->name, //productnaam
                            $productLink->artnr, //Artikelnr
                            //link naar de hoofdafbeelding
                            "". URL::to('/'). ucfirst($productLink->mainthumb),
                            $productLink->category->name, //soort
                            $productLink->collection->name, //soort
                            $sizeLink->size->name,   //maat naam
                            $productLink->desciption,   //omschrijving
                            number_format((float) $productLink->price_buy_in, 2, ',', ''), //inkoopprijs
                            number_format((float) $productLink->price, 2, ',', ''), //verkoopprijs
                            number_format((float) $p->price, 2, ',', ''), //prijs betaald
                            $p->quantity, //geboekt aantal
                            $order->billingname . $order->billingnamelast, //verkocht aan
                            number_format((float) $p->quantity * $p->price, 2, ',', ''), // totaal kosten
                            //number_format((float) ($p->quantity * $p->price - $p->quantity * $p->price_buy_in), 2, ',', ''), // winst inkoop-verkoop
                            date("d",strtotime($order->billed_at)), //dag
                            date("n",strtotime($order->billed_at)), //maand
                            date("Y",strtotime($order->billed_at)), //jaar
                            ceil(date("m",strtotime($order->billed_at))/3), // kwartaal
                            $order->reseller->name, // verkoper
                            $order->creator, // verkoper
                            $order->name, //text op factuur
                            $order->status->name,
                        ));
                    }
                }

            });


            // Auto filter for entire sheet
            $sheet->setAutoFilter();
            $sheet->freezeFirstRow();
            // Set black background
            $sheet->row(1, function($row) {

                // call cell manipulation methods
                $row->setBackground('#cccccc');
                $row->setFontWeight("bold");

            });
    $sheet->setColumnFormat(array(
        'G' =>  \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00,
        'H' => '[$EUR ]#,##0.00_-',
        'I' =>  \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00,
    ));

        });

    })->download('xlsx');;
}

I know I could raise the memory limit but I would like to find out why so much memory is used and how I can avoid using to much memory.



via Chebli Mohamed

Laravel Form Input hidden keep returning empty

Description

I have a form

<form method="POST" accept-charset="UTF-8" action="http://site/account/1003/destroy">
  <input name="_method" type="hidden" value="DELETE">
  <input name="_token" type="hidden" value="pBRx8u17C6KHFxzfhatx0BpnmOF5x55EWSP2lpis">
  <input name="id" type="hidden" value="1003">
  <a data-dismiss="modal" class="btn btn-danger mr10">No</a>
  <button type="submit" class="btn btn-success" data-toggle="modal" data-target=".bs-example-modal-lg"> Yes </button>
</form>

As you can see the id has the value of 1003.


Attempt

I'ved to test in my destroy() function

public function destroy($id)
{
    dd(Input::all());
    ...

I got

array:3 [▼
  "_method" => "DELETE"
  "_token" => "pBRx8u17C6KHFxzfhatx0BpnmOF5x55EWSP2lpis"
  "id" => "" <------ empty 
]

I double check everything. I could not seem to know what is the cause of my id to be empty while I can clearly see it in the HTML in my browser.


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

joining tables in laravel and get data by group

I have tables like below. I want to get the data which has count of unique make_id.

I joined all the tables and I'm getting error as 'Unexpected data found'.

leads:

+----+------------+
| id | vehicle_id |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

vehicles

+----+------------+
| id | model_id   |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

models:

+----+------------+
| id | make_id    |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

This is my code:

$Leads = Leads::join('vehicles', 'vehicles.id', '=', 'leads.vehicle_id')
        ->join('models', 'models.id', '=', 'vehicles.model_id')
->groupBy('vehicles.model_id')
->get();

Thank you



via Chebli Mohamed

mercredi 18 octobre 2017

Make a GET with Guzzle in Laravel 5.1

I have an API, and make GET to it via Postmen

Ex.http://site/api/users.count

I got

{
    "status": 200,
    "message": "Success",
    "data": {
        "count": 8
    }
}

I've tried to use Guzzle

composer require guzzlehttp/guzzle  


Using version ^6.3 for guzzlehttp/guzzle                                                                                          
./composer.json has been updated                                                                                                  
Loading composer repositories with package information                                                                            
Updating dependencies (including require-dev)                                                                                     
  - Installing guzzlehttp/promises (v1.3.1)                                                                                       
    Downloading: 100%                                                                                                             

  - Installing psr/http-message (1.0.1)                                                                                           
    Loading from cache                                                                                                            

  - Installing guzzlehttp/psr7 (1.4.2)                                                                                            
    Loading from cache                                                                                                            

  - Installing guzzlehttp/guzzle (6.3.0)                                                                                          
    Downloading: 100%                                                                                                             

Writing lock file                                                                                                                 
Generating autoload files                                                                                                         
> php artisan clear-compiled                                                                                                      

> php artisan optimize                                                                                                            

Generating optimized class loader                                                                                                 


include it

I add these 2 lines on top of my class

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;


use it

$client = new Client();
$res = $client->request('GET','http://site/api/users.count');
dd($res);


result

I kept getting

Response {#664 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:4 [▼
    "Connection" => array:1 [▼
      0 => "Keep-Alive"
    ]
    "Content-Length" => array:1 [▼
      0 => "61"
    ]
    "Content-Type" => array:1 [▼
      0 => "application/json; charset=utf-8"
    ]
    "Date" => array:1 [▼
      0 => "Wed, 18 Oct 2017 18:01:50 GMT"
    ]
  ]
  -headerNames: array:4 [▼
    "connection" => "Connection"
    "content-length" => "Content-Length"
    "content-type" => "Content-Type"
    "date" => "Date"
  ]
  -protocol: "1.1"
  -stream: Stream {#662 ▼
    -stream: stream resource @272 ▼
      wrapper_type: "PHP"
      stream_type: "TEMP"
      mode: "w+b"
      unread_bytes: 0
      seekable: true
      uri: "php://temp"
      options: []
    }
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}


expected result

I am hoping to get a similar result like this :

{
    "status": 200,
    "message": "Success",
    "data": {
        "count": 8
    }
}


question

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Laravel 5.1 MethodNotAllowedHttpException - Registration

I have a problem with registration. When the user will finish registration then he will get this error message - MethodNotAllowedHttpException in RouteCollection.php line 219. Could you check pls the code if you will the issue that causing this error.

01.) Routes.php

/**
     * Guest only visit this section
     */
    Route::group(['middleware' => 'guest'], function () {
        Route::get('account/login', ['as' => 'login', 'uses' => 'Auth\LoginController@getLogin']);
        Route::get('auth/{provider}', 'Auth\LoginController@getSocial');
        Route::get('auth/{provider}/callback', 'Auth\LoginController@getSocialCallback');
        Route::get('registration/{provider}', 'Auth\RegistrationController@getSocialRegister');
        Route::get('account/registration', ['as' => 'registration', 'uses' => 'Auth\RegistrationController@getIndex']);
        Route::get('registration/activate/{username}/{code}', 'Auth\RegistrationController@validateUser');
        Route::get('password/email', ['as' => 'password.reminder', 'uses' => 'Auth\PasswordController@getEmail']);
        Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
    });

    /**
     * Guest Post form with csrf protection
     */
    Route::group(['middleware' => 'csrf:guest'], function () {
        Route::post('account/login', 'Auth\LoginController@postLogin');
        Route::post('registration/{provider}', 'Auth\RegistrationController@postSocialRegister');
        Route::post('password/email', 'Auth\PasswordController@postEmail');
        Route::post('password/reset/{token}', 'Auth\PasswordController@postReset');
        Route::post('account/registration', 'Auth\RegistrationController@postIndex');
        Route::get('image/freefiles/{slug}', ['as' => 'images.freefiles', 'uses' => 'ImageController@getFreeFiles']);
    });

02.) login.blade.php

   <form action="" method="POST">
                                    <input type="hidden" name="_token" value="">
                                    <div class="sminputs">
                                        <div class="input full">
                                            <label class="string optional" for="username">username*</label>
                                            <input class="string optional" maxlength="255" id="username" name="username" placeholder="username" type="text" size="50" />
                                        </div>
                                    </div>
                                    <div class="sminputs">
                                        <div class="input full">
                                            <label class="string optional" for="email">Email*</label>
                                            <input class="string optional" maxlength="255" id="email" name="email" placeholder="Email" type="email" size="50" />
                                        </div>
                                    </div>
                                    <div class="sminputs">
                                        <div class="input string optional">
                                            <label class="string optional" for="password">Password *</label>

                                            {!! Form::password('password',['class'=>'form-control input-lg','placeholder'=>t('Enter Password'),'autocomplete'=>'off','required'=>'required']) !!}
                                        </div>
                                        <div class="input string optional">
                                            <label class="string optional" for="password_confirmation">Repeat password *</label>

                                            {!! Form::password('password_confirmation',['class'=>'form-control input-lg','placeholder'=>'Confirm Password','autocomplete'=>'off','required'=>'required']) !!}
                                        </div>
                                    </div>
                                    <div class="simform__actions">
                                        <input class="sumbit" name="commit" type="submit" value="Create Account" />

                                        <span class="simform__actions-sidetext">By creating an account you agree to our <a class="special" href="#" target="_blank" role="link">Terms & Privacy</a></span>
                                    </div>
                                </form>

03.) login_beta.blade.php

  <form action="" class="contact_form2" method="POST">
            <h1 style="text-align: center">Create Your Account</h1>
            <input type="hidden" name="_token" value="">
            <ul id="usn_eml">
                <li>
                    <input type="text" maxlength="255" id="username" name="username" class="textbox1"
                    placeholder="Your username..." required/>
                    <span class="form_hint">Enter username</span>
                </li>
                <li>
                    <input type="email" maxlength="255" id="email" name="email" class="textbox1"
                    placeholder="Your email..." required>
                    <span class="form_hint">Enter email...</span>
                </li>
                <li>
                    {!! Form::password('password',['class'=>'textbox1','placeholder'=>t('Enter Password'),'autocomplete'=>'off','required'=>'required']) !!}
                    <span class="form_hint">Your password...</span>
                </li>
                <li>
                    {!! Form::password('password_confirmation',['class'=>'textbox1','placeholder'=>'Confirm Password','autocomplete'=>'off','required'=>'required']) !!}
                    <span class="form_hint">Confirm password...</span>
                </li>
                                <ol style="clear: both; display: block; padding-top: 17px;">
               
                <div class="form-group">
                    <script src='http://ift.tt/1xQsaAf'></script>

                    <div class="g-recaptcha" data-sitekey="xxxx"></div>
                </div>
            
                           </ol>
                <input name="commit" type="submit" value="Create Account"/>
                
            </ul>

            <style>
                #usn_eml {
                    width: 50%;
                    display: block;
                    margin: auto;
                }
            </style>

            

            <div class="tos">
                By creating an account you agree to our <a
                class="special" href="http://ift.tt/2ywFks0" target="_blank" role="link">Terms &
                Privacy</a>
            </div>

            <div class="already_member">
                <p>Already a member? Please<a id="getSignInDiv" href="#"> Sign In</a></p>
            </div>
        </form>


via Chebli Mohamed

Payfort integration Response in Laravel 5.1

I am using payfort as payment gateway. And y application is in Laravel 5.1. Iam using a pafort library for integrating it. When i am using purchase request api, it returns a html page.

When i check it in postman, for pretty, got response something like

 <!DOCTYPE html>
 <html>
<head>
    <title>Payment redirect page</title>
</head>
<body>
    <form method="post" action="http://ift.tt/2bOOvZK" id="frm" name="frm">
        <input type="hidden" name="command" value="PURCHASE">
        <input type="hidden" name="access_code" value="hjwuuquudhqdjd">
        <input type="hidden" name="merchant_identifier" value="klklkns">
        <input type="hidden" name="merchant_reference" value="ijijisux">
        <input type="hidden" name="amount" value="1000">
        <input type="hidden" name="currency" value="USD">
        <input type="hidden" name="language" value="en">
        <input type="hidden" name="customer_email" value="dev@gmail.com">
        <input type="hidden" name="return_url" value="http://ift.tt/2yyvTsA">
        <input type="hidden" name="signature" value="70ff4d91adef50f91c049bc68b64c12d1b212d5597463c3a2fef30830aa502dc">

    </form>
    <script>
document.frm.submit();
  </script>
 </body>
</html>

But for preview, i got a blank page. What should i do? I couldnt proceed without getting that preview.



via Chebli Mohamed

How to filter a tree like array by a specific field using Laravel Eloquent

This is my result tree which I want to filter by 'language_code' field

"theme_detail": [
            {
                "id": 1,
                "parent_theme_id": null,
                "image_url": "no_image",
                "index_value": 1,
                "status": "active",
                "theme_detail": [
                    {
                        "id": 4,
                        "theme_id": 1,
                        "language_code": "bn",
                        "theme_name": "থিম 1",
                        "theme_subtitle": "থিম 1 উপশিরোনাম",
                        "status": "active"
                    },
                    {
                        "id": 1,
                        "theme_id": 1,
                        "language_code": "en",
                        "theme_name": "Theme 1",
                        "theme_subtitle": "Theme 1 Subtitle",
                        "status": "active"
                    }
                ],
                "parent_recursive": [
                    {
                        "id": 2,
                        "parent_theme_id": 1,
                        "image_url": "no_image",
                        "index_value": 1,
                        "status": "active",
                        "theme_detail": [
                            {
                                "id": 5,
                                "theme_id": 2,
                                "language_code": "bn",
                                "theme_name": "থিম 2",
                                "theme_subtitle": "থিম 2 উপশিরোনাম",
                                "status": "active"
                            },
                            {
                                "id": 2,
                                "theme_id": 2,
                                "language_code": "en",
                                "theme_name": "Theme 2",
                                "theme_subtitle": "Theme 2 Subtitle",
                                "status": "active"
                            }
                        ],
                        "parent_recursive": [
                            {
                                "id": 3,
                                "parent_theme_id": 2,
                                "image_url": "no_image",
                                "index_value": 1,
                                "status": "active",
                                "theme_detail": [
                                    {
                                        "id": 3,
                                        "theme_id": 3,
                                        "language_code": "en",
                                        "theme_name": "Theme 3",
                                        "theme_subtitle": "Theme 3 Subtitle",
                                        "status": "active"
                                    },
                                    {
                                        "id": 6,
                                        "theme_id": 3,
                                        "language_code": "bn",
                                        "theme_name": "থিম 3",
                                        "theme_subtitle": "থিম 3 উপশিরোনাম",
                                        "status": "active"
                                    }
                                ],
                                "parent_recursive": [
                                    {
                                        "id": 4,
                                        "parent_theme_id": 3,
                                        "image_url": "no_image",
                                        "index_value": 1,
                                        "status": "active",
                                        "theme_detail": [
                                            {
                                                "id": 7,
                                                "theme_id": 4,
                                                "language_code": "bn",
                                                "theme_name": "থিম 4",
                                                "theme_subtitle": "থিম 4 উপশিরোনাম",
                                                "status": "active"
                                            },
                                            {
                                                "id": 9,
                                                "theme_id": 4,
                                                "language_code": "en",
                                                "theme_name": "Theme 4",
                                                "theme_subtitle": "Theme 4 Subtitle",
                                                "status": "active"
                                            }
                                        ],
                                        "parent_recursive": []
                                    }
                                ]
                            },
                            {
                                "id": 5,
                                "parent_theme_id": 2,
                                "image_url": "no_image",
                                "index_value": 1,
                                "status": "active",
                                "theme_detail": [
                                    {
                                        "id": 8,
                                        "theme_id": 5,
                                        "language_code": "bn",
                                        "theme_name": "থিম 5",
                                        "theme_subtitle": "থিম 5 উপশিরোনাম",
                                        "status": "active"
                                    },
                                    {
                                        "id": 10,
                                        "theme_id": 5,
                                        "language_code": "en",
                                        "theme_name": "Theme 5",
                                        "theme_subtitle": "Theme 5 Subtitle",
                                        "status": "active"
                                    }
                                ],
                                "parent_recursive": []
                            }
                        ]
                    }
                ]
            }
        ]


This is my json array which is in a tree like structure. This array is the result of a recursive eloquent relation. Now I want to filter it by a specific language code or by any other field. How can I do it using Laravel eloquent? can anybody help?



via Chebli Mohamed