jeudi 31 août 2017

I have and array with multi-dimension i want to get the name of the array and the value of array

Problem in splitting array in PHP.

i need pradm_policy_risk_attr_details_motor_id => 20170825113749907

but in array only ex.

$array = [pradm_policy_risk_attr_details_motor_id => 20170825113749907,
column_11 => BP-2-B1534,
column_14 => Mahindra];

how can get plx...

This is my array

array:19 [
  "pradm_policy_risk_attr_details_motor_id" => array:1 [
    0 => "20170825113749907"
  ]
  "column_11" => array:1 [
    0 => "BP-2-B1534"
  ]
  "column_14" => array:1 [
    0 => "Mahindra"
  ]
  "column_15" => array:1 [
    0 => "Bolero-Camper 2WD (2523 cc)"
  ]
  "column_61" => array:1 [
    0 => ""
  ]
  "column_92" => array:1 [
    0 => "0.000000"
  ]
  "column_28" => array:1 [
    0 => "[SELECT]"
  ]
  "column_29" => array:1 [
    0 => "Closed"
  ]
  "column_30" => array:1 [
    0 => "0"
  ]
  "column_32" => array:1 [
    0 => "Owner Driver"
  ]
  "column_33" => array:1 [
    0 => ""
  ]
  "column_35" => array:1 [
    0 => "Excavator"
  ]
  "column_36" => array:1 [
    0 => ""
  ]
  "column_69" => array:1 [
    0 => ""
  ]
  "column_70" => array:1 [
    0 => ""
  ]
  "column_24" => array:1 [
    0 => ""
  ]
  "column_16" => array:1 [
    0 => "Select"
  ]
  "column_121" => array:1 [
    0 => ""
  ]
  "column_122" => array:1 [
    0 => ""
  ]
]

i took almost 3 days to solve this problem. please somebody help me.please expertise if you have solution or idea about this comment me with answer below i am in urgent. #from Bhutan....



via Chebli Mohamed

Laravel, force 1min gap between article post

I want to force a 1min gap between two article post by same user. This is to prevent accidental double post and hopefully reduce spam.

right now I am doing this.

in user model

public function canPostNewArticle()
{
    $article = Article::where('user_id', $this->id)->latest()->first();
    if ($article == null)
    {
        return true;
    }
    $date = $article->created_at->timestamp;
    $currentTime = Carbon::now()->timestamp;

    $diff = ($currentTime - $date) / 60;
    return $diff > 1;
}

I am using this function to check before creating new article. Is there a better way to do this.



via Chebli Mohamed

Cannot set content with Laravel middleware

I'm trying to append some query log data to my ajax requests via a middelware.

use DB;
use App;
use Closure;

class Queries
{
    public function handle($request, Closure $next)
    {
        if (env('APP_QUERIES')) {
            DB::enableQueryLog();

            $response = $next($request);

            $content_type = substr($response->headers->get('Content-Type'), 0, 16);

            if ($content_type === 'application/json') {
                $content = $response->original;

                $queries = DB::getQueryLog();

                $content['queries'] = $queries;

                $response->setContent($content);
            }

            return $response;
        }

        return $next($request);
    }
}

In the docs it shows $mixed but seems it only excepts string?

http://ift.tt/2ensX6J

When I put json_encode around the $content it works, but in another app I don't have this and it's the same version of Laravel so not sure what's going on.



via Chebli Mohamed

BadMethodCallException App\User::create() when seeding with zizaco

I'm having an error when seeding to the database using laravel 5.5 the error message is below and there is my users class and my seeder class. What is happening is that one record is being inserted at a time when calling db:seed but after the first call it says BadMethodException rest below

[BadMethodCallException]
Call to undefined method App\User::create()

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Eloquent;

class User extends Eloquent
{
    use EntrustUserTrait;

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

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

<?php

use App\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {       
        foreach (range(1, 100) as $index) {
            $faker = Faker::create();
            $user = User::create([
                'name' => $faker->firstName . ' ' . $faker->lastName,
                'email' => $faker->email,
                'password' => bcrypt('secret')
            ]);
        }
    }
}



via Chebli Mohamed

Laravel 5.4 Set All Authentication Routes Except Logout Route - Using Custom Logout Route/Controller

So for some reason I thought I came across the answer to this question before, but for the life of me I can't find the answer again, either through Google or StackOverflow. This might just be a rubber duck question and I'm sorry if it is, but I hope this question will be of some use to someone someday with this same issue.

Let's assume we're starting with a fresh installation of Laravel 5.4. I run the php artisan make:auth command in my terminal and it sets up the Authentication Scaffolding for me. Now in my /routes/web.php file I see the following line:

Auth::routes();

Which is awesome and the route list has all the Authentication routes listed including the logout route defined. (Typed php artisan r:l to double check) Now I want to set a custom logout route for the user using the a custom Logout Controller. Now, I thought that there was a method you could chain onto a route called 'except()' but for the life of me I can't find any information in the documentation about this method. I don't know if this method even exists let alone know what to pass it.

So the question is simple. How do I include all authentication routes except the logout route, and then i'll define the logout route using the following line.

Route::get('logout', 'LogoutController@userLogout')->name('logout');

Sorry if this is a duplicate entry, I've used the search bar for the past hour and nothing is answering my question.



via Chebli Mohamed

mercredi 30 août 2017

Search Query with Pagination

When I run a search with constraints and get more than the set paginate amount, if I change the pages the search query is lost and my default page 2 is shown rather than the 2nd page of results for the query ran by a user.

How do i fix this?

        $batsQuery = Batsmen::where('approved', '=', 1)->leftJoin('reviews', 'reviews.batsmen_id', '=', 'batsmens.id')->select('batsmen.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('batsmen.id');

        if(!empty($name)){
            $batsQuery->where('batsmenname', 'LIKE', '%'.$name.'%')->get();
        }
        if(!empty($cat)){
            $batsQuery->where('categories_id', $request->input('categories_id') )->get();
        }

        $batsmen= $batsQuery->paginate(8);

return view('page.search')->withBatsmen($batsmen)



via Chebli Mohamed

Get an array of dates using Carbon in Laravel 5.4

I'm a beginner in Laravel/PHP, and I'm using the Carbon class to manage dates. I need to get an array of datetime by month, from the beginning of the previous year till this month, the output should be as follow :

$dates = [
    '2016-01-01 00:00:00',
    '2016-02-01 00:00:00',
    '2016-03-01 00:00:00',
    '2016-04-01 00:00:00',
    '2016-05-01 00:00:00',
    '2016-06-01 00:00:00',
    '2016-07-01 00:00:00',
    '2016-08-01 00:00:00',
    '2016-09-01 00:00:00',
    '2016-10-01 00:00:00',
    '2016-11-01 00:00:00',
    '2016-12-01 00:00:00',
    '2017-01-01 00:00:00',
    '2017-02-01 00:00:00',
    '2017-03-01 00:00:00',
    '2017-04-01 00:00:00',
    '2017-05-01 00:00:00',
    '2017-06-01 00:00:00',
    '2017-07-01 00:00:00',
    '2017-08-01 00:00:00',
];

I can't figure out how to do this, thank you in advance.



via Chebli Mohamed

PHPUNIT TEST No hint path defined for [xxx]

I'm trying to run unit tests on my controller using oceshtral/testbench I have the following setup

protected function getPackageProviders($app)
    {
        return [
            LaravelModulesServiceProvider::class,
            CoreServiceProvider::class,
            BrokerquotesServiceProvider::class,
            ViewServiceProvider::class,
            UserServiceProvider::class,
        ];
    }

    protected function getEnvironmentSetUp($app)
    {
        $app['path.base'] = __DIR__ . '/..';
        $app['config']->set('app.debug', true);
        $app['config']->set('app.log','single');
        $app['config']->set('app.log_level','debug');
        $app['config']->set('translatable.locales', ['en']);
        $app['config']->set('modules.paths.modules', __DIR__ . '/../Modules');
        $app['config']->set('database.default', 'mysql');
        $app['config']->set('database.connections.mysql', array(
            'driver' => 'mysql',
            'database' => 'dohlapse',
            'host' => 'localhost',
            'port' => '3306',
            'username' => 'homestead',
            'password' => 'secret',
        ));
        $app['config']->set('uuid.default_uuid_column','uuid');
        $app['config']->set('asgard.user.driver', 'Sentinel' );

        return $app;
    }

and I call a test

public function setUp()
    {
        parent::setUp();

        $faker = Faker\Factory::create();

        $this->crawler = $this->call('POST', 'brokerquotes.requests', array_merge(
          factory(Request::class)->make()->toArray(),
          factory(\Modules\Brokerquotes\Entities\Insuree::class)->make(['user_id' => null])->toArray()
          ,['meta_key' => 'brokerquotes__loan']
          ,$this->generateLoanMetaData()
          ,['email' => $faker->email]
        ));
    }

    public function getEnvironmentSetup($app)
    {
      $app = parent::getEnvironmentSetup($app);

      $app['router']->post('brokerquotes.requests', [
        'uses' => '\Modules\Brokerquotes\Http\Controllers\RequestController@store'
      ]);

      return $app;
    }

However my tests to the contoller are coming back with

No hint path defined for [brokerquotes]. /home/vagrant/Code/dohlapse/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php line 112

I'm not to familiar with integration testing but wondering it its because my views aren't loaded.

What is causing this error?



via Chebli Mohamed

How to retrieve a file with an ajax request?

I would like to send a file via an ajax request, however I also have multiple selects/inputs used in my form, so I used form.serialize();

My ajax request is below:

('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: $("#form").attr("action"),
        dataType: 'json',
        async: false,
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
        success: function (data) {//do stuff

Now because of form.serialize(), it does not even detect that I have uploaded a file, I'm guessing. Is there anyway around this so it does not interfere with the other functionality of form.serialize.

My html is:

<form class="form-horizontal" method="POST" action="/roa/" id="form" enctype="multipart/form-data" files=true>
   <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
   <input type="file" name='cv'>
//all my other inputs, including many text/select statements which maybe cloned
</form>

Could anyone provide any guidance?



via Chebli Mohamed

Convert eloquent query constraints to function in Laravel model (eager loading)

i want to convert this part:

'likes as is_liked' => function($query){
                        $query->where('user_id', auth()->user()->id);
                    }]);
                }

