mardi 1 mars 2016

Laravel 5 Json with relationship

I have this code, is a tale with relathioship it self:

Category Model

class Cateogry extends Model {
    public function subCategory(){
        return $this->hasMany('\App\SubCategory');
    }
} 

SubCategory Model

<?php
class SubCategory extends Model {
    public function Category(){
        return $this->belongsTo('\App\Category');
    }
} 

In your controller

SomeController

<?php 

class SomeController extends Controller {
    public function index(){
        return Category::with('subCategory')->get()
    }
} 

when i do the return Category::with('subCategory')->get(); he prints:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 43,
                    "name": "Quartos",
                    "subcategories_id": null
                }
            ]
        }
    {
        "id": 55,
        "name": "Jovenil",
        "subcategories_id": 2,
        "sub_category": [
            {
                "id": 55,
                "name": "Jovenil",
                "subcategories_id": 2
            }
        ]
    }

instead:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 50,
                    "name": "Casal",
                    "subcategories_id": 1
                }
                {
                    "id": 51,
                    "name": "Jovenil",
                    "subcategories_id": 2
                }(...)
            ]
        }

why the quer does that?



via Chebli Mohamed

About laravel eloquent - how to get specified column value in database

i'm new to Laravel, i'm using laravel 5.1 I want to get the specified column in the database.

It's my controller:

public function index()
{
    $markQuizs = MarkAss::select('year')->where('user_id','=','abc001')->get();
    return view('marks-management', ['markQuizs'=> $markQuizs]);
}

In the view page, i try to echo

$markQuizs

but it got

[{"year":2016}]

how can i only get the "2016" value? Does it need ajax?



via Chebli Mohamed

sendOutputTo in Laravel Console

I scheduled a cronjob through Laravel console. It is working and giving the result in every minute. But I tried to write the output to a file using the sendOutputTo and appendOutputTo method. But this is not writing to the file. My file has write permission. Below is my code.

Kernel.php

protected function schedule(Schedule $schedule) {

  $filePath = base_path() . "\cron\CleanSession.txt";

  $schedule->command('cleansession')
           ->everyMinute()
           ->sendOutputTo($filePath);
}

Session.php

public function handle() {

        $this->info('Display this on the screen');
        $onlineCodeObj = new OnlineCode();
        if ($onlineCodeObj->cleanSession()) {
            echo "SESSION CLEANED : echo" . "\n";
            return "SESSION CLEANED: return" . "\n";
        }
         echo "SESSION CLEANED : echo2" . "\n";
         return "SESSION CLEANED: return2" . "\n";
    }

Any help appreciated.



via Chebli Mohamed

Laravel 5 - Blade casting collection to array and checking its value

I pass my view a Campaign Collection. If I do

{{ dd($campaign->campaignCreatives->campaignCreativesData) }}

I get something like

Collection {#348 ▼
  #items: array:2 [▼
    0 => CampaignCreativesData {#349 ▼
      #attributes: array:7 [▼
        "id" => "5"
        "name" => "creativeOption"
        "label" => "Other"
        "value" => "sdfsdfsdfsdfsdf"
        "campaignCreativesId" => "5"
        "created_at" => "2016-03-01 10:24:38"
        "updated_at" => "2016-03-01 10:24:38"
      ]

    }
    1 => CampaignCreativesData {#350 ▼
      #attributes: array:7 [▼
        "id" => "4"
        "name" => "creativeOption"
        "label" => "checkboxSelection"
        "value" => "Animated GIF"
        "campaignCreativesId" => "5"
        "created_at" => "2016-03-01 10:24:38"
        "updated_at" => "2016-03-01 10:24:38"
      ]
    }
  ]
}

If I cast it to an array

{{ dd($campaign->campaignCreatives->campaignCreativesData->toArray()) }}

I get something like

array:2 [▼
  0 => array:7 [▼
    "id" => "5"
    "name" => "creativeOption"
    "label" => "Other"
    "value" => "sdfsdfsdfsdfsdf"
    "campaignCreativesId" => "5"
    "created_at" => "2016-03-01 10:24:38"
    "updated_at" => "2016-03-01 10:24:38"
  ]
  1 => array:7 [▼
    "id" => "4"
    "name" => "creativeOption"
    "label" => "checkboxSelection"
    "value" => "Animated GIF"
    "campaignCreativesId" => "5"
    "created_at" => "2016-03-01 10:24:38"
    "updated_at" => "2016-03-01 10:24:38"
  ]
]

