mercredi 31 mai 2017

Storing an image and multiple input

I have a problem in storing an image and multiple input

this is my image code

                $ngo = new User;           
 $user_certificate = Request::file('user_certificate');
            $destination_path = 'Certificate/';
            $filename = str_random(6).'_'.$user_certificate->getClientOriginalName();
            $user_certificate->move($destination_path, $filename);

            $ngo->user_certificate = $destination_path . $filename;
$ngo->save();

my multiple input

$bank = $request->bank_name;
                foreach ($bank as $asd) {

                    $banks = new BankAccount;
                    $banks->user_id = $user->id; 
                    $banks->bank_name = $asd;
                    $banks->account_name = $request['account_name'];
                    $banks->account_number = $request['account_number'];
                    $banks->save();
            }         

When i use use Illuminate\Http\Request; the image upload will error and this is the error.

Non-static method Illuminate\Http\Request::file() should not be called statically, assuming $this from incompatible context

and the multiple input are ok then when i change the use Illuminate\Http\Request; to use Request; it will error.

Undefined property: Illuminate\Support\Facades\Request::$bank_name

Anyone can help me to solve this problem?



via Chebli Mohamed

mardi 30 mai 2017

Auth:check() always returns false

I tried googling but didn't get the solution yet.

I'm trying to know whether user is authenticated or not into the view file by using

  1. Auth::check() always returns false
  2. Auth::User() always returns NULL

Tried posts:

  1. It says to place domain to null that's already there.

  2. Some posts say to edit into the kernel.php, how safe is it?

Any help will be appreciated. Thanks



via Chebli Mohamed

Laravel Guzzle params

I have this curl request from the API docs

curl http://ift.tt/2sbeOir --user TOKAN-HO:2eL4aKsSGCaN4FH8 -k

Now I'm trying to call this request with Laravel 5.1 using Guzzle library, so I do this

public function testacorne()
{
    $client = new GuzzleHttp\Client();

    $res = $client->get('http://ift.tt/2rBDMuq', [
        'form_params' => [
            'user' => 'TOKAN-HO:2eL4aKsSGCaN4FH8'
        ]
    ]);

    dd($res);
}

This is what i get

ClientException in RequestException.php line 107:
Client error: `GET http://ift.tt/2rBDMuq` resulted in a `401 Unauthorized` response:
{
"Message": "Authorization has been denied for this request."
}

But the username and password are correct. How can I fix this issue?



via Chebli Mohamed

Laravel - use years as pagination numbers

I am on Laravel 5.1.45 (LTS). One club has many events.

I want to display a page which lists all the events for the current year (the default page). At the bottom at the page I want the links for the previous and for the next years (one link per page and one page per year).

This is my PublicController:

public function index()
{
            $events = Event::with('Club')
                                    ->orderBy('date', 'desc')
                                    ->get()
                                    ->groupBy(function($date) {
                                            return Carbon::parse($date->date)->format('Y');
                                    });
            $currentPage = Paginator::resolveCurrentPage() - 1;
            $perPage = 1;
            $currentPageSearchResults = $events->slice($currentPage * $perPage, $perPage)->all();
            $paginator = new LengthAwarePaginator($currentPageSearchResults, count($events), $perPage);
            return view('events.index', ['events' => $paginator]);
}

And this is my view:

@foreach ($events as $year)
    @foreach ($year as $object)
            
            
    @endforeach
@endforeach

{!! $events->setPath('/events/events')->appends(Request::except('page'))->render() !!}

This is working; I get all the events for the year in one page and one page for each year.

However, the links at the bottom of the page are, of course, in the form of, for example, '?page=2' for the 2016 events.

What I would like to have is a link in the form of '?page=YEAR'. And, if there are already events listed for the next year, to land on the page with the events for the current year if no parameter has been added to the URL.

Is that even possible?



via Chebli Mohamed

Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz

I got this error