and this part :

'post' => function($query){
                return $query->withCount(['comments', 'likes', 'likes as is_liked' => function($query){
                    $query->where('user_id', auth()->user()->id);
                }]);
            }

of below query to function in Laravel model , but i dont know how can i do this; is there any way to add this constraints in Laravel model and summarize the code in controller action?

$bookmarks = auth()->user()->bookmarks()
            ->with(['post.user', 'post.categories', 'post' => function($query){
                return $query->withCount(['comments', 'likes', 'likes as is_liked' => function($query){
                    $query->where('user_id', auth()->user()->id);
                }]);
            }])
            ->paginate(10);

Laravel version : 5.4



via Chebli Mohamed

Laravel repeated select list validation

I have form that has a repeated select list like the following:

<select class="form-control set-25" name="equipments[:selectName:-1]">...
<select class="form-control set-24" name="equipments[:selectName:-2]">....
<select class="form-control set-8" name="equipments[:selectName:-3]">....

I want to validate each one of those lists.

public function installCavitySave(Request $request)
    {

        $this->validate(request(), ['equipments.*' => 'required']);
       dd(request());
    }

However, the rule does not work. When I tried $this->validate(request(), ['equipments' => 'required']) It works only if there is no any select option values selected but if one of them is selected the validation allow others to be null.

I need the validation to validate every select list named equipments[x] where x is any key supplied to the elements name attribute.



via Chebli Mohamed

How to design a user system with socialite user and local user?

I use Laravel 5.4 framework and mongodb to build an SSO application.I have already implemented the local user login and register function.

Now I need add socialite user auth to my application.I add some Laravel Socialite Package.

The problem is should I make collections for every kind of socialite platform?

I think the easy way is that add a field oauth to the users collection. And when user login with a socialite platform I can get the user's socialite ID.At last I just add the socialite platform name and ID to field oauth.The data object like this:

{
 "username":"foo",
 "oauth":{
   "github":{"id":"1234abc","token":"123abc"}
 }
}

But I found this users collection for login action may be slow.Because the key to validate user whether registered with the socialite platform or not need scan the "oauth" field and its sub object ('github','facebook',.etc)

If I make a github-user collection for that github platform then I only need to check the github-user collection by field id and it may be fast.

Sorry about my mongodb useage because I am new for mongodb and used mysql for some years.With mysql I must make table for each socialite platform.

PS: user amount is about 5 million.



via Chebli Mohamed

Laravel Login works great on local machine but not on server

I just copied my local Laravel project to a live server and encountered an issue I never had before. When I try to login with the builtin laravel register/login form it redirects right back to the login form. It doesn't show an error, nor are there any errors in the log so i'm not sure what to look for. This has been driving me nuts all day. I'm not sure which code to show but this is my routes.php

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

This is my authenticate.php

public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {

            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

My authcontroller.php

public function __construct(Guard $auth, Registrar $registrar)
    {

            $this->auth = $auth;
            $this->registrar = $registrar;
            $this->middleware('guest', ['except' => 'getLogout']);

    }

I'm not sure what else I would need to show...

PS. Just to make sure, I created a new user on the live server and tried to log in, didn't work either. Can this be some token issue?

(Laravel 5.0.35)

Any help would be highly appreciated... Thank you!



via Chebli Mohamed

is it possible to change the path to PHP that the Laravel task scheduler uses

I have a Laravel 5.4 app which is on shared hosting and the cron job isn't working. I have set the command up in the kernel.php like so:

$schedule->command('eoddsmaker:get_events')
         ->withoutOverlapping()
         ->appendOutputTo(storage_path('logs').'/cron-get_events.log')
         ->everyMinute();

And if I just run /usr/bin/php-5.6 artisan eoddsmaker:get_events from the command line it runs fine. When it gets called by the cron job though it doesn't run. This is my cron definition:

* * * * * /usr/bin/php-5.6 /var/sites/c/http://ift.tt/2wIVAWA schedule:run >> /var/sites/c/http://ift.tt/2wo7HWw 2>&1

I can see from the cron logs on the server that this task is running every minute and everytime that it runs the following output gets added to the cron.log file:

Running scheduled command: '/usr/bin/php' 'artisan' eoddsmaker:get_events > '/dev/null' 2>&1
X-Powered-By: PHP/5.6.8
Content-type: text/html; charset=UTF-8

So to dig a bit deeper if I look in the cron-get_events.log file that I have configured the task to send output to the following gets output every time it runs:

Warning: Unexpected character in input:  '\' (ASCII=92) state=1 in /var/sites/c/http://ift.tt/2wIVAWA on line 31

Parse error: syntax error, unexpected T_STRING in /var/sites/c/http://ift.tt/2wIVAWA on line 31

Because I'm on shared hosting the default PHP version is 5.2 and I have to add a rule in the htaccess file to get it to use PHP 5.6. If I forget to add the rule I get the same error as the one that is in the cron-get_events.log so this leads me to believe that the reason the command isn't working is because when the scheduler runs it is calling the command with /usr/bin/php as the path to PHP rather than /usr/bin/php-5.6

Is there a way to configure the task scheduler to use a different path to PHP?



via Chebli Mohamed

How to Preform a where query on a relation table Laravel?

I have an order with orderLines and an orderLine has a product.

I want to only retrieve orderLines where product type != Partkit. So i want to query the Product table where type != Partkit.

How do i do this? Order query:

$order = Order::with('orderLines.product')->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

What i tried:

$order = Order::with('orderLines.product')->whereHas('orderLines.product', function($query) {
            $query->where('type','!=', 'Partkit');
        })->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

this allways return NULL which is not what i want and isn't correct...

any help is appreciated



via Chebli Mohamed

Laravel 5.4 - Jquery Ajax Method post does not exist

I am getting this error Method post does not exist., and I can't figure it out what is going on. My routes:

Route::group(['middleware' => ['auth']], function () {
    Route::get('/', 'SiteController@index');
    Route::get('/dashboard', 'DashboardController@index')->middleware('role');

    Route::post('/search', 'UserController@search')->middleware('role');
});

HTML code:

<form class="navbar-form" role="search" id="employees-search">

    <div class="input-group add-on col-md-6">

    <div class="input-group-btn">
        <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i>    </button>
    </div>
        <input class="form-control" placeholder="Search" name="employee-name" id="employee-name" type="text">

    </div>
</form>

JS code:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

// Search users

$('#employees-search').on('keyup', '#employee-name', function(){


    let
        $this = $(this),
        name  = $this.val();

    if(name.length > 2){

        $.ajax({
            url: '/search',
            type: 'POST',
            data: $('#employees-search').serialize(),
            contentType: 'application/json',
            dataType: 'json',
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });

    }


})

UserController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function search(Request $request)
    {
        dd($request->post('employee-name'));
    }
}

What am I doing wrong here?



via Chebli Mohamed

Filter record using from date and to date

In my case, I have to filter records by using from-date and to-date ,

I have tired with where between But it works only if I enter both from-date and to-date