Now I have several checkboxes, and if the value is in the array, I need to check the checkbox. At the moment I have something like this

{!! Form::checkbox('creativeOptions[]', 'Animated GIF', in_array('Animated GIF', $campaign->campaignCreatives->campaignCreativesData->toArray()), ['class' => 'styled', 'id' => 'checkbox1']) !!}

As you can see, Animated GIF is in the array, but the checkbox is not checked.

How can I get the checkbox checked based on what is in the array?

Thanks



via Chebli Mohamed

Validate field with another rule if there is a condition

In Italy the Tax Code is a set of 16 alpha-numeric characters and the Vat Number is a number of 11 digits, but the the Tax Code can be equal to the Vat in certain conditions. I created two custom validation rules in Laravel 5.1 to check these two data types, but I don't know to tell the Framework "If the tax code is a number of 11 digits, validate as Vat Number!".

Here is the code of app/Providers/AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        //validate tax_code
        Validator::extend('tax_code', function($attribute, $value, $parameters, $validator) {
            if($value=='')
                return false;

            if ((strlen($value) == 11) && is_numeric($value))
            {
                //validate as vat number
            }

            if(strlen($value)!= 16)
                return false;

            $value=strtoupper($value);

            if(!preg_match("/[A-Z0-9]+$/", $value))
                return false;

            $s = 0;
            for($i=1; $i<=13; $i+=2){
                $c=$value[$i];
                if('0'<=$c and $c<='9')
                    $s+=ord($c)-ord('0');
                else
                    $s+=ord($c)-ord('A');
            }

            for($i=0; $i<=14; $i+=2){
                $c=$value[$i];
                switch($c){
                    case '0':  $s += 1;  break;
                    case '1':  $s += 0;  break;
                    case '2':  $s += 5;  break;
                    case '3':  $s += 7;  break;
                    case '4':  $s += 9;  break;
                    case '5':  $s += 13;  break;
                    case '6':  $s += 15;  break;
                    case '7':  $s += 17;  break;
                    case '8':  $s += 19;  break;
                    case '9':  $s += 21;  break;
                    case 'A':  $s += 1;  break;
                    case 'B':  $s += 0;  break;
                    case 'C':  $s += 5;  break;
                    case 'D':  $s += 7;  break;
                    case 'E':  $s += 9;  break;
                    case 'F':  $s += 13;  break;
                    case 'G':  $s += 15;  break;
                    case 'H':  $s += 17;  break;
                    case 'I':  $s += 19;  break;
                    case 'J':  $s += 21;  break;
                    case 'K':  $s += 2;  break;
                    case 'L':  $s += 4;  break;
                    case 'M':  $s += 18;  break;
                    case 'N':  $s += 20;  break;
                    case 'O':  $s += 11;  break;
                    case 'P':  $s += 3;  break;
                    case 'Q':  $s += 6;  break;
                    case 'R':  $s += 8;  break;
                    case 'S':  $s += 12;  break;
                    case 'T':  $s += 14;  break;
                    case 'U':  $s += 16;  break;
                    case 'V':  $s += 10;  break;
                    case 'W':  $s += 22;  break;
                    case 'X':  $s += 25;  break;
                    case 'Y':  $s += 24;  break;
                    case 'Z':  $s += 23;  break;
                }
            }

            if( chr($s%26+ord('A'))!=$value[15] )
                return false;

            return true;

        });

        //validate vat number
        Validator::extend('vat_number', function($attribute, $value, $parameters, $validator) {
            if($value=='')
                return false;

            //la p.iva deve essere lunga 11 caratteri
            if(strlen($value)!=11)
                return false;

            //la p.iva deve avere solo cifre
            if(!@ereg("^[0-9]+$", $value))
                return false;

            $primo=0;
            for($i=0; $i<=9; $i+=2)
                $primo+= ord($value[$i])-ord('0');

            for($i=1; $i<=9; $i+=2 ){
                $secondo=2*( ord($value[$i])-ord('0') );

            if($secondo>9)
                $secondo=$secondo-9;
            $primo+=$secondo;

            }
            if( (10-$primo%10)%10 != ord($value[10])-ord('0') )
                return false;

            return true;        
        });
    }

}