GuzzleHttp\Exception\ClientException: Client error: `POST http://ift.tt/2riapfS` resulted in a `400 BAD REQUEST` response:
{
  "message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz (truncated...)

when i trying unit test for function i have ? how i can fix that ??



via Chebli Mohamed

lundi 29 mai 2017

Laravel Events Dispatcher has empty listeners for some events

I am trying to debug a strange Events quirk in Laravel 5.1.46. The application is enhanced with some other OSS components such as Symfony DIC, but no change has been made to actual Event handling.

Some events during a request lifespan fail to find their listeners. Everything seems to be set up correctly (code excerpt from the DIC):

$instance = new \Illuminate\Events\Dispatcher($this->get('illuminate\contracts\foundation\application'));
$instance->listen('App\\Events\\FallbackPeopleAdded', 'App\\Listeners\\NotifyAboutNewFallbackRole');

However, NotifyAboutNewFallbackRole is never handled. I've setup some debugging calls in Illuminate\Events\Dispatcher, I print out name of the event and count($this->listeners) at the beginning of sortListeners method. It returns 13 for all but 2 events in the middle of the event list. The SPL object hash of the Dispatcher instance does not change, therefore it is the same object for all the events (list shortened).

"App\Auth\AuthServiceProvider" (31)
13
"router.before" (13)
13
"router.matched" (14)
13
"jwt.valid" (9)
0
"App\Events\FallbackPeopleAdded" (34)
0
"App\Events\BroadcastPayload" (31)
13
"router.after" (12)
13
"kernel.handled" (14)
13

The NotifyAboutNewFallbackRole listener is listed correctly in $listeners dump for all other events

There is nothing special about the events with no listeners

class FallbackPeopleAdded implements \Illuminate\Contracts\Queue\ShouldQueue
{

nor with their firing

$this->eventDispatcher->fire(
    new FallbackPeopleAdded(
        $newFallback,
        $brand->getId(),
        $originatingPerson->getId()
    )
);

The queue should not be the issue here, the error occurs despite that, and more, it occurs even for the textual jwt.valid event.

Has anybody else encountered this as well? I do not understand where the listeners from the protected property could be removed and how come they are back again for another 3 events.



via Chebli Mohamed

how to add artisan command to my package laravel

SO i developed a custom package in Laravel 5.4, i add my route,my controllers but i have no idea how to add a artisan command, this is my code :

namespace MyPackage;

use Illuminate\Support\ServiceProvider;

class MyPackageServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        include __DIR__.'/routes.php';
    }

    /**
    * Register the application services.
    *
    * @return void
    */
    public function register()
    {
      $this->app->make('MyPackage\Controllers\MyPackageServiceController');
    }
}

Normally in the usual case i add a new artisan command and add it to app/Console/Commands/Kernel.php, so how can i do that inside my package ?



via Chebli Mohamed

dimanche 28 mai 2017

laravel error message: syntax error, unexpected 'class'

Installed Laravel 5.1 using Composer. php version 5.9

Now, I am getting an error in my index.php

Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home/user/public_html/laravel_one/public/index.php on line 50

index.php

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/

require __DIR__.'/../bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Many places, users are saying that, this is because of php version. Is there any option to solve this without upgrading php version?



via Chebli Mohamed

vendredi 26 mai 2017

Laravel - move index.php file in project/public

I am hosting my Laravel project on shared hosting where I don't have access to modify the apache config to look for the index file in /public.

I've also tried adding DirectoryIndex index.html to my .htaccess file at the place where the hosting is looking for the index.php file.

This does not work.

That being said, I think I can solve the problem if I simply move the index.php file out of /public (where Laravel has it by default) to the root where the hosting is looking for it.

That being said, what do I need to modify in this index.php file to allow the Laravel app to work?

My structure is:

public_html/ <-- where my files are served from and where index.php should be 
    my-project/
           public/
               index.php <-- where Laravel expects index.php to be to bootstrap the app



via Chebli Mohamed

How do I parse this json data in view blade? Output [{"...":...}]

I am trying to display the maximum value of an attribute in a table

my controller

$member = DB::table('member')
->select(DB::raw('MAX(code) as code'))  
->where('status', '=', "No")->get();
return view('member.index', compact('member')); 

Currently this is my view



And this is the output

[{"code":14101234}]

I wanted to display something like this

14101234

I've tried using json_decode but the result remains.



via Chebli Mohamed

jeudi 25 mai 2017

Laravel 5.1 - Standalone EC2 to AWS Elastic Beanstalk

I have a Laravel 5.1 app deployed on a standalone EC2. I would like to deploy it on AWS Elastic Beanstalk. Can I just zip it up and upload it or do I need to deploy everything from scratch?



via Chebli Mohamed

InvalidArgumentException Please provide a valid cache path Error laravel 5.2

I'm working with Laravel 5.2 and i have an error when i run composer update or artisan optimize ..

i've searched on my vendor, i didn't found compiled.php file ! i try to generate this i run the artisan optimize, i have the same error

[InvalidArgumentException]          
  Please provide a valid cache path

Script php artisan clear-compiled handling the post-update-cmd event returned with error code 1

how i can resolve this ?



via Chebli Mohamed

mercredi 24 mai 2017

How to migrate:rollback a specific table in laravel 5

I know this feature has been already added in laravel 5.3, but I am using Laravel 5.1, how can I do it using 5.1 version? I've also searched it on internet, but there's only solution for 5.3. Hope you can help me, and for those who have the same problem.



via Chebli Mohamed

Laravel GuzzleHttp issue

I need to use and API from example.com I use Laravel as a framework and to get data with API in their docs I see this:

  curl http://ift.tt/2riu0gD ^
 -H "Authorization: Bearer eyJ0ehsagdasjhgdashdgaOiJIUzI1NiJ9.eyJpc3Msjhdshjdasd7676N5c3RlbXMuY29tIn0.DBR5UPxxxxxxzxzxzxzxzxzxzxyzxyzxyzxyzyxzyxyzxyxxWQ_BkS1mzxw" ^
 -d VisitDate=2017-05-08 ^
 -d PartySize=2 ^
 -d ChannelCode=ONLINE

What I try to do is:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

class TestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function test()
    {

$client = new GuzzleHttp\Client();

$res = $client->request('GET','http://ift.tt/2rRzzj0', [
    'headers' => [
        'Authorization' => 'Bearer eyJ0ehsagdasjhgdashdgaOiJIUzI1NiJ9.eyJpc3Msjhdshjdasd7676N5c3RlbXMuY29tIn0.DBR5UPxxxxxxzxzxzxzxzxzxzxyzxyzxyzxyzyxzyxyzxyxxWQ_BkS1mzxw',
    ],
    'form_params' => [
        'VisitDate' => '2017-05-24',
        'PartySize' => '2',
        'ChannelCode' => 'ONLINE',
    ],
]);

// You need to parse the response body
// This will parse it into an array
$res = json_decode($res->getBody(), true);

dd ($res);

    }


    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Now when I try to test i get:

BadMethodCallException in functions.php line 324:
Unknown method, request

How I can solve ths problem? How to use Guzzle instead cURL with Laravel framework? What is wrong in my code ... I just follow guzzle docs and API docs.



via Chebli Mohamed

Migrations running (Uploading)

I have problem in migrations(uploading). when i write "php artisan migrate" running only 5 migrations in database, and lost 3 migrations.

I want to run all migrations.

What is my problem?



via Chebli Mohamed

Laravel 5.1 pagination groupby links rendering

I am on Laravel Framework version 5.1.45 (LTS).

One club can have many events. I am trying to list all the events, group them by year and show one page per year.

According to my Laravel version documentation "Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually."

Here is my attempt to create the paginator manually and it seems to do the job:

public function index()
{
            $page = Paginator::resolveCurrentPage() - 1;
            $perPage = 1;
            $events = new Paginator(Event::orderBy('date', 'desc')->groupBy(DB::raw('YEAR(date)'))->skip(($page - 1) * $perPage)->take($perPage + 1)->get(), $perPage, $page);
            $events->setPath(['events/events']);
            return view('events.index', ['events' => $events]);
}

And here is how I try to display the links at the bottom of the page.

{!! $events->render() !!}

If I remove the render bit, the page is displayed, albeit with no links. I can even go to the next page (year 2016) adding manually ?page=2 at the end of the url in my browser.

But if I leave the render bit in the index page, I get ErrorException in AbstractPaginator.php line 130: Array to string conversion.

What am I doing wrong?



via Chebli Mohamed

laravel Invalid argument supplied for foreach()

I got this error

Invalid argument supplied for foreach() (View: /home/myproject/resources/views/client/route_data/data_table.blade.php) (View: /home/myproject/resources/views/client/route_data/data_table.blade.php)

when I try this path

/backend/route-data/11/edit

and this function belong to the path in laravel v5.1

public function edit($id)
    {
        $routeData = RouteData::find($id);
        if(null === $routeData) {
            Session::flash('error', 'Not found #' . $id);
            return Redirect::to('backend/route-data');
        }

        return view('backend.route_data.edit', compact('routeData'));
    }



via Chebli Mohamed

mardi 23 mai 2017

Select Query - Upto Previous Date Records is Not Working in Laravel

Following Laravel Query I Write for to get Upto Previous Date Records. thats Not Get any Records. If i Remove Date query its get Many Records. my $data['frmdate_submit'] format is 2017-05-24. How to Fix this Problem

$getpreviousbalance=Companyledger::where('transaction_date','>',$data['frmdate_submit'])->WhereIn('frm_ledger',$ledgerlist)->where('company_id',$companyids)->get();    



via Chebli Mohamed

Laravel 5.1 how to make my eloquent query closure secured

what i'm trying to do is to Sum the total deposits of each reservation model, with the condition of less than the amount input in the text.

here's my query:

$reservations->whereHas('deposits', function($query) use ($etc_filters){
                $query->havingRaw('SUM(amount) <= '.$etc_filters);
            });

as you can see, i'm using havingRaw that can be injected with another query. right now i cant find any alternative solution for my code.



via Chebli Mohamed

lundi 22 mai 2017

Laravel get select value with variable

Hello Im trying to get the select value which also happens to be a variable is that possible if not how can I get that done.

<select name="foo">
<option value="bar"></option>
</select>
echo Input::get('foo') // outputs bar

Ho can I get this work ?

 <select name="foo">
<option value=""></option>
</select>
<echo Input::get('foo') // outputs nothing



via Chebli Mohamed

Laravel get div without ajax

Hi I am trying to get the content within a div element that also happens to be within a form into my controller. I dont want to use ajax. How may I get that done ?

 <div id="editorcontents" name="editorcontents">
 </div>

Then in controller

  Use Input;
  $content = Input::get('editorcontents');



via Chebli Mohamed

Laravel 5.1 Mail::send doesn't work - gives 500 internal server error

I took an example from the Laravel 5.1 documentation for Mail and replaced it with my send and receiver email ids.

Mail::raw works in the controller and if I use Mail::send in tinker it works. However, if I use Mail::send in the controller it doesn't work.

Everything is set up as described on the Laravel 5.1 mail page. http://ift.tt/2hmkilE . I have also cleared app cache, config cache and view cache.