public function searchCustomers(Request $request, CustomerProfile $user)
{
    $fromDate = $request->get('from_date');
    $toDate = $request->get('to_date');
    $user = $user->newQuery();

    if ($request->has('city')) {
        $user->where('city', $request->input('city'));
    }

    if ($request->has('from_date') && $request->has('to_date')) {
        $user->whereBetween('date_of_visit', [$fromDate, $toDate]);
    }
    $results = $user->get();

    return response()->json($results);
}

But sometimes I just want to search with only from-date, and sometimes I want to search with only to-date, and sometimes I want to search with both from date and to-date,

How can I get above output??



via Chebli Mohamed

Laravel calling model from controller? Is this the right approach?

I am trying to split some code and let model handle all database stuff, such as create, retrieve etc.

At the moment all of that code was in the controller and I quickly realized that code is very messy so instead I wanted to do something like this:

public function incompletedEntity(EntityRequestPartial $request)
{
    $partial_entity = EntityTrash::saveEntity();
}

And my model:

public static function saveEntity(Request $request)
    {
        $entity  = new EntityTrash();
        $entity->lat = $request->input('lat');
        $entity->lng = $request->input('lng');
        $entity->slug = $request->input('name');
        $user_id = Auth::id();
        $entity->name = $request->input('name');
        $entity->type = $request->input('type');
        $entity->email = $request->input('email');
        $entity->tags = $request->input('tags');
        $entity->slug = $user_id;
        $entity->building_name = $request->input('building_name');
        $entity->address = $request->input('address');
        $entity->town = $request->input('town');
        $entity->postcode = $request->input('postcode');
        $entity->telephone = $request->input('telephone');
        $entity->save();
    }

However, I cannot call that function because I am not passing an argument from the controller, what is the right approach for this? Should I do $request->input in controller and assign it to an array maybe? and deal with it in the controller?



via Chebli Mohamed

Larevel Cannot use object of type stdClass as array when using Query Builder

Short Version of question:

I received Cannot use object of type stdClass as array when using Query Builder, but works fine with Eloquent. How I solve that issue?

Long Version of question:

When I using method 1 there is a error.

Error : Cannot use object of type stdClass as array (This gives for view foreach start line)

But when I using method 2 there is no error.

I wanted to know why it return error when I using method 2. How I correct it?

Method 01 (In Controller)

$parents = DB::table('stuparents');
$parents = $parents->orderBy('first_name');
$parents = $parents->get();

Method 02 (In Controller)

$parents = StuParents::orderBy('first_name');
$parents = $parents->get();


In View

@foreach($parents as $student)

//Code

@endforeach



via Chebli Mohamed

Passing data for all views in Laravel

I have a website that had a calculation scores function, and I want to pass the score for all views in my website.

Laravel version 5.4



via Chebli Mohamed

how to post category_id on desinger table laravel

hi i have 3 table 1st is products 2nd is category 3rd is designer

products and category is many to many relationship product belongsto designer & designer hasMany products designer belongsto category & category hasMany designers

here is my table

product

Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('image');
        $table->string('stock');
        $table->string('title');
        $table->string('slug')->unique();
        $table->string('gender');
        $table->text('description');
        $table->integer('price');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')
                    ->onDelete('restrict')
                    ->onUpdate('restrict');

        $table->dateTime('published_at');
    });

designers table

Schema::create('designers', function (Blueprint $table) {
        $table->increments('id');

        $table->string('name')->unique();
        $table->string('slug')->unique();
        $table->timestamps();
    });

category table

Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });

    Schema::create('category_product', function (Blueprint $table) {

        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories')
                    ->onDelete('restrict')
                    ->onUpdate('restrict');

        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')
                    ->onDelete('restrict')
                    ->onUpdate('restrict');

        $table->timestamps();
    });

adding missing column in products table

Schema::table('products', function (Blueprint $table) {
        $table->integer('designer_id')->unsigned();
        $table->foreign('designer_id')->references('id')->on('designers')
                    ->onDelete('restrict')
                    ->onUpdate('restrict');
    });

adding missing column in designer

Schema::table('designers', function (Blueprint $table) {
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')
                    ->onDelete('restrict')
                    ->onUpdate('restrict');
    });

here is my controller

public function productpost(Request $request){

    $this->validate($request, [
        'title' => 'required|max:255',
        'description' => 'required',
        'price' => 'required',
        'image' => 'image|required',
    ]);

    $designer_name = $request->designer;
    $designer_slug = str_random(40);
    $designer = designer::where('name', $designer_name)->firstOrCreate(
            ['name' => $designer_name], ['slug' => $designer_slug]
        );
    $designer->name = $designer_name;
    $designer->slug = $designer_slug;
    $designer->save();
    $designer_id = $designer->id;
    $product = new Product;
    $product->title = $request->title;
    $product->designer_id = $designer_id;
    $product->description = $request->description;
    $product->price = $request->price;
    $product->stock = $request->stock;
    $product->gender = $request->gender;
    $product_slug = str_random(40);
    $product->slug = $product_slug;
    $product->user_id = Auth::user()->id;
    $product->published_at = Carbon::now()->format('Y-m-d');
    if($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        $name = $timestamp. '-' .$file->getClientOriginalName();
        $file->move(public_path().'/images/product/', $name);
        $product->image = $name;
        $thumb = Image::make(public_path().'/images/product/' . $name)->resize(1200,1800)->save(public_path().'/images/product/thumb/' . $name, 90);  
    }
    $product->save();
    $productsearch = product::where('slug', $product_slug)->firstorfail();
    $product_id = $productsearch->id;
    $categoryname = $request->category;
        foreach ($categoryname as $name) {
            $category = category::firstOrNew(['name' => $name]);
            $category->designer_id = $designer_id;
            $category->save();
            $category->products()->attach($product_id);
        }

    return Redirect::back()->with('status', 'Post Success');

missing is product need designerid
designer need category_id category need product_id how to solve this on controller thank you



via Chebli Mohamed

Laravel 3 way pivot when two column come from same id

How can i set up this, i'm trying to build a student and teacher lesson schedule, here is my code.

 Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->text('photo_url')->nullable();
        $table->string('firstname');
        $table->string('lastname');
        $table->string('username')->unique()->nullable();
        $table->date('date_of_birth');
        $table->string('email')->unique();
        $table->string('password');
        $table->timeTz('timezone');
        $table->integer('is_active')->default(0);

        $table->tinyInteger('verified')->default(0);
        $table->string('email_token')->nullable();

        $table->text('address');
        $table->string('district');

        $table->rememberToken();
        $table->timestamps();
    });

And then for the lesson schedules

Schema::create('lessons', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('status'); //0 - not started, 1 - completed, 2 - no show

        $table->dateTime('start_at');
        $table->dateTime('end_at');

        $table->dateTime('started_at');
        $table->dateTime('ended_at');

        $table->string('unique_id')->unique();

 $table->integer('teacher_id')->unsigned();
          $table->foreign('teacher_id')
              ->references('id')->on('users')
              ->onUpdate('cascade')
              ->onDelete('cascade');

          $table->integer('student_id')->unsigned();
          $table->foreign('student_id')
              ->references('id')->on('users')
              ->onUpdate('cascade')
              ->onDelete('cascade');
        $table->integer('completed');
        $table->timestamps();
    });

if i want to display my data on the view for this. How do i add the relations to the various models and how do i display them to view.

I believe this is a belongsToMany relations

Pleas help!

how do i do this?

Not sure if i clear enough



via Chebli Mohamed

Different relationships on different model types Laravel

I wonder how you'd go about my problem where I am going to display different types of events. For example 2 different events could be a soccer event and a formula1 event.

In these 2 scenarios there are different types of participants. In a soccer game this would be the 2 teams, and in a formular1 event it would be all the drivers.

Here are my Eloquent example of what I would like to do:

public function participants()
{
    if ($this->type == 'soccer_game') {
        return $this->hasMany(EventTeam::class);
    } else if ($this->type == 'formula1_race') {
        return $this->hasMany(EventDriver::class);
    }
    return $this;
}

But when trying this and try to load it I get the error "Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()".

I think I need a push in the right direction.

Thanks in advance.



via Chebli Mohamed

How test unauthorized method in Laravel?

I have controller Post with typical CRUD method's. I have a PostPolicy, in which:

public function destroy(User $user, Post $post)
{
    $user->id === $post->author_id;
}

I want to write test for this. When I check if user delete his own post - all OK.

But when I test if other user user can delete not his own post, laravel test send error:

Illuminate\Auth\Access\AuthorizationException: This action is unauthorized.

How bypass it or which has another method for write this test?

Code

$user = factory(User::class)->create([
        'id' => 3,
        'role_id' => 2
    ]);