via Chebli Mohamed

ErrorException in Controller Argument 2 passed to Controller::__construct()

I am getting this error in my laravel application I am not able to find a fix

ErrorException in FactoryController.php line 39:
Argument 2 passed to Vanguard\Http\Controllers\FactoryController::__construct() 
must implement interface Vanguard\Repositories\Factory\FactoryRepository, 
instance of Vanguard\Repositories\Country\EloquentCountry given

These are the lines that it is pointing to.

//Line 39 is below
public function __construct(CountryRepository $countries, FactoryRepository $factories, RoleRepository $roles, PermissionRepository $permissions)
{
    $this->middleware('permission:system.manage');
    $this->roles = $roles;
    $this->permissions = $permissions;
    $this->countries = $countries;
    $this->factories = $factories;

}

This is the code of FactoriesRepositories

   <?php

namespace Vanguard\Repositories\Factory;

interface FactoryRepository
{
    /**
     * Get all system factorys.
     *
     * @return mixed
     */
    public function all();

    /**
     * Finds the factory by given id.
     *
     * @param $id
     * @return mixed
     */
    public function find($id);

    /**
     * Creates new factory from provided data.
     *
     * @param array $data
     * @return mixed
     */
    public function create(array $data);

    /**
     * Updates specified factory.
     *
     * @param $id
     * @param array $data
     * @return mixed
     */
    public function update($id, array $data);

    /**
     * Remove specified factory from repository.
     *
     * @param $id
     * @return mixed
     */
    public function delete($id);
}

and this is the EloquentFactory

<?php

namespace Vanguard\Repositories\Factory;



use Cache;
use Vanguard\Events\Factory\Created;
use Vanguard\Events\Factory\Deleted;
use Vanguard\Events\Permission\Updated;
use Vanguard\Factories;

class EloquentFactory implements FactoryRepository
{
    /**
     * {@inheritdoc}
     */
    public function all()
    {
        return Factories::all();
    }

    /**
     * {@inheritdoc}
     */
    public function find($id)
    {
        return Factories::find($id);
    }

    /**
     * {@inheritdoc}
     */
    public function create(array $data)
    {
        $factory = Factories::create($data);

        event(new Created($factory));

        return $factory;
    }

    /**
     * {@inheritdoc}
     */
    public function update($id, array $data)
    {
        $factory = $this->find($id);

        $factory->update($data);

        Cache::flush();

        event(new Updated($factory));

        return $factory;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($id)
    {
        $factory = $this->find($id);

        event(new Deleted($factory));

        $status = $factory->delete();

        Cache::flush();

        return $status;
    }
}



via Chebli Mohamed

Using soft delete, delete child of child Laravel 5.1 eloquent model

Parent child soft deleting is simple but when the scenario is extended to children of the child to be deleted from the parent model I'm finding it uncomfortable. This image describes fully the relationship I'm trying to cope withDelete the children of child when parent is deleted

I have a company that has address and product as children. Deleting these is convenient using soft delete. Product, as the child of company has it child which is address, what I want to achieve is when a company is deleted this product address should also be deleted. This is my company model:

class Company extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
    public function products()
    {
        return $this->hasMany('App\Product');
    }

    public function companyAddress()
    {
        return $this->hasMany('App\CompanyAddress');
    }

     public function delete()
    {
        $product = new Product;
        $this->products()->delete();
        $this->companyAddress()->delete();
        $product->productLocation()->delete();
        return parent::delete();
    } 
}

THis is the product model:

class Product extends Model
{
    public function productLocation()
    {
        return $this->hasMany('App\ProductLocation');
    }

    public function delete()
    {
        $this->productLocation()->delete();
        return parent::delete();
    }
}

This is the function in the controller where the deletion is done:

public function destroy($id)
    {
        $company = Company::findOrFail($id);
        if(!$company->user_id === Auth::user()->id)
        {
            return redirect()->route('companyindex')->with('message', 'Sorry, you cannot delete this company');
        }else{
            $company->delete();
            return redirect()->route('companyindex')->with('message', 'Company successfully deleted.');
        }
    }



via Chebli Mohamed