public function sendEmailReminder(Request $request, $id)
{
    $user = User::findOrFail($id);
    Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
        $m->from('hello@app.com', 'Your Application');

        $m->to($user->email, $user->name)->subject('Your Reminder!');
    });
}



via Chebli Mohamed

Laravel 5.1 Cant return Null Field in Relation

How to prevent Trying to get property of non-object from an empty field?

I have

 $employee->genderRelation->name;

but gender field in my Employee table is empty or not set yet. how to return it into an empty string instead of returning error?



via Chebli Mohamed

Laravel 5.1 helping class is not working in my laravel application

My helping class code is here

use App\ReceivingItem;

class ReportReceivingsDetailed {

    public static function receiving_detailed($receiving_id)
    {
        $receivingitems = ReceivingItem::where('receiving_id', $receiving_id)->get();
        return $receivingitems;
    }

My report page code

@extends('app')

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

                <div class="panel-body">
<div class="well well-sm">: </div>
<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td>&nbsp;</td>
        </tr>
    </thead>
    <tbody>
    @foreach($receivingReport as $value)
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td>
                <a class="btn btn-small btn-info" data-toggle="collapse" href="#detailedReceivings" aria-expanded="false" aria-controls="detailedReceivings"></a>
            </td>
        </tr>

            <tr class="collapse" id="detailedReceivings">
                <td colspan="9">
                    <table class="table">
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        @foreach(ReportReceivingsDetailed::receiving_detailed($value->id) as $receiving_detailed)
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        @endforeach
                    </table>
                </td>
            </tr>

    @endforeach
    </tbody>
</table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

But it is showing the result enter image description here

Please help me to solve it. The application is in laravel 5.1



via Chebli Mohamed

Check value dropdown select using change function in javascript

I have a script that hides a div tag with id=showDiv for Name of School .During the first load,the default value of select of School location is "Choose location" and I set it to hide.Upon changing or selecting option from School location, the div for Name of School will show.What if I will change the select of School location back to "Choose location"?It suppose to hide it back.How can I hide the div again?

HTML- just some part of it

<div class="col-lg-3">
   <div class="form-group">
     <label class="control-label">School Location:</label>
     <select name="location_primary" class="form-control" id="selection">
       <option>Choose location</option>
         @foreach($locations as $location)
          <option  value="{!! $location->location_id!!}" rel="{!! $location->location_id!!}">{!! $location->location_name!!}</option>
          @endforeach
        </select>
      </div>
   <div class="form-group" id="showDiv">
  <label class="control-label">Name Of School </label>
  <button class=" add_field_button_primary btn-primary">+</button>
   <select name="school_primary" class="form-control " style="display: none;">
   <option  class="0">Choose school</option>
      @foreach($schol as $school)
      <option  value="{!! $school->school_id !!}" class="{!! $school->location_id!!}">{!! $school->school_name!!}</option>
      @endforeach
      </select>
      </div>
   <div class="input_fields_view_primary">
     </div>
   </div> 

    ---Script---

    $(document).ready(function(){
        var $cat = $('select[name=location_primary]'),
        $school = $('select[name=school_primary]');
        var thisSelect = document.getElementById('selection');

        var selection = thisSelect.options[thisSelect.selectedIndex].innerHTML;

            if(selection == 'Choose location'){
                    $('#showDiv').hide();
               }

             $cat.change(function(){
                alert(selection);
               if(selection == 'Choose location') {
                    alert('true');
                    $('#showDiv').show();
               } 


               var $this = $(this).find(':selected'),
               rel = $this.attr('rel'),
               $set = $school.find('option.' + rel);

                if ($set.size() < 0) {
                  $school.hide();
                  return;
                }
               $school.show().find('option').hide();
               $set = $school.find('option.0, option.' + rel);

               $set.show().first().prop('selected', true);


      });
    });



via Chebli Mohamed

Laravel-Backpack I need upload images with 3 different thumbnails sizes

I need upload images with 3 different thumbnails sizes.

For example I upload image and now I get one thumbnail (48x48px), and I want to have 3 sizes: 100x100px, 300x300px, 600x600px.

How can I do this? Help me please.



via Chebli Mohamed

Laravel get select value with variable

Hello Im trying to get the select value which also happens to be a variable is that possible if not how can I get that done.

<select name="foo">
<option value="bar"></option>
</select>
echo Input::get('foo') // outputs bar

Ho can I get this work ?

 <select name="foo">
<option value=""></option>
</select>
<echo Input::get('foo') // outputs nothing



via Chebli Mohamed

dimanche 21 mai 2017

Laravel get div without ajax

Hi I am trying to get the content within a div element into my controller. I dont want to use ajax. How may I get that done ?

 <div id="editorcontents" name="editorcontents">
 </div>

Then in controller