factory(Post::class)->create([
        'id' => 30,
        'editor_id' => 2,
    ]);

    $this->delete('/api/posts/30', [], [
        'authorization' => "Bearer {$user->api_token}",
        'accept' => 'application/json',
    ])->assertJson([

    ]);;



via Chebli Mohamed

How to make localization of dates Laravel?

There is a withdrawal date



on multilingual website, 5 languages. Is there a way of locating months?



via Chebli Mohamed

html Checkbox in laravel send true on every request

Laravel send true in every request with different html tags:




And it send "on"; i want to send 1 or 0 What can i do ?



via Chebli Mohamed

Laravel - How to write Multiple conditions in where clause?

Actually my query is - SELECT * FROM company WHERE status<>$status AND type=$b1 AND type=$b2

How to do this in laravel...?

I did this in laravel but it is not working..

$data['Company']=DB::table('company')->where([["status","<>",$status], ["type","=",$b1],["type","=",$b2]])->get();

Please help me on this..



via Chebli Mohamed

Firebase push notification custom token for all device

I want to generate custom token then i use one token for all device ( android, ios, web ,etc ). My backend code writeing in laravel 5. Does anyone can help me?



via Chebli Mohamed

How to change Laravel crudbooster datamodal to a select2

The below code works and I can create a measurement modal that displays the kgs, grams etc but was wondering if there is a way to do it as a dropdown select2 instead as the list is quite short. the two I've tried below show just the label but no select2 box. Any ideas? regards

$columns = [];
        $columns[] = ['label'=>'Quantity','name'=>'quantity','type'=>'number','required'=>true];
        $columns[] = ['label'=>'Measure','name'=>'measures_id','type'=>'select2','datatable'=>'measures,measure'];
        $columns[] = ['label'=>'Measure2','name'=>'measures_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-5','datatable'=>'measures,measure'];
        //  $columns[] = ['label'=>'Measure','name'=>'measures_id','type'=>'datamodal','datamodal_table'=>'measures','datamodal_columns'=>'measure','datamodal_select_to'=>'measure:measure','required'=>true];



via Chebli Mohamed

what is best way to add another language to laravel website?

i created new website by laravel in ENG language and working perfectly, right now i decide to add another language.i searching in google and find some solution but its not sufficient for me. in all solutions,just translated a few word to another language ( for example "Hello" = > "Hallo" ) and these solutions good for interface (UI),using it like words in admin panel or something like that. but i try to find best way to display my content ( long text or bullet list) in another language.



via Chebli Mohamed

How to display image laravel 5.4

I'm trying to display image in view using following code but it does not showing

    <img src="" style="width:150px; height:150px; float:left; 
border-radius:50%; margin-right:25px;">

images are stored inside \storage\app\public\users

enter image description here



via Chebli Mohamed

How to pass some taken value in a view and then send it to another view in laravel?

I have a table called pages then in one of my views I used this table as:

@foreach ($pages as $page)
            @if ($subject->names == $page->related_subject)
              <li><a href=""><i class="fa fa-circle-o">
              </i><span> </span></a>
             </a></li>
            @endif
@endforeach

in my loop I put a link to another view and I want to send the record to that view with this link.



via Chebli Mohamed

Laravel 5.4 restful api

How to rewrite this code?

protected function mapWebRoutes(Route $route)
{
    Route::middleware('web')
         ->namespace($this->namespace)
         ->group(base_path('routes/web.php'));
}

When I am sending POST request I want to avoid VerifyCsrfToken



via Chebli Mohamed

where does laravel controller function returns its response?

where does laravel controller function returns its response?

I have an APICONTROLLER and it has a function test() which returns a response as

return response()->json($response);

Now, where does the control goes from here?



via Chebli Mohamed

API call returns on postman, but returns a 500 internal server error when called and logged in browser

This is related to Laravel 5.4 and its Passport Password Grant.

I have routes for obtaining an access_token for the user to use that works completely fine.

I also have a route to refresh the token should the current access token expire.

When I use Postman to hit the route

http://ift.tt/2x3PnEF

I get this back which is valid:

"data": {
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOi...deleting most of it.",
    "expires_in": 600
}

However when I hit the route from the browser, using axios via this code:

let  headers = { 'Content-type': 'application/json' }
return axios.post("http://ift.tt/2x3PnEF", {headers: headers}).then(res => {
    if (res) return res;
        }).catch(err => {
            if (err) return err.response;
        });

I get an HTTP 500 Error status code.

I'm tailing the laravel log for errors as well and this is the stack trace.

[2017-08-30 07:21:41] local.ERROR: GuzzleHttp\Exception\ClientException: Client error: POST http://ift.tt/2vDGzBN resulted in a 400 Bad Request response: {"error":"invalid_request","message":"The request is missing a required parameter, includes an invalid parameter value, (truncated...) in /home/vagrant/Code/work/vendorgraphs-api/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

The other part of this error is that it may be a malformed value.

Doesn't make sense to me and I've tried everything from making curl requests directly from PHP code and also used http_query_builder functionality.

Cache-Control →no-cache, private
Connection →keep-alive
Content-Type →application/json

This is what's set on Postman with the request. I am sending those headers from the browser as well. Any ideas on what might be causing the issue? This is driving me crazy.



via Chebli Mohamed

Laravel Eloquent where and order conditions only if needed

Please look at following code. This code I have written with Codeigniter. What I need to highlight it where condition and order conditions works only if those post requests are set. Otherwise it i just select * from student.

Codeigniter Code

$this->db->select('*');
$this->db->from('student');
if($this->input->post('first_name') != NULL){
    $first_name = $this->input->post('first_name');
    $this->db->where('first_name', $first_name);
}

if($this->input->post('last_name') != NULL){
    $last_name= $this->input->post('last_name');
    $this->db->where('last_name', $last_name);
}

if($this->input->post('order_by') != NULL){
    $order_by= $this->input->post('order_by');
    $this->db->order_by($order_by);
}

$query = $this->db->get();

Laravel Code

I am going do the same thing with laravel.

$first_name = $request->input('first_name');
$last_name = $request->input('last_name');
$order_by = $request->input('$order_by');

$students = Student::orderBy($order_by)
      ->where('first_name',$first_name)
      ->where('last_name',$last_name);
      ->paginate(10);

I able to run above code. The code works when there all post requests.

But if there is no first_name post request I need to remove ->where('first_name',$first_name).

If there i no order_by post request, I need to remove orderBy($order_by).

How to do it with above Laravel code.



via Chebli Mohamed

mardi 29 août 2017

laravel 5.4 common arrays, constants, common functions?

laravel 5.4, where to put common arrays, constants, common functions, so that it is accessible every where eg. in controller, model, mailables, etc. eg. $common_array = array("1" => "a", "2" => "b");

where to put above array, so that, it can be accessible everywhere just like configuration.



via Chebli Mohamed

Filter AngularJS routes based on Laravel Auth user data

I am trying to build a dashboard that uses AngularJS and Laravel for my API. I would like to know if there is a way to add a global filter for certain users when they try to access restricted routes. Something that does not need to be added to every controller in my Angular app.



via Chebli Mohamed

Select and Groupby in Laravel

How can i use this script in laravel controller?

 SELECT MAX(branch_tbl.branch_name) AS Branch_Name, COUNT(staffinfo.branchID) AS Count_Branch
    FROM branch_tbl
    LEFT JOIN staffinfo ON staffinfo.branchID = branch_tbl.branch_id
    GROUP BY branch_tbl.branch_id;



via Chebli Mohamed

password reset feature from laravel 5.2

I tried the password reset feature laravel 5.2, however when I tried to submit a password reset, perform an error like this:

Cannot insert the value NULL into column 'EMAIL', table 'KSP_ASTRA.dbo.PASSWORD_RESETS'; column does not allow nulls. INSERT fails. (SQL: insert into [password_resets] ([email], [token], [created_at]) values (, 97fdbc9463ea9807b5da729182960a31293e482ae33b9e42f81b6eee35bd6a4f, 2017-08-30 02:24:01.000))

the column email unreadable, even though I didn't change the default display auth password reset laravel.

please, If anyone could help



via Chebli Mohamed

Maatwebsite import csv Maximum execution time of 60 seconds exceeded error

I am making an application with upload csv file. but I am having an Maximum execution time of 60 seconds exceeded error. How to handle this on Laravel 5.3? I am uploading a file with a minimum of 1000 lines filling up sql columns. Thank you so much



via Chebli Mohamed

If I use Mailgun with Laravel for a webform, who do I get my email account from, my DNS provider or my host provider?

I have a website setup using Laravel which uses a webform for visitors to send email to me. I use Mailgun as the driver. I have my domain registered with Namecheap. They said they are my DNS provider. I set up my website using Forge and DigitalOcean.

I have two email accounts with Namecheap's Private Email subscription. The instructions at Mailgun told me to change the setting from Private Email at Namecheap to use MX Records. When I did that I was able to get Mailgun working but I no longer could use the email accounts I had with Namecheap. Essentially what Namecheap is saying is that I can't have email addresses with my domain and use Mailgun at the same time. They said it is because I can't have both my email addresses and Mailgun configured on one domain. That can't be true.

What do I need to do to set up email addresses with my domain and use Mailgun as my email driver with Laravel?



via Chebli Mohamed

How to allow & symbol when using htmlspecialchars()

I am using htmlspecialchars() on my site to display status post from users. The status post is being saved to my database and pulled to show in their timeline.

I'm using laravel 5.3

The problem is if someone post something like: Netflix & Chill, this turns into Netflix &amp; Chill

How can i still use htmlspecialchars() so that I can keep my site safe, but still show the proper text instead of turning even & symbol into &amp;



via Chebli Mohamed

laravel 5.4 access current user data in layout.blade

I want to get data about the current user in the header of the site, what would be displayed on each page! I tried to use , but only works on the login page. When I go to another page, I get an error: "Trying to get property of non-object". How to fix it?



via Chebli Mohamed

how do I order eager relationship using with()

I need to order

Content::with('blocks.settings')->where('slug', $slug)->first();

blocks by a 'order' column, how can I do that?

i am aware of this approach:

with(array('model' => function($query) {
        $query->orderBy('result', 'DESC');
    }))

but I am not sure how that would work in my case? I am using nested eager loading and it seems to me that above approach will only work for single level eager load?

Can someone give me an idea how to solve this?



via Chebli Mohamed

How to insert into mutiple tables with Laravel

I am trying to insert into 2 different tables(House and Contact) using a single method.

public function store(HouseRequest $request){

    $dataForm = $request->all();

    $house = House::create($dataForm); //Insert into House table
    $contact = $house->contact()->create($dataForm['contact']); //Insert into Contact table


    return back('dashboard/houses')->with('message', 'Success');
}

Here is my table Contact:

  Schema::create('contacts', function (Blueprint $table) {    
        $table->integer('house_id')->unsigned();
        $table->string('name', 255);
        $table->char('phone', 11);
        $table->timestamps();

        $table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade')
  }

House Model:

public function contact(){
    return $this->hasOne(Contact::class);
}

It works fine (inserts into both tables), but after submitting the form, I got this:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from contacts where id = 0 limit 1)

I don't know why it is running the query above. How can I get rid of this error?



via Chebli Mohamed

include class with autoload.php but getting class not found error

I tried to use jasonmapper just as written in manual. I required autoload.php file, and when construct JasonMapper object, i go class not found exception.

(1/1) FatalThrowableError Class 'App\Http\Controllers\JsonMapper' not found

Here is my code

namespace App\Http\Controllers;

require __dir__.'/../../../vendor/autoload.php';
use Illuminate\Http\Request;
use App\Http\Games\Numbers;

class ApiController extends Controller
{
    public function home()
    {
        $client = new \GuzzleHttp\Client();
        $res = $client->request(
          'GET',
          $testurl
        );
        $json = json_decode($res->getBody());
        $mapper = new JsonMapper();// error occurs at this line
        $numbers = $mapper->map($json, new Numbers());
        return json_encode($numbers);
    }
}



via Chebli Mohamed

laravel 5.4 add index to field

I know this can easily be achieved by doing this:

$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->unsignedInteger('gender_id');
$table->date('date_of_birth');
$table->date('active_in_sport');
$table->unsignedInteger('people_type_id');
$table->timestamps();

$table->unique([
    'first_name',
    'last_name'
]);
$table->index('gender_id');
$table->index('people_type_id');

The downside of this is that Laravel first creates the table and than runs an alter table query. At the moment I run into a foreign key error because of this so I'd like to add the index to the field in the create statement. How can I do this?



via Chebli Mohamed

How to remove a many-to-many relationship based on the Pivot Table information

I am in need to detach records from my pivot table, based on info stored in it.

So I have three tables, 1) Activity 2) activity_submissions 3) Submissions

One activity can have many submissions and one submission can have many activities, they share a many to many relationship. Now there is a catch: the activity_submissions table has a description column in it too.

This is the activity_submissions table:

id | activity_id | submission_id | desription

So I have three records as below:

1 | 20 | 1 | "First"
2 | 20 | 1 | "Second"
3 | 20 | 1 | "Third"

I only want to reove the one with description "Third".

I tried using detach, but that removes all of them:

$activity=\App\Activity::find(20);
$submissions=$activity->submissions()->where('submission_id','=','1')->get();
for($i=0; $i<$submissions->count(); $i++){
    if ($submissions[$i]->pivot->description == "Third"){
       $submissions[$i]->activities()->detach();
    }
}

But this code detaches all my records, how would I go about doing this? I am using Laravel 5.0.



via Chebli Mohamed

Error call to member function path on null Laravel 5

I have to get file info using Laravel

The input form have

<input type="file" name = "avator">

path = $request->file('avator')->path();



via Chebli Mohamed

nam run * not working after updating webpack.mix.ks

I am working on a laravel project and trying to add some less stylesheets.

However, when I change the webpack.min.js from this:

let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |-------------------------------------------------------------------------    -
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

to:

let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |-------------------------------------------------------------------------    -
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');
mix.less('resources/assets/less/main.less', 'public/css');

My npm stops working. When I try to execute npm run dev after these changes I get the following errors:

> @ dev /Applications/MAMP/htdocs/***.dev
> npm run development


> @ development /Applications/MAMP/htdocs/***.dev
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

Additional dependencies must be installed. This will only take a moment.
/bin/sh: yarn: command not found
child_process.js:515
    throw err;
    ^

Error: Command failed: yarn add less-loader less --save
/bin/sh: yarn: command not found

    at checkExecSyncError (child_process.js:472:13)
    at execSync (child_process.js:512:13)
    at installDependencies (/Applications/MAMP/htdocs/***.dev/node_modules/laravel-mix/src/Verify.js:127:5)
    at Function.dependency (/Applications/MAMP/htdocs/***.dev/node_modules/laravel-mix/src/Verify.js:103:13)
    at Api.less (/Applications/MAMP/htdocs/***.dev/node_modules/laravel-mix/src/Api.js:113:16)
    at Object.<anonymous> (/Applications/MAMP/htdocs/***.dev/webpack.mix.js:16:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)

npm ERR! Darwin 16.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "development"
npm ERR! node v6.11.2
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs 
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls 
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Applications/MAMP/htdocs/***.dev/npm-debug.log

npm ERR! Darwin 16.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "dev"
npm ERR! node v6.11.2
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ dev script 'npm run development'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run development
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs 
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls 
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Applications/MAMP/htdocs/***.dev/npm-debug.log

I don't know what the problem is and already tried reïnstalling npm and laravel mix. Also cleared npm cache..



via Chebli Mohamed

How to create with Laravel query in controller

who can help me? I was selected from sql. This is my sql. How to create with Laravel query in controller.

SELECT sp.name_en, sp.email, sp.phone, post.name AS position_name FROM staff_profiles sp INNER JOIN staff_positions p INNER JOIN positions post WHERE sp.id=p.staff_id and p.position_id=post.id



via Chebli Mohamed

Laravel 5.4 - group by, count and join

I have two tables (models have the same name as the tables):

StatusNames: id|name

and

CurrentUserStatus: id|user_id|status_id

At the moment CurrentUserStatus is empty, and StatusNames have several records inserted (Active, Inactive, On Pause, Terminated...).

I need to get all data from CurrentUserStatus and show how much are there within each status (given the current tables, next to each status name there should be zero (0)).

Is this possible to do with one query?



via Chebli Mohamed

Laravel create custom method to get form data

How do I make custom method to get form data? I want this method same with Laravel update method with parameters request and id. I try this but get error.

In controller

public function updatePassword(Request $request, int $id) {
   dd($request->all());
}

In route

Route::post('staffs/{id}/upassword', 'Admin\StaffController@updatePassword')->name('admin.staffs.upassword');

In blade file

<form method="post" accept-charset="utf-8" action="">
    <div class="row">
        <div class="col-md-3">
            <div class="form-group">
                <label class="control-label" for="password">New Password</label>
                <input class="form-control" name="password" type="password">
            </div>
       </div>
   </div>
   <div class="row">
       <div class="col-md-3">
           <div class="form-group">
               <label class="control-label" for="password_confirmation">Confirm New Password</label>
               <input class="form-control" name="password_confirmation" type="password">
           </div>
       </div>
  </div>

  <input class="btn btn-primary" type="submit">
</form>

I am using Laravel 5.4.



via Chebli Mohamed

values returned by the server invalid json

I'm using json_decode to parse a result returned by the server, the code below used to work fine with one unit, but recently there're new "units": ["ug/m3""mg/m3"] and they are not separated by comma.

  $client = new Client(); //GuzzleHttp\Client
  $result = $client->get($url);
  $body = (string)$result->getBody(); 

   $area = json_decode($body, true);

    foreach($area as $v)
       {
          $arr[$v['key']] = $v['key'];
       }

  }

Invalid argument supplied for foreach()

'body' => '[{ "key": "0001", "desc": "SO2", "units": ["ppb""ug/m3"] },
{ "key": "0003", "desc": "NO2", "units": ["ppb""ug/m3"] },
{ "key": "0004", "desc": "CO", "units": ["ppm""mg/m3""ug/m3"] },
{ "key": "0008", "desc": "O3", "units": ["ppb""ug/m3"] },
{ "key": "PM10", "desc": "PM10", "units": ["ug/m3""mg/m3"] },
{ "key": "PM25", "desc": "PM25", "units": ["ug/m3""mg/m3"] }]', 'area' => null)  



via Chebli Mohamed

Testing with Laravel: DatabaseTransactions or DatabaseMigrations

DatabaseTransactions trait seems to be faster than DatabaseMigrations trait in Laravel tests. It's normal, because for each test DatabaseMigrations runs all migration process (+rollback) again, and DatabaseTransactions just cancels the last transaction. It seems sensible to choose DatabaseTransactions trait then.

Still, DatabaseMigrations does exist. So, is there any benefits in using it (instead of using DatabaseTransactions)?



via Chebli Mohamed

Laravel Orderby not working inside Eloquent whereHas relationship?

Please have look on below code.

 $serviceNew = CompletedService::selectRaw('gallons_collected as total,account_id,id,service_provider_id,service_id,service_date')
            ->where("service_id", '1')->where('service_provider_id', $service_privider_id)->whereMonth('service_date', $month)->whereYear('service_date', $year)
            ->with('account')
            ->whereHas('account', function($qs) {
                $qs->orderBy('restaurant_name', 'DESC');
            })
            ->get();

I have multiple records in "CompletedService" and there is one parent id account_id which in account table. and i made with on account.

Already ASC and DESC tried.

Try to order by in whereHas but it's not affect on any records. Below is model relationship.

 public function account() {
    return $this->hasOne('App\Account', 'id', 'account_id');
}

i don't need to orderby in model because i used this relation in multiple time and need only order by in this single query.

Output enter image description here

Every help will be appreciated. Thanks in advance.!



via Chebli Mohamed

Install Laravel Socialite without composer?

I was adding social authentication using laravel socialte. and It works prfectly on local machine. but when I add that functionality to live server and putting the package inside composer directory and updating composer.json is not working. I am asking if there is any possible way to install the package to a web server without composer?



via Chebli Mohamed

Laravel,PHP - Error when returning my blade view

I keep getting an error that says that I got an error "Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) " in my master blade view.It says that the error is in "c8b1f4540e0eacfb9a43e3fc107c6a88db708eac.php (line 150)" when I only 148 lines in my code.

My routes:

Route::get('search',array('as'=>'search','uses'=>'AutoCompleteController@search'));
Route::get('autocomplete',array('as'=>'autocomplete','uses'=>'AutoCompleteController@autocomplete')); 

My Controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;
class AutoCompleteController extends MainController {

      public function search()
    {
        return view('master');
    }

     public function autocomplete(Request $request)
     {

if( !empty(request('query'))){

        $data = Product::select("title")
        ->where("title","LIKE","%{$request->input('query')}%") 


->get(); 
         dd('justrandom');
     $dataJson =$data->toJson();
        return view('master', compact('dataJson'));
}else{ 

  return view ('master', ['dataJson' => false]);

}

    }
} 

My master blade:

<head>
    <meta charset="UTF-8">
    <title>@if (!empty($title) )
          
        @else
        MySite
        @endif</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="http://ift.tt/2aHU2x3" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">  
    <link href="" rel="stylesheet" type="text/css"/>
    <link href="" rel="stylesheet"/>    
    <script>var BASE_URL = "/";</script>  


</head>

<header>
    <!-- NAVBAR
================================================== -->
    <body>
        <div class="navbar-wrapper">
            <div class="container-fluid">

                <nav class="navbar navbar-inverse navbar-static-top">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            <a class="navbar-brand" href="">MySite</a>

                        </div>
                        <div id="navbar" class="navbar-collapse collapse" >

                            <ul class="nav navbar-nav">

                                @if( !empty($menu))
                                @foreach($menu as $item)
                                <li><a href=""></a></li>
                                @endforeach
                                @endif

                                <li><a href="">Shop</a></li>
                                <li>
                                    <a href="">
                                        <img width="20" src="">  
                                        <div id="total-cart">
                                            @if(! Cart::isEmpty())
                                            
                                            @endif
                                        </div>

                                    </a>
                                </li>
                            </ul>  

                            <ul class="nav navbar-nav navbar-right">
                                @if(Session::has('user_id'))
                                <li><a href=""></a></li>  
                                @if( Session::has('is_admin'))
                                <li><a href="">CMS DASHBOARD</a></li>  
                                @endif
                                <li><a href="">Logout</a></li>
                                @else
                                <li><a href="">Sign In</a></li>
                                <li><a href="">Sign Up</a></li>  

                                @endif
                            </ul>
                            <div class="row">
                            <div class="container">
                                <form method="GET" action="" class="navbar-form navbar-right">

                        <div class="input-group">
                            <input type="text" name="find" class="typeahead form-control" aria-label="Search here..." placeholder="Search here..." autocomplete="off" value="">
                            <div class="input-group-btn">
                                <button type="submit" class="btn btn-default" style="height: 34px; width: 40px" ><i class="glyphicon glyphicon-search"></i></button>
                            </div>
                        </div>
                    </form>

                        </div>
                    </div>
                </nav>

            </div>
        </div>




</header>  <br><br><br><br>


 @if(!empty($dataJson))
    @foreach(json_decode($dataJson, true) as $value)
          
    @endforeach
$endif

<div class="container" >@yield('carousel')</div> <br><br>

<main>  
    <div class="container">

        @include ('inc.sm')
        @include ('inc.errors')


        @yield('content')  

    </div>

</main>  
<br><br><br>
<footer>  
    <div class="container">  
        <hr>
        <div class="row">
            <div class="col-md-12" >
                <p class="text-center" style="font-size: 18px;" >MySite &copy;  </p>
            </div>
        </div>
    </div>

</footer>    



<script src="http://ift.tt/2n9t8Vj"></script>
<script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="http://ift.tt/2scr4kY"></script>
<script src="" type="text/javascript"></script>  
<script type="text/javascript">
    var path = "";
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
                return process(data);
            });
        }
    });
</script>



via Chebli Mohamed

laravel eloquent nested SELECT statement

I am using LARAVEL with eloquent with MYSql I have three tables POSTS USERS and COMMENTS. My POST and COMMENT are in One-to-many relation thus with the following code I get the list of Comments for particular POST id

   $post =  Post::where('id', $id)->get();
   $comment = Post::find($id)->comment()->paginate(10);       
   return view('posts\single', ['post' => $post, 'comments' => $comment]);

Now I want to get the Details of each user from the USER table. I dont want to use the foreach() and then get details of every single ID. Is there any method by which I can get all the Comments(From COMMENTS table) including user details (From USER table) at a single call.



via Chebli Mohamed

Laravel API isn't getting inputs

I am developing a REST API in laravel and upon requesting it I am posting some data. But in laravel controller nothing appears. This is my controller code:

try {
      $rules = [
         'type' => 'required|integer'
      ];

      $validator = Validator::make($this->inputs, $rules);
      if ($validator->passes()) {
         //code here
      } else {
         return response()->json([
                'status' => $this->BAD_REQUEST,
                    'response' => [
                        'message' => $validator->messages(),
                        'data' => $this->NO_DATA_ARRAY
                    ],
                ], $this->BAD_REQUEST);
      }
} catch (\Exception $ex) {
            return response()->json([
                'status' => $this->BAD_REQUEST,
                'response' => [
                    'message' => $ex->getMessage(),
                    'data' => $this->NO_DATA_ARRAY
                ],
            ], $this->BAD_REQUEST);
}

Now when I do print_r($this->inputs); I get nothing. I am sending the request from postman and sending the data as form-data. I have tried sending it using an online API tester as well. Still the same result. Any help?



via Chebli Mohamed

Custom laravel migration command "[Illuminate\Database\Migrations\MigrationRepositoryInterface] is not instantiable"

I'm trying to create a custom laravel (5.2) migration command that basically works the same as migrate:status except it just lists the pending migrations instead of all the migrations.

To do this i've very simply copied the migrate:status into another class within my app/console directory and adjusted the code to suit my needs. However whenever I try to run it I get an error:

[Illuminate\Contracts\Container\BindingResolutionException] Target [Illuminate\Database\Migrations\MigrationRepositoryInterface] is not instantiable while building [App\Console\Commands\PendingMigrations, Illuminate\Database\Migrations\Migrator].

The contents of the class itself and the fire() method doesn't seem to matter as it doesn't get that far, it fails within the __construct() method.

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Migrations\Migrator;

class PendingMigrations extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'migrate:pending';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Shows a list of pending migrations';

    /**
     * The migrator instance.
     *
     * @var \Illuminate\Database\Migrations\Migrator
     */
    protected $migrator;

    /**
     * Create a new migration rollback command instance.
     *
     * @param  \Illuminate\Database\Migrations\Migrator $migrator
     * @return \Illuminate\Database\Console\Migrations\StatusCommand
     */
    public function __construct(Migrator $migrator)
    {
        parent::__construct();

        $this->migrator = $migrator;
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
    }
}