  Use Input;
  $content = Input::get('editorcontents');



via Chebli Mohamed

vendredi 19 mai 2017

Laravel issue: Fatal error: Class 'Symfony\Component\Finder\Adapter\AbstractAdapter' not found

when I upload my laravel project on hostinger. I got that type of error:

Fatal error: Class 'Symfony\Component\Finder\Adapter\AbstractAdapter' not found in /home/u855555878/public_html/buildcrm/vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.php on line 28.

but its working on wamp. what is issue on hostinger.



via Chebli Mohamed

jeudi 18 mai 2017

Laravel 5.1 Mail::send doesn't work - gives 500 internal server error

Hi I have take then example as it is published on the Laravel 5.1 Mail page and replaced it with my send and receiver email ids. Mail::raw works in the controller and if I use Mail::send in tinker it works. However, if I use Mail::send in the controller it doesn't work. Everything is set up as described on the Laravel 5.1 mail page. http://ift.tt/2hmkilE . I have also cleared app cache, config cache and view cache.

public function sendEmailReminder(Request $request, $id) { $user = User::findOrFail($id);

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

        $m->to($user->email, $user->name)->subject('Your Reminder!');
    });
}



via Chebli Mohamed

mercredi 17 mai 2017

Laravel 5.1 Cant return Null Field in Relation

How to prevent "Trying to get property of non-object" from an empty field. I have $employee->genderRelation->name; but gender field in my Employee table is empty or not set yet. how to return it into an empty string instead of returning error?



via Chebli Mohamed

Laravel 5.1 helping class is not working in my laravel application

My helping class code is here

use App\ReceivingItem;

class ReportReceivingsDetailed {

public static function receiving_detailed($receiving_id)
{
    $receivingitems = ReceivingItem::where('receiving_id', $receiving_id)->get();
    return $receivingitems;
}

My report page code

@extends('app')

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

                <div class="panel-body">
<div class="well well-sm">: </div>
<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td>&nbsp;</td>
        </tr>
    </thead>
    <tbody>
    @foreach($receivingReport as $value)
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td>
                <a class="btn btn-small btn-info" data-toggle="collapse" href="#detailedReceivings" aria-expanded="false" aria-controls="detailedReceivings"></a>
            </td>
        </tr>

            <tr class="collapse" id="detailedReceivings">
                <td colspan="9">
                    <table class="table">
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        @foreach(ReportReceivingsDetailed::receiving_detailed($value->id) as $receiving_detailed)
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        @endforeach
                    </table>
                </td>
            </tr>

    @endforeach
    </tbody>
</table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

But it is showing the result enter image description here

Please help me to solve it. The application is in laravel 5.1



via Chebli Mohamed

lundi 15 mai 2017

Laravel 5.1, PHP 7.0: WhereNotIn not working

we have this 2 eloquent script which retrieves a user video based on the filter. I know this is working before because I haven't received any complains from the testers and my superiors have verified it is working.

$previous_winners = Stage::whereNotNull('win_date')
                ->where('win_date','>',Carbon::now()->subDays(8)->format('Y-m-d H:i:s'))
                ->lists('userId')
                ->toArray();

output for the 1st script is like:

array:4 [
  0 => 84
  1 => 361
  2 => 304
  3 => 326
]

but the output of the script below is null

$stage = Stage::whereIn('stageId',$id)
                            ->whereNull('win_date')
                            ->whereNotIn('userId',$previous_winners)
                            ->where('stageId','!=',Config::get('constants.intro'))
                            ->where('stageId','!=',88)
                            ->first();

When the controller is called I always get a null value for the 2nd script even though when I checked the data it should retrieve one as I forced it to return results. The issue that I found out is that when removing this line ->whereNotIn('userId',$previous_winners) i get the correct results but when I put it back again i only get null values. I tried moving the whereNotIn to different positions from the first and before the end but as long as it is present I only get null values. Any idea or workaround on this one, please? Thanks.



via Chebli Mohamed

Check value dropdown select using change function in javascript

I have a script that hides a div tag with id=showDiv for Name of School .During the first load,the default value of select of School location is "Choose location" and I set it to hide.Upon changing or selecting option from School location, the div for Name of School will show.What if I will change the select of School location back to "Choose location"?It suppose to hide it back.How can I hide the div again?

HTML- just some part of it

<div class="col-lg-3">
   <div class="form-group">
     <label class="control-label">School Location:</label>
     <select name="location_primary" class="form-control" id="selection">
       <option>Choose location</option>
         @foreach($locations as $location)
          <option  value="{!! $location->location_id!!}" rel="{!! $location->location_id!!}">{!! $location->location_name!!}</option>
          @endforeach
        </select>
      </div>
   <div class="form-group" id="showDiv">
  <label class="control-label">Name Of School </label>
  <button class=" add_field_button_primary btn-primary">+</button>
   <select name="school_primary" class="form-control " style="display: none;">
   <option  class="0">Choose school</option>
      @foreach($schol as $school)
      <option  value="{!! $school->school_id !!}" class="{!! $school->location_id!!}">{!! $school->school_name!!}</option>
      @endforeach
      </select>
      </div>
   <div class="input_fields_view_primary">
     </div>
   </div> 

    ---Script---