The reason for it is likely to be something to do with the IoC container and the order with which things are loaded, but I don't know enough about the inner workings of Laravel to figure out any more than that.

It surely must be possible?

I am currently stuck on 5.2, so i'm not sure if this problem exists in more recent versions.

The only thing i've attempted so far is added the migration service provider to the top of the list in config/app.php however it didn't seem to have an affect and it was just a random guess anyway.

providers' => [
    Illuminate\Database\MigrationServiceProvider::class,`
]



via Chebli Mohamed

Laravel - Pass a function parameter to a DB method

I have a function that is taking an id as a param, and updates the db using the DB method. however, when i run the code, the variable is not being passed to the method. to test, i replaced $id with an integer and it worked, so i think the DB method can not access the variable from the parameter

public function disable($id)
{

    // Update the user status to 0 from 1
    DB::table('employees')->where('id', $id)->update(['status' => 0]);
    return redirect('/employee')->with('error', 'User is disabled, all related accounts are now shutdown!...');
}



via Chebli Mohamed

Laravel: how to run seeder with relationships

Why "relationship" in my seeder code isn't working? It inserts to User model without any problem. But doesn't insert anything to UserMeta model. There is not even any error.
I have tested this code in controller. It was functioning fine with "relationship"

    <?php

use Illuminate\Database\Seeder;
use App\User;
use App\UserMeta;

class MyUsersTableSeeder extends Seeder
{
    /**
     * Auto generated seed file.
     *
     * @return void
     */
    public function run()
    {
        if (User::count() == 0) {

            $user = User::create([
                'name'           => 'Admin',
                'email'          => 'admin@admin.com',
                'password'       => bcrypt('password'),
                'remember_token' => str_random(60),
            ]);

            $user_meta = new UserMeta([
                'meta_key' => 'role',
                'meta_value' => 'admin',
            ]);
            $user->UserMeta()->save($user_meta);
        }
    }
}



via Chebli Mohamed

Laravel 5.2 not working in PHP 5.6 with Nginx server

I am currently migrating my website from Apache to nginx, but my .htaccess file is not working. How can I use .htaccess in my nginx server?

My nginx config file:

server {
#listen 8000;
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
#listen [::]:80 default_server;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;

server_name localhost;

location /phpmyadmin {
           root /usr/share/;
           index index.php index.html index.htm;
           location ~ ^/phpmyadmin/(.+\.php)$ {
                   try_files $uri =404;
                   root /usr/share/;
                   fastcgi_pass unix:/var/run/php5-fpm.sock; # or 127.0.0.1:9000
                   fastcgi_index index.php;
                   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                   include /etc/nginx/fastcgi_params;
           }
           location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
                   root /usr/share/;
           }
    }
    location /phpMyAdmin {
           rewrite ^/* /phpmyadmin last;
    }

location / {
        try_files $uri $uri/ /index.php?$query_string;
}

# Remove trailing slash to please routing system.
    if (!-d $request_filename) {
        rewrite     ^/(.+)/$ /$1 permanent;
    }

location ~ \.php$ {
    #try_files $uri =404;
    try_files $uri /index.php =404;
    #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}

location ~ /\.ht {
    deny all;
}
}

What I tried:

sudo chown -R www-data:www-data *

sudo chown -R root:root *

also I tried to change

try_files $uri $uri/ /index.php?$query_string;
try_files $uri $uri/ /index.php$is_args$args;
try_files $uri $uri/ /index.php;

php artisan cache:clear

Mostly questions in google i have read, but nothing helps me.



via Chebli Mohamed

DatabaseMigrations Not Found In Laravel 5.0

I was watching a video of Unit Testing of Laravel 5.4, and the tutor uses

use Illuminate\Foundation\Testing\DatabaseMigrations;

and

use DatabaseMigrations;

inside the testing file

In Laravel 5.0, there are no such files and I cannot use DatabaseMigrations in my testing file.

I get error like

Fatal error: Trait 'Illuminate\Foundation\Testing\DatabaseMigrations' not found

Are there any replacements in Laravel 5.0



via Chebli Mohamed

How to forward form values from one view to another using $request->all(); ? Laravel 5

I pull all the values (topup amount and phone number) from a form on the index page and forward it to the checkout page:

public function topupPost(Request $request) {
        $validator = [
        'topupAmount'=> 'required|integer|between:1,100',
        'phonenumber'=> 'required|http://regex:/^05[602][0-9]{7}$/',
        ];

        $inputs = $request->all();

        Log::info($inputs);

        $validator = Validator::make($inputs, $validator);

        if($validator->fails()){
            return Response::json([
                'error' => true,
                'message' => $validator->messages(),
                'code' => 400
            ], 400);
        }


        // return "Thanks! we'll take you to payment in a Giffy!";
        return view('pages.checkout', compact(inputs));
    }

How can I can I access the values of inputs which are: phonenumber and topupAmount in the checkout page template ?

I tried this:

<td> USD</td>

And it shows this error in the debugger :

(1/1) ErrorException Use of undefined constant inputs - assumed 'inputs' in PagesController.php (line 39) at HandleExceptions->handleError(8, 'Use of undefined constant inputs - assumed \'inputs\'', 'C:\xampp\htdocs\onlinerecharge\app\Http\Controllers\PagesController.php', 39, array('request' => object(Request), 'validator' => object(Validator), 'inputs' => array('_token' => 'CsySUUecI0ekYNPY6oS1B2kleVHqNnrUKBpHbYwa', 'phonenumber' => '0501234567', 'topupAmount' => '1'))) in PagesController.php (line 39)



via Chebli Mohamed

Laravel 5.5: Syntax error or access violation: 1067 Invalid default value for 'created_at'

I install laravel 5.5 and When I run php artisan migrate show me this error

[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQ L: alter table users add unique users_email_unique(email))

And I add bellow code on AppServiceProvider.php

 public function boot()
{
     Schema::defaultStringLength(191); //Solved by increasing StringLength
}

And then show me this error

[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_at' (SQL: create table password_resets (email varchar(191) not null, token varchar(191) not null, created_at timestamp not null) de fault character set utf8mb4 collate utf8mb4_unicode_ci)



via Chebli Mohamed

How to keep the previous form parameter to current form, after validation

I have 2 forms, form A + B

I choose an option from form A and passes great to form B.

After validation of the form B tho I loose selected option from the form A.

In the Controller of the form B I get the option from the form A like this

$option = $request->option;

and I pass it to the view like this:

return view('formB', ['option' => $option]);

Depending the option I show dynamic different title and different form.

So i have 2 questions:

  1. How can i keep the option after validation and
  2. Is this the right way to do the 2-step forms?

I hope that I was clear enough :)

Thanks in advance



via Chebli Mohamed

Laravel Unit Test api controller : compare two models result

i'm trying to use for the first time unit tests for my future projects. But i'm blocked with storing a model.

This is the api controller i want to test :

public function store(QuestionFormRequest $request)
{
    $questionRequest = $request->question();

    $question = new Question($questionRequest);
    $question->save();

    $question->answers()->createMany($questionRequest['answers']);

    return response()->json($question->load('answers'), 201);
}

This is my test :

public function it_can_store_a_question()
{
        $surveyFactory = factory(Survey::class)->create();
        $themeFactory = factory(Theme::class)->create();
        $pillarFactory = factory(Pillar::class)->create();

        $questionToStore = [
            'survey_id' => $surveyFactory->id,
            'theme_id' => $themeFactory->id,
            'pillar_id' => $pillarFactory->id,
            'name' => 'question',
            'type' => 'simple',
            'answers' => [
                [
                    'label' => 'reponse1',
                    'points' => '3',
                ],
                [
                    'label' => 'reponse2',
                    'points' => '5',
                ]
            ]
        ];

        $response = $this->post('/api/1.0/question', $questionToStore);
        $response->assertStatus(201);

        $expectedQuestion = Question::with('answers')->get()->first();
        $this->assertEquals(json_encode($expectedQuestion), $response->getContent());
} 

this is the result :

Failed asserting that two strings are equal.
Expected :'{"id":1,"survey_id":1,"theme_id":1,"pillar_id":1,"name":"question","type":"simple","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null,"answers":[{"id":1,"question_id":1,"label":"reponse1","points":3,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null},{"id":2,"question_id":1,"label":"reponse2","points":5,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null}]}'
Actual   :'{"survey_id":1,"theme_id":1,"pillar_id":1,"name":"question","type":"simple","updated_at":"2017-08-29 08:54:45","created_at":"2017-08-29 08:54:45","id":1,"answers":[{"id":1,"question_id":1,"label":"reponse1","points":3,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null},{"id":2,"question_id":1,"label":"reponse2","points":5,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null}]}'

In fact, the result is right. But not in the same order. What do I do wrong in my test ?

Thanks.



via Chebli Mohamed

Bcrypt Password when uploading file excel into database in Laravel 5.4

Hello i have a problem with importing excel to the database, i need to bcrypt my password. For now i already can successfully import my excel to database, but my password still in plain text. Here is my code :

 public function importExcel()
  {
    if(Input::hasFile('import_file')){
      $path = Input::file('import_file')->getRealPath();
      $data = Excel::load($path, function($reader) {
      })->get();
      if(!empty($data) && $data->count()){
        foreach ($data as $key => $value) {
          $insert[] =
          [
            'name'=>$value->name,
            'password'=>$value->password,
            'email'=>$value->email,
            'id_branch'=>$value->id_branch,
            'birth_date'=>$value->birth_date,
            'birth_location'=>$value->birth_location,
            'sex'=>$value->sex,
            'job'=>$value->job,
            'address'=>$value->address,
            'telephone'=>$value->telephone,
            'handphone'=>$value->handphone,
            'office_address'=>$value->office_address
          ];
        }
        if(!empty($insert)){
          $value['password'] = bcrypt($value['password']);
          DB::table('member')->insert($insert);
          return redirect('admin/'.$this->path . '/')->with('success','Success Add New Record');
        }
      }
    }
    return back();
  }



via Chebli Mohamed

lundi 28 août 2017

Laravel how to pass the name of the user when I sent the forgot password function

I want to make my mail more detailed when the user has sent a forgot password reset link to his/her email. This is the sample of the picture when receaving a reset password link.

enter image description here

I want to add some details here that the Hello should be Hello! (user name here)

Here is the code that I added in my SendsPasswordResetEmails.php

public function sendResetLinkEmail(Request $request)
    {
        $this->validateEmail($request);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        $applicant_name = Applicant::where('email', $request->email)->get()->value('name');

        return $response == Password::RESET_LINK_SENT
                    ? $this->sendResetLinkResponse($response)
                    : $this->sendResetLinkFailedResponse($request, $response);
    }

and it should pass the data to my email.blade.php in my vendor/notifications/email.blade.php

@component('mail::message')

@if (! empty($greeting))
# 
@else
@if ($level == 'error')
# Whoops!
@else
# Hello! $applicat_name // Name of the applicant to be passed in after sending reset password request
@endif
@endif


@foreach ($introLines as $line)


@endforeach


@isset($actionText)
<?php
    switch ($level) {
        case 'success':
            $color = 'green';
            break;
        case 'error':
            $color = 'red';
            break;
        default:
            $color = 'blue';
    }
?>
@component('mail::button', ['url' => $actionUrl, 'color' => $color])

@endcomponent
@endisset


@foreach ($outroLines as $line)


@endforeach


@if (! empty($salutation))

@else
Regards,<br>CCTV Team
@endif


@isset($actionText)
@component('mail::subcopy')
If you’re having trouble clicking the "" button, copy and paste the URL below
into your web browser: []()
@endcomponent
@endisset
@endcomponent

I think I messed up with here. Would really appreciate if someone could help. Thanks in advance.



via Chebli Mohamed

Laravel to get db values from session id

I am trying to create a session and retrieve it and get db values using the session id

(i.e) While on click edit i like to store the data-id in session and from session id i like to retrieve the db values using Eloquent

so far i stored and retrieve the session the only problem i don't know to get db from that session id here is my following code

My ajax call :

    $(document).ready(function(){
        $('.editaction').click(function(){
            var editaction=($(this).attr("data-id"));
            console.log(editaction);
                $.ajaxSetup({
                    headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                });
         $.ajax({
            type:"POST",
              url:"/design_session",
              data:"design_id="+editaction,
              success:function(results){
                window.location.href="/design_edit";
              }
            }); 
        });
    })  

Db controller page :

public function show()
{
    $design_id = $request->session()->get('design_id');
    return view('pages.design_edit')->with('design',$design_id);
}  

so far i am getting redirect to another page successfully but i don't how to invoke or pass the ajax through the function to get db values



via Chebli Mohamed

Laravel - SQLSTATE[42000]: Syntax error or access violation: 1064 on migration

I never had this error until now it happens when I run php artisan migrate
I'm using MySQL 5.6.34
I tried everything I could think of ): and still have no luck I have a similar table to this and worked fine but for some reason, this once does not work

[PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
  to use near 'unsigned not null, `address_1` varchar(191) unsigned not null, `address_2` varch' at line 1

Here is my migration file

public function up()
    {
        Schema::create('rmaRequests', function (Blueprint $table) {
           $table->increments('id');
           $table->integer('user_id')->unsigned();
           $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
           $table->string('reference_number')->unique();
           $table->string('first_name');
           $table->string('last_name');
           $table->string('email');
           $table->string('phone');
           $table->string('fax');
           $table->string('company');
           $table->integer('marketplaceId')->unsigned();
           $table->string('order_number')->unsigned();
           $table->string('address_1');
           $table->string('address_2');
           $table->string('city');
           $table->string('state');
           $table->string('zip');
           $table->integer('returnTypeId')->unsigned();
           $table->string('sku');
           $table->string('qty');
           $table->string('productName');
           $table->text('comments');
           $table->integer('status_id')->unsigned();
           $table->string('replacement_tracking');
           $table->string('return_tracking');
           $table->string('rma_number');
           $table->string('refund_number');
           $table->timestamps();
        });
    }



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



via Chebli Mohamed

How do i add stripe billing for multiple login user guards in laravel

am currently working on an application where i set guards for both vendors and suppliers which is currently working fine but now i want to add subscription for both login users and am confused bout how. Please if anyone can help me out here i'd be very grateful.



via Chebli Mohamed

Laravel 5.4 not working on PHP 7.0 due to Doctrine package

I'm trying to deploy a Laravel application on an AWS PHP 7.0 instance (Elastic Beanstalk, but that doesn't really matter).

I get the following error

+ composer.phar install --no-ansi --no-interaction
Do not run Composer as root/super user! See http://ift.tt/1UioBPp for details
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for doctrine/instantiator 1.1.0 -> satisfiable by doctrine/instantiator[1.1.0].
    - doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.16) does not satisfy that requirement.
  Problem 2
    - doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.16) does not satisfy that requirement.
    - phpunit/phpunit-mock-objects 3.4.4 requires doctrine/instantiator ^1.0.2 -> satisfiable by doctrine/instantiator[1.1.0].
    - Installation request for phpunit/phpunit-mock-objects 3.4.4 -> satisfiable by phpunit/phpunit-mock-objects[3.4.4].
 (Executor::NonZeroExitStatus)

Any ideas how can I suppress this or get around it on PHP 7.0?

My composer.json

{
    "name": "myapp",
    "description": "My App.",
    "keywords": ["framework", "laravel", "lumen"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/lumen-framework": "5.4.*",
        "vlucas/phpdotenv": "~2.2",
        "romanpitak/nginx-config-processor": "^0.2.1",
        "symfony/stopwatch": "^3.2",
        "comodojo/zip": "^2.1",
        "riimu/kit-pathjoin": "1.*",
        "aws/aws-sdk-php": "^3.25",
        "spatie/url": "dev-master"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "phpunit/phpunit": "~5.0",
        "mockery/mockery": "~0.9"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/",
            "database/"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ]
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

P.s. I am not using any unit testing. I tried to get rid of the "require-dev" packages and still the same error.



via Chebli Mohamed