    $(document).ready(function(){
        var $cat = $('select[name=location_primary]'),
        $school = $('select[name=school_primary]');
        var thisSelect = document.getElementById('selection');

        var selection = thisSelect.options[thisSelect.selectedIndex].innerHTML;

            if(selection == 'Choose location'){
                    $('#showDiv').hide();
               }

             $cat.change(function(){
                alert(selection);
               if(selection == 'Choose location') {
                    alert('true');
                    $('#showDiv').show();
               } 


               var $this = $(this).find(':selected'),
               rel = $this.attr('rel'),
               $set = $school.find('option.' + rel);

                if ($set.size() < 0) {
                  $school.hide();
                  return;
                }
               $school.show().find('option').hide();
               $set = $school.find('option.0, option.' + rel);

               $set.show().first().prop('selected', true);


      });
    });



via Chebli Mohamed

Laravel-Backpack I need upload images with 3 different thumbnails sizes

I need upload images with 3 different thumbnails sizes.

For example I upload image and now I get one thumbnail (48x48px), and I want to have 3 sizes: 100x100px, 300x300px, 600x600px.

How can I do this? Help me please.



via Chebli Mohamed

dimanche 14 mai 2017

Two select drop-down with category in JavaScript

sample database

Location
    location_id     location
    1           Bacolod
    2           Bohol
    3           Cebu
    4           Manila

School

id      location_id     School_name
1           1               Bacolod Tay Tung High School
2           3               University of Southern Philippines Foundation
3           2               Dr. Cecilio Putong National High School
4           1               Jack and Jill School
5           4               British School Manila
6           2               Holy Spirit School of Tagbilaran
7           4               Chinese International School Manila
8           2               Ubay National Science High School
9           3               Abellana National School


<select onChange="jsFunction()" id="team1" >
@foreach($locations as $location)
<option onclick="jsFunction()">{!! $location->location_name!!}</option>
@endforeach
</select>


<select id="team2">
<option>Computer Science</option>
<option>Mathematics</option>
<option>Bioinformatic</option>
<option>Management Sciences</option>
</select>

<script>
function jsFunction(){
    var team1 = document.getElementById( "team1" );
    var team2 = document.getElementById( "team2" );
    for (i=0;i<4;i++){
        team2.remove(0);
    }
    var position=0;
    for (i=0;i<4;i++){
        if (i!=team1.selectedIndex){
            team2.options[position] = new Option(team1.options[i].value);
            position=position+1;
        }
    }
}
</script>

I have these two dropdown select in which the first dropdown is the holder or sort of category that once click, the list that belongs to this will display it.For example base from the database value,if i select Cebu,all the schools that belong to Cebu schould display in the second dropdown. Dont mind my current script because it is wrong.The code must expect multiple data so the second dropdown must display all the data not just limitting the view to 4 items. I am not really familiar with javascript.Anyone could help me construct the javascript?NOT the AJax please because its more complicated to me.



via Chebli Mohamed

laravel Invalid JSON was returned from the route. Perhaps an exception was thrown?

This is my test for store function

 /** @test */
    public function storeTest()
    {  
       $this->be($this->user);
       $response = $this->json('POST','/client/ocp/profile/247/route-',[
                     'name' => 'Test store',
                     'speed' => 4.5,
                     'created_by' => $this->user->id,
                     'client_id' => '262',

                   ]);
        $response
                ->seeStatusCode(302)
                ->seeJson(['status' => 'OK']);

    }

when i run it i got this error

Invalid JSON was returned from the route. Perhaps an exception was thrown?

i try to add this header to solve a problem
['X-Requested-With' => 'XMLHttpRequest'] but it not solving

how i can solve this?



via Chebli Mohamed

vendredi 12 mai 2017

SOAPClient Error: Could not connect to host on PHP 7.0 and Laravel

I am having issues connecting to a WSDL via SOAPClient on my Laravel application in a server with PHP 7.0. I have tested the following code on my local server using PHP 5.6 and it works. Both are running Linux; my local server is running Kubuntu and the other server is running CentOS 7.

var $client;

function __construct(){
    ini_set('soap.wsdl_cache_enabled',WSDL_CACHE_NONE);
    ini_set('soap.wsdl_cache_ttl', 0);

    $this->client = new SoapClient(env('WSDL_SOLMAN02_TEST'),
        ['login'=>env('SOLMAN_US_TEST'),
         'password'=>env('SOLMAN_PSSWD_TEST'),
         'cache_wsdl' => WSDL_CACHE_NONE,
         'soap_version' => SOAP_1_1,
         'ssl_method' => 'SOAP_SSL_METHOD_SSLv3',
         'trace' => true,
         'exception' => false,
         'stream_context'=> stream_context_create(array(
            'ssl'=> array(
                    'verify_peer'=>false,
                    'verify_peer_name'=>false
                )
            ))
        ]
    );

}
public function updateTicket(Ticket $ticket){

    $incident = $this->createTicketObject($ticket);
    $params = get_object_vars($incident);

    return $this->client->wsdlFunc($params);
}

The funny thing is that when I print dd($this->client->__getFunctions()); the WSDL responds with an array of all the functions that you can call, but when I actually call upon any function, the error is displayed.

I have tried just about everything, from changing every parameter in the connection to changing the php.ini, but nothing has worked. I have downgraded the server to PHP 5.6 and it still doesn't work.

I have also tested WSDL on SOAPUI and it works.

The only difference I find between both environments is that the server with PHP 7.0 has https.



via Chebli Mohamed

jeudi 11 mai 2017

Php: Temporary Settings

I want to implement a configuration where user can select company where all data will be fetch. my first idea was to store it into the settings table in my database, but i just realize it will change the configuration to all the users. Is there a way to do this?

*sample idea
$company = $this->company($request->input('company_id')->get());
return $company;



via Chebli Mohamed

write unit test request->ajax() laravel

how to write test for this function ?? how to test request-ajax()??

public function getChangeLoc(Request $request, $loc)
{   
    if ($request->ajax()) {

        if(!in_array($loc, config('loc.available'))) {
            return response()->json([
                'status' => 'ERROR',
                'message' => 'Not available'
            ]);
        }
        Session::put('locale', $loc);

        return response()->json([
            'status' => 'OK',
            'loc' => $loc,
        ]);
    }

    if(!in_array($loc, config('loc.available'))) {
        return Redirect::to('/?unknown-loc);
    }
    Session::put('loc', $loc);

    if(filter_var($request->input('redirect_url', ''), FILTER_VALIDATE_URL)) {
        return Redirect::to($request->input('redirect_url'));
    }

    return Redirect::to('/');
}

I test the function like this

            $this->visit('/loc/en')
                 ->seePageIs('/admin/client')

but its not see request->ajax?



via Chebli Mohamed

mercredi 10 mai 2017

how to mock get function laravel 5.1 ?

I have this function in laravel 5.1

  { 
        if ($request->ajax()) {
        if(!in_array($loc, config('loc.available'))) {
            return response()->json([
                'status' => 'ERROR',
                'message' => 'Not available loc'
            ]);
        }
        Session::put('loc', $loc);

        return response()->json([
            'status' => 'OK',
            'loc' => $loc,
        ]);
    }

how to write mock test for this function to get passing ?



via Chebli Mohamed

Laravel middleware always logs out

I'm working with Laravel 5.1, and I have been searching the answer for this problem long ago, but I've been not succeed.

The problem takes place when a super-administrator tries to login. The whole login process is implemented in AJAX, so when the login takes place AJAX awaits for the redirection url while the Authentication process is taken by an Auth Controller.

If the request is ok, the a dashboard url is sent back to the ajax, BUT the middleware logs me out once the redirection is performed.

The auth WelcomeController to validate the super-admin looks like this (this works just fine, delivering the propper redirection url):

\Config::set('auth.model', 'App\Super_Admin');

        $sadmin = \Auth::createEloquentDriver();

        \Auth::setProvider($sadmin->getProvider());

        //Admin verification
        if(\Auth::attempt(['system_admin_user' => $request->username, 'password' => $request->password])) {

            \Auth::user()->setAttribute('profile','SuperAdmin');
            \Session::set('sadmin_name',\Auth::user()->system_admin_fullname);

            return response()->json(['login_status' => 'success', 'redirect' => 'SuperAdmin/dashboard', 'error' =>'']);
        }
        else {
            return response()->json(['login_status' => 'invalid', 'error' => 'Usuario y/o password invalidos', 'redirect' => '/']);
        }

The function to handle the requests in Middleware is_admin looks like this (not working as intended):

public function handle($request, Closure $next)
{

    if(\Auth::check() && \Auth::user()->profile == "SuperAdmin") {
            return redirect('/');
    }
    else {
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

I also tried with a different code of the middleware:

public function handle($request, Closure $next)
{
    if(!\Auth::check() || \Auth::user()->profile != "SuperAdmin") {
        $this->auth->logout();
    }

    return $next($request);
}

The route group protected for the admin is defined like this:

Route::group(['middleware' => ['auth','is_superAdmin']], function() {
    Route::get('SuperAdmin/dashboard', 'Super_Admin\SuperAdminController@index');
});

If anyone could tell me the propper way to do this, I would be very happy! Thank you in advance!



via Chebli Mohamed

how to write test for json response?

I have function return JSON

return response()->json([
            'status' => 'OK',
            'data' => [
                'id' => $routeForecast->id,
            ],
        ])

how can I make test for this .. my laravel version is 5.1 and i used assertJson([ ]) it give me this error

***** PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertJson() must be a string

and try seeJson it give me this error

***** Invalid JSON was returned from the route. Perhaps an exception was thrown?

how can i solve it ??



via Chebli Mohamed

samedi 6 mai 2017

Laravel 5 Call to undefined method Illuminate\Database\Query\Builder::muestras()

I'm working with Laravel 5.1: I have a model called Muestra that has 4 foreign keys/relationships one to many with Ganado, TipoMuestra, TipoConsulta and Laboratorio. The problem comes when I create a Muestra element called $muestra in guardarNueva() from a form, and it calls $muestra->setTipoConsulta/Laboratorio/TipoMuestra(), it calls to the function with and throws the error:

BadMethodCallException in Builder.php line 2123:
Call to undefined method 
Illuminate\Database\Query\Builder::muestras()
in Builder.php line 2123
at Builder->__call('muestras', array())
at call_user_func_array(array(object(Builder), 'muestras'), array()) 
in Builder.php line 1015
at Builder->__call('muestras', array())
at call_user_func_array(array(object(Builder), 'muestras'), array()) 
in Model.php line 3444
at Model->__call('muestras', array()) in Muestra.php line 51
at Muestra->setTipoConsulta(object(TipoConsulta)) in Muestra.php line 65
at Muestra::guardarNueva(object(Request)) in MuestrasController.php line 48

Muestra model code is:

class Muestra extends Model
{
protected $fillable = ['tubo'];
protected $dates = ['fecha_extraccion'];

public function ganado()
{
    return $this->belongsTo(Ganado::class);
}

public function tipo_muestra()
{
    return $this->belongsTo(TipoMuestra::class);
}

public function tipo_consulta()
{
    return $this->belongsTo(TipoConsulta::class);
}

public function laboratorio()
{
    return $this->belongsTo(Laboratorio::class);
}

public function setFechaExtraccion($date)
{
    $this->fecha_extraccion = $date;
    $this->save();
    return $this->fecha_extraccion;
}

public function setLaboratorio($laboratorio){
    return $laboratorio->muestras()->save($this);

}

public function setTipoMuestra($tipomuestra){
    return $tipomuestra->muestras()->save($this);

}

public function setTipoConsulta($tipoconsulta){
    return $tipoconsulta->muestras()->save($this);

}
public function setGanado($ganado){
    return $ganado->muestra()->save($this);

}

public static function guardarNueva($request){
    $datos = $request->except(['tipo_muestra_id','tipo_consulta_id','laboratorio_id','ganado_id','fecha_extraccion']);
    $muestra=self::create($datos);
    $muestra->setFechaExtraccion($request->input('fecha_extraccion'));
    $muestra->setGanado(Ganado::find($request->input('ganado_id')));
    $muestra->setLaboratorio(Laboratorio::find($request->input('laboratorio_id')));
    $muestra->setTipoConsulta(TipoConsulta::find($request->input('tipo_consulta_id')));
    $muestra->setTipoMuestra(TipoMuestra::find($request->input('tipo_muestra_id')));
    return $muestra;

}

}

The migration of Muestra is:

class CreateMuestrasTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('muestras', function (Blueprint $table) {
        $table->increments('id');
        $table->string('tubo')->unique();
        $table->date('fecha_extraccion');
        $table->integer('ganado_id');
        $table->integer('tipo_muestra_id');
        $table->integer('tipo_consulta_id');
        $table->integer('laboratorio_id');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('muestras');
}
}

And any of the other models that are failing, for example TipoMuestra is like this:

class TipoConsulta extends Model
{
//
protected $fillable=['nombre'];

protected function muestras(){
    return $this->hasMany(Muestra::class);
}


public function getSelectOptionAttribute(){
    return $this->attributes['nombre'];
}
}



via Chebli Mohamed

vendredi 5 mai 2017

lazychaser/laravel-nestedset - how to limit depth of nested items?

I'm currently working on a project which is making use of nested categories. As is most likely obvious, there will be categories which will have parent-child relationships. To help with this, I am learning how the lazychaser/laravel-nestedset Laravel package could work.

What I would like to know is if I can limit the depth of parent categories to an arbitrary limit (e.g 5), like so:

Category 1
|__ Category 2
    |__ Category 3
        |__ Category 4
            |__ Category 5

Following on from the above description...

What would be the recommended way to make an Eloquent model rule - where I can specify an integer value for the maximum category depth? Then, perhaps catch an exception, or deal with an error in the controller if this maximum depth is already reached (when creating a category)?



via Chebli Mohamed

mardi 2 mai 2017

Reading Date from Postgres Row in Laravel. Php

I m trying to create an object in Laravel, when i set the date I get an error. Thats my code:

$result = pg_query($this->conn, "SELECT * FROM cliente");
    if (!$result) {
      $this->message('Error to query cliente');
      exit;
    }
    while ($row = pg_fetch_row($result)) {
        if($row[7]== null){
            $cliente->fecha_nacimiento = null;
        }
        else{
            $fechaString = (string)$row[7];
            //$this->info($fechaString);
            $fecha = DateTime::createFromFormat('Y-m-d', trim($fechaString));
            $cliente->fecha_nacimiento =  $fecha;
        }
}

The error is:

[ErrorException]                                                             
DateTime::createFromFormat() expects parameter 2 to be string, object given

If I use Carbon:

$fecha = Carbon::createFromFormat('Y-m-d', trim($fechaString));

Getting:

[InvalidArgumentException]                  
The separation symbol could not be found  
Unexpected data found.                    
Trailing data     

Thanks in advance!



via Chebli Mohamed

lundi 1 mai 2017

Getting error through Burp proxy in Laravel application

Good Morning...! I am working on clearing security audit of laravel application please suggest how to do remove these type of problems and also suggest error page number (e.g. 500, 501) of second screen shoot ?

  1. Load the main url of the website “http://example.com” and intercept the request using the burp proxy. In the host header, append the following script as shown below.

enter image description here

  1. The application is throwing critical errors as shown in the screenshot.

enter image description here



via Chebli Mohamed