lundi 29 février 2016

artisan queue is creating hundreds of jobs

I have a command which process some data and then creates a job to be process in the jobs table of laravel, when I run php artisan queue:listen --queue=job-name its starts creating a lot of thread.I use supervisor to manage my jobs and the config of supervisor is as follows :

[program:exportlistener]
command=php /var/www/prodadm/sipi-www/current/artisan queue:listen --queue exportdata --tries 3 --timeout 3600
user=prodadm
autostart=true
autorestart=true

[program:htmllistener]    
command=php /var/www/prodadm/sipi-www/current/artisan queue:listen --queue=htmldownload --tries 1 --memory=256 --timeout 240
user=prodadm
autostart=true
autorestart=true

The following is the result of ps aux | grep php5 these processes keep increasing as the time passes which is eating all my RAM

Please see

root 4761 0.0 0.4 277448 16980 ? Ss Feb26 0:26 php-fpm: master process (/etc/php5/fpm/php-fpm.conf)

prodadm 8948 0.0 0.0 4440 656 ? S 12:39 0:00 sh -c "/usr/bin/php5" artisan queue:work --queue="htmldownload" --delay=0 --memory=256 --sleep=3 --tries=1 --env=production

prodadm 8950 0.3 0.9 270568 36540 ? S 12:39 0:00 /usr/bin/php5 artisan queue:work --queue=htmldownload --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8953 0.0 0.0 4440 656 ? S 12:39 0:00 sh -c "/usr/bin/php5" artisan queue:work --queue="htmldownload" --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8954 0.3 0.9 270568 36540 ? S 12:39 0:00 /usr/bin/php5 artisan queue:work --queue=htmldownload --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8955 0.0 0.0 4440 656 ? S 12:39 0:00 sh -c "/usr/bin/php5" artisan queue:work --queue="htmldownload" --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8956 0.2 0.9 270568 36548 ? S 12:39 0:00 /usr/bin/php5 artisan queue:work --queue=htmldownload --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8957 0.0 0.0 4440 656 ? S 12:39 0:00 sh -c "/usr/bin/php5" artisan queue:work --queue="htmldownload" --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 8958 0.3 0.9 270568 36544 ? S 12:39 0:00 /usr/bin/php5 artisan queue:work --queue=htmldownload --delay=0 --memory=256 --sleep=3 --tries=1 --env=production prodadm 9050 0.0 0.0 4440 656 ? S 12:41 0:00 sh -c "/usr/bin/php5" artisan queue:work --queue="exportdata" --delay=0 --memory=128 --sleep=3 --tries=3 --env=production prodadm 9051 8.0 0.8 189360 31108 ? S 12:41 0:00 /usr/bin/php5 artisan queue:work --queue=exportdata --delay=0 --memory=128 --sleep=3 --tries=3 --env=production root 9053 0.0 0.0 10464 932 pts/2 S+ 12:41 0:00 grep --color=auto php5



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oV1hJG
via IFTTT

Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()

I am working in a laravel 5 application and I am trying to debug the database queries that are running in the background.

So I tried the way that many people in the community try:

http://ift.tt/1LRNTL9

But to my surprise I am getting back a weird exception thrown by laravel saying:

Missing argument 2 for App\Providers\AppServiceProvider::App\Providers{closure}()

[2016-03-01 07:12:18] local.ERROR: exception 'ErrorException' with message 'Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()' in /home/vagrant/Code/tenant-application/app/Providers/AppServiceProvider.php:19
Stack trace:
#0 /home/vagrant/Code/tenant-application/app/Providers/AppServiceProvider.php(19): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'Missing argumen...', '/home/vagrant/C...', 19, Array)
#1 [internal function]: App\Providers\AppServiceProvider->App\Providers\{closure}(Object(Illuminate\Database\Events\QueryExecuted))
#2 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(221): call_user_func_array(Object(Closure), Array)
#3 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Connection.php(750): Illuminate\Events\Dispatcher->fire(Object(Illuminate\Database\Events\QueryExecuted))
#4 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Connection.php(641): Illuminate\Database\Connection->logQuery('select * from `...', Array, 1.26)
#5 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Connection.php(342): Illuminate\Database\Connection->run('select * from `...', Array, Object(Closure))
#6 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(1461): Illuminate\Database\Connection->select('select * from `...', Array, true)
#7 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(1447): Illuminate\Database\Query\Builder->runSelect()
#8 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(569): Illuminate\Database\Query\Builder->get(Array)
#9 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(303): Illuminate\Database\Eloquent\Builder->getModels(Array)
#10 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(273): Illuminate\Database\Eloquent\Builder->get(Array)
#11 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php(100): Illuminate\Database\Eloquent\Builder->first()
#12 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php(353): Illuminate\Auth\EloquentUserProvider->retrieveByCredentials(Array)
#13 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php(256): Illuminate\Auth\SessionGuard->attempt(Array, false, false)
#14 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php(239): Illuminate\Auth\SessionGuard->validate(Array)
#15 [internal function]: Illuminate\Auth\SessionGuard->once(Array)
#16 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php(282): call_user_func_array(Array, Array)
#17 /home/vagrant/Code/tenant-application/vendor/tymon/jwt-auth/src/Providers/Auth/IlluminateAuthAdapter.php(39): Illuminate\Auth\AuthManager->__call('once', Array)
#18 /home/vagrant/Code/tenant-application/vendor/tymon/jwt-auth/src/Providers/Auth/IlluminateAuthAdapter.php(39): Illuminate\Auth\AuthManager->once(Array)
#19 /home/vagrant/Code/tenant-application/vendor/tymon/jwt-auth/src/JWTAuth.php(108): Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter->byCredentials(Array)
#20 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(221): Tymon\JWTAuth\JWTAuth->attempt(Array, Array)
#21 /home/vagrant/Code/tenant-application/vendor/archiveonline/tenant-package/src/Controllers/Auth/AuthController.php(43): Illuminate\Support\Facades\Facade::__callStatic('attempt', Array)
#22 /home/vagrant/Code/tenant-application/vendor/archiveonline/tenant-package/src/Controllers/Auth/AuthController.php(43): Tymon\JWTAuth\Facades\JWTAuth::attempt(Array, Array)
#23 [internal function]: Uppdragshuset\AO\Tenant\Controllers\Auth\AuthController->authenticate()
#24 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(78): call_user_func_array(Array, Array)
#25 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(146): Illuminate\Routing\Controller->callAction('authenticate', Array)
#26 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(94): Illuminate\Routing\ControllerDispatcher->call(Object(Uppdragshuset\AO\Tenant\Controllers\Auth\AuthController), Object(Illuminate\Routing\Route), 'authenticate')
#27 [internal function]: Illuminate\Routing\ControllerDispatcher->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#28 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#29 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#30 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#31 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(96): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#32 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(54): Illuminate\Routing\ControllerDispatcher->callWithinStack(Object(Uppdragshuset\AO\Tenant\Controllers\Auth\AuthController), Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request), 'authenticate')
#33 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Route.php(174): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request), 'Uppdragshuset\\A...', 'authenticate')
#34 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Route.php(140): Illuminate\Routing\Route->runController(Object(Illuminate\Http\Request))
#35 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Router.php(724): Illuminate\Routing\Route->run(Object(Illuminate\Http\Request))
#36 [internal function]: Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#37 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#38 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#39 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#40 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Router.php(726): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#41 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Router.php(699): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#42 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#43 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#44 [internal function]: Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#45 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#46 /home/vagrant/Code/tenant-application/vendor/archiveonline/tenant-package/src/Middleware/Cors.php(25): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#47 [internal function]: Uppdragshuset\AO\Tenant\Middleware\Cors->handle(Object(Illuminate\Http\Request), Object(Closure))
#48 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#49 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#50 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#51 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#52 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#53 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#54 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#55 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#56 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#57 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#58 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#59 /home/vagrant/Code/tenant-application/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#60 /home/vagrant/Code/tenant-application/public/index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#61 {main}  

That is the trace but I cannot figure out what I am doing wrong here.

AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use DB;
use Log;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($sql, $bindings, $time) {
            Log::info($time . "\r\n" . $sql);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TNrNQl
via IFTTT

Laravel 5 - Not seeding table that has 2000 rows

I entered php artisan db:seed but it skip seeding CountriesRetailerSeeder.

It seeds when I do it manually.

php artisan db:seed --class=CountriesRetailerSeeder

How will I be able to run it in php artisan db:seed along with the other seeders ?

here's the code in my CountriesRetailerSeeder

public function run()
{
     DB::table('country_retailer')->truncate();
     $file = base_path().'/database/seeds/country_retailer_csv.csv';
     $reader = Reader::createFromPath($file);

     $data = array();
     $count_elements = 0;
     foreach($reader as $index => $row)
     {
         $data[$count_elements] = array('country'=>$row[0],'original_header'=>$row[1],'count'=>$row[2],
         'channel'=>$row[3],'retailer'=>$row[4],
         'website'=>$row[6],'contacts'=>$row[7],'notes'=>$row[8]);

         $count_elements++;
     }
     $cr = new CountryRetailer;
     $cr::insert($data);
}

Take not that all of those 2000 rows of data is from a csv file.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VO4gxR
via IFTTT

Laravel 5.1 cron not workin in OVH

I'm trying to run a cron in my OVH but it is not accepting the command :

php artisan schedule:run 1>> /dev/null 2>&1

it say :

The characters for the records are letters , numbers, and characters -_./ Moreover , it is forbidden to access parent folders

Help me out with this. Thanks in advanced



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/21yz5xq
via IFTTT

Redirect URL callback for facebook is not taking Base Url laravel 5

Hello everyone I'm trying to integrate facebook login using laravel5, In my code i have mentioned my redirect URL so it should go on below mentioned URL but when i'm trying to login with facebook my url is coming like this it's not taking my folder name see the difference in both URLs

 http://localhost:8000/facebook/callback?code=xxxxx

 Correct Url 
 http://localhost:8000/facebook/public/facebook/callback/

'facebook' => [
'client_id' => 'xxxxxxxxxxxxxxx',
'client_secret' => 'xxxxxxxxxxxxxxxxxxx',
'redirect' => 'http://localhost:8000/facebook/public/facebook/callback/',
 ],

This is my routes

Route::get('facebook/callback', 'Auth\AuthController@handleProviderCallback'); 

My controller

  public function handleProviderCallback()
{
    try {
        $user = Socialite::driver('facebook')->user();
    } catch (Exception $e) {
        return redirect('facebook');
    }

    $authUser = $this->findOrCreateUser($user);

    Auth::login($authUser, true);

    return redirect()->route('home');
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1OKF7hP
via IFTTT

Searching in Laravel relationship for second table

I have two table having polymorphic relationships.

Table1 is history id|amount|type|created_at|updated_at

Table2 is accounts id|amount|account_number|accountable_id|accountable_type|created_at|updated_at

history have the summary of accounts table. accounts table is having polymorphic fields (accountable)

Now i am executing a query in history table results includes the accounts table also. The question is i want to search some data in accounts table too say payer name is in account table. So when i hit query on hitory table i will pass payer name with that so it can fetch only that accounts having the specific payer name.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1neIesi
via IFTTT

How to compare two encrypted(bcrypt) password in laravel

How to compare two bcrypt password

$pass1 = '$2y$10$ooPG9s1lcwUGYv1nqeyNcO0ccYJf8hlhm5dJXy7xoamvgiczXHB7S';

And

$pass2 = '$2y$10$QRgaiS6bpATKKQeT22zGKuHq.edDfXQc2.4B3v.zaN.GtGwoyQuMy';

Both $pass1 & $pass2 are bcrypt for 'test'.

How I can check for equality. without using text 'test' like this

$hash1 = Hash::make('test');
$hash2 = Hash::make('test');

var_dump(Hash::check('test', $hash1) && Hash::check('test', $hash2));



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TNQPjz
via IFTTT

Laravel 5.2 could not open laravel.log

I know there are a lot of questions on this topic but my issues is really weird that's why I decided to post. I have this error in /var/logs/apache/error.log

  [Tue Mar 01 07:26:51.435312 2016] [:error] [pid 8837] [client 127.0.0.1:37843] PHP Fatal error:  Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/var/www/personale/librarie-cor/storage/logs/laravel.log" could not be opened: 
failed to open stream: Permission denied' in /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:87\nStack trace:
\n#0 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\\Handler\\StreamHandler->write(Array)
\n#1 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Logger.php(289): Monolog\\Handler\\AbstractProcessingHandler->handle(Array)
\n#2 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Logger.php(565): Monolog\\Logger->addRecord(400, Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array)
\n#3 /var/www/personale/librarie-cor/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\\Logger->error(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array)
\n#4 /var/www/personale/librarie-cor in /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 87

The thing is I already did chmod -R 777 storage/, here is a screenshot:

chmoded

How can I get rid of the error?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1T5ou8h
via IFTTT

Populate form and update with Laravel Collective

I didn't understand the documentations and examples I've found around about populating a form with Form::model() and updating the data.

First, the form is not being populated with it.

{!! Form::model($post, ['route' => ['/admin/post/edit', $post->id]]) !!}
...
{!! Form::close() !!}

The Controller:

public function edit($id)
{
    return \View::make('admin/post/edit')->with([
        'post' => \DB::table('posts')->find($id)
    ]);
}

The route:

Route::get('/admin/post/edit/{id}', [
    'as' => '/admin/post/edit',
    'uses' => 'Admin\PostController@edit'
]);

According to what I've seen, the form was supposed to be filled with the selected data automagically, but that's not the case with me. I tested the $post variable with {{ var_dump($post) }} and it printed the information from the database, which means it's returned, but why isn't the form filled?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QI0rGf
via IFTTT

How to use custom pagination in laravel 5.2 using LengthAwarePaginator

How to use custom pagination in laravel 5.2 using Illuminate\Pagination\LengthAwarePaginator , i think this gives more flexibility than other class according to thier doc. But couldn't figure it out how to do that . So i need help on this . Kindly guide me .



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QHXXYc
via IFTTT

laravel 5 html to pdf view issue

I am trying to put html and save it as pdf. however, it seems the content inside pdf not rendered well. I am using plugin from maatwebsite. Here is the code I've tried

Controller

Excel::create('test',function($file){
        $file->sheet('Sheet1', function ($sheet){

            $sheet->loadView('excel');
            $sheet->setAutoSize(true);
        });

    })->store('pdf',storage_path('uploaded-excel'));

View

<body>
    <p>test</p>
    <img src="images/hierarchy.png"/>
</body>

Result

enter image description here

But when I remove img tag, the size itself looks normal

enter image description here

What am I missing?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LslW1q
via IFTTT

Laravel Event not firing inside a listener

I have an event say EventA. with a handler HandlerA. Inside HandlerA, if a specific case is met, i'm trying to fire EventB. Unfortunately EventB is never getting fired.

I tried to fire EventB inside a controller and it worked just fine.

Is this a bug / is this supposed be like this / am i doing something wrong?

I'm using Laravel 5.1.

Thank you



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VNUonK
via IFTTT

Refactor Laravel Controller to send response from another method

I have two methods in same controller. In first half of both these methods I am creating user,and sending error response if there is some validation issue. I am able to refactor that repeating code into createUserFromRequest.

 public function createUserFromRequest(Request $request)
    {
        $user = $this->getUserFromRequest($request);
        $userRepo = new UserRepository($user);
        if($userRepo->userExists())
        {
            return response()->json(['toast'=>$this->responseOnFailure()]);
        }
        if(!$userRepo->saveUser())
        {
            return response()->json(['toast'=>$this->responseOnFailure()]);
        }
        return $user;
    }
protected function getUserFromRequest(Request $request)
{
    $user = new User;
    $user->email = $request->email;
    $user->first_name = $request->first_name;
    $user->last_name = $request->last_name;
    $user->password = \Hash::make($request->password);
    return $user;
}

I am not able to use it, since in case of error it is returning response()->json(). So what is the way I can send response from other method in case of error and process normally in case there isn't any.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1L0CdLj
via IFTTT

Laravel - Provider data being requested on all routes

I am currently using a Laravel Provider to pass data to a view each time it is called. The App.blade.php includes the blade file if the user is authenticated.

My problem is that at the moment, no matter what view the user is on, it still calls the ViewServiceProvider.php, which doesn't seem very efficient.

I have tried to use @if(view()->exists('home')), but that doesn't seem to have any effect what so ever, and thus, the queries are still called from the ViewServiceProvider.php.

App.blade.php:

@if(!Auth::guest())

  @if(view()->exists('home'))

    @include('layouts.check')

  @endif

@endif

ViewServiceProvider.php:

public function boot()
    {
      view()->composer('layouts.check', function ($view) {

        $sites = Site::where('trust_id', Auth::id())->get();

        $view->with(['sites' => $sites]);
      });
    }

Any help would be hugely appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Qhtx1W
via IFTTT

Laravel select from specific row

I need to select data after specific row with where condition. If i use

Select->where(condition)->skip(x)->take(y)

it will filter where condition first and then skip X row in filtered array and take Y. I need to skip X row first and then use where condition



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LrjPek
via IFTTT

Using Laravel 5 Sessions Externally

I've figured out how to boot Laravel in an external script, but I can't seem to get Session::put() to stick.

$path = "/path/to/laravel/bootstrap/";

require $path . 'autoload.php';
$app = require_once $path . 'app.php';

$app->make('Illuminate\Contracts\Http\Kernel')
  ->handle(Illuminate\Http\Request::capture());

print_r(Session::all());
Session::put('test', 1);

Even after I refresh, this is the output:

Array ( 
    [_token] => emt8sZz7U6prnGUnHV889XPKwuhRCuMpVsAOfWW0 
    [flash] => Array ( 
        [old] => Array ( ) 
        [new] => Array ( ) 
    ) 
    [_previous] => Array ( 
        [url] => http://myurl.local  
    )
)

With no trace of my test variable. For some reason it doesn't make it into the Session. Any ideas?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1XW6EE2
via IFTTT

Creating Follower & Following relationships in Laravel 5

Im trying to create a function in laravel that will return all the user's followers through Laravel's dynamic property. It should look something like this:$user->followers.

I also have the following table structures:

--users--
id pk

--follows--
follower pk,fk
following pk,fk

I was trying to use the hasManyThrough function in the model but I haven seen an example in the documentation that lets me specify a custom primary key aside from an incremental id.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oTlr6T
via IFTTT

Relationships of models (Laravel 5.2)

My tables (Mysql DB):

// Stores Table

CREATE TABLE IF NOT EXISTS `app_beta`.`stores` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
 PRIMARY KEY (`id`))

// Items Table

 CREATE TABLE IF NOT EXISTS `app_beta`.`items` (
 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
 `user_id` INT UNSIGNED NOT NULL,
 `title` TEXT NOT NULL,
 `content` LONGTEXT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_items_user_id`
  FOREIGN KEY (`user_id`)
  REFERENCES `app_beta`.`users` (`id`))

// Products Table

CREATE TABLE IF NOT EXISTS `app_beta`.`products` (
`id` INT UNSIGNED NOT NULL,
`reviews` DECIMAL(7,1) NOT NULL,
 PRIMARY KEY (`id`),
 CONSTRAINT `fk_products_id`
 FOREIGN KEY (`id`)
REFERENCES `app_beta`.`items` (`id`))

// Product_Store Table

CREATE TABLE IF NOT EXISTS `app_beta`.`products_stores` (
`product_id` INT UNSIGNED NOT NULL,
`store_id` INT UNSIGNED NOT NULL,
`price` DECIMAL(7,2) NOT NULL,
`url` VARCHAR(255) NOT NULL,
 CONSTRAINT `fk_products_store_product_id`
 FOREIGN KEY (`product_id`)
 REFERENCES `app_beta`.`products` (`id`),
 CONSTRAINT `fk_products_stores_store_id`
 FOREIGN KEY (`store_id`)
 REFERENCES `app_beta`.`stores` (`id`))

// Offers Table

CREATE TABLE IF NOT EXISTS `app_beta`.`offers` (
`id` INT UNSIGNED NOT NULL,
`store_id` INT UNSIGNED NOT NULL,
`price` DECIMAL(7,2) NULL,
`url` VARCHAR(255) NOT NULL,
`start_date` DATE NOT NULL,
`end_date` DATE NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_offers_store_id`
FOREIGN KEY (`store_id`)
REFERENCES `app_beta`.`stores` (`id`),
CONSTRAINT `fk_offers_id`
FOREIGN KEY (`id`)
REFERENCES `app_beta`.`items` (`id`))

"Offers" and "Products" tables inherit from "items" table, simply beacause products can have many stores, by against "offers" can only have one store (please take a look of foreign keys to understand the relationships).

I have the 4 models on Laravel 5.2 (Store,Item,Product and Offer) and I want to make relationships between them. Please can anyone help me to do that!

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VNfYZF
via IFTTT

How to convert UNIX timestamp into date without the time

I have a table full of UNIX timestamps and I want to strip the time and check againt the CURRENT_DATE and grab the total count.

$shippedCount = Model::whereRaw('DATE(UNIX TABLE) = CURRENT_DATE')->count();

What is the best way to go about this.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LQh0yg
via IFTTT

Laravel 5 shared host subdomain htaccess

Firstly because im on a shared host I cannot place contents of my public folder directly into root. I have to place the entire project into the public_html directory and use a .htaccess to point to the public folder like below (which works fine for a single Laravel project):

RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

I now created a subdomain with the host and it created a directory inside my public_html directory called store.domain.com. This will be for an entirely different Laravel project. If I place the regular folder structure with the .htaccess file into this subdomain folder I get a 503 error when accessing the subdomain. I spoke to the host and when they suggested removing the root .htaccess file the subdomain started working but the main domain fell over.

Ive been struggling for days now reading up various solutions to other peoples similar issues on WordPress but cannot get anything to work correctly. The solution below sort-of works but it keeps adding on the public folder to my URL for the subdomain (root domain project is working fine):

RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^store.mc.com
RewriteRule ^(.*)$ /public/$1 [L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^store.mc.com$
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ /public/$1 [L]

Anyone had this issue or know how to solve it? Very frustrating...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1pkXfdx
via IFTTT

How to define a class and in which folder to define a custome validation rule in laravel 5.2

How to define a class and in which folder to define a custome validation rule in laravel 5.2. In their doc for validation they have given the following code .

Validator::extend('foo', 'FooValidator@validate');

But they haven't mentioned what is this FooValidator and if it is a class name or file name , then where where to place this file. I need help on this .



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Lq9M9k
via IFTTT

how to use foreach loop for two different tables in same page in laravel5

how to use for each loop to retrieve the data from database in laravel5,there is two tables in same page property_details and agent_details then we join two table and show the agent_details as per the same state of property_details.

controller for property_details; public function property_details($state) {

        $view=DB::table('property_details')->where('state',$state)->get();
        return view::make('pages/property_details', array('row'=>$view));

    }

Route::get('property_details/{id}', array('as' => 'property_details', 'uses' => 'PageController@property_details'));



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1nbrHVX
via IFTTT

How to always append attributes to Laravel Eloquent model?

I was wondering how to always append some data to Eloquent model without the need of asking for it for example when getting Posts form database I want to append the user info for each user as:

{
    id: 1
    title: "My Post Title"
    body: "Some text"
    created_at: "2-28-2016"
    user:{
            id: 1,
            name: "john smith",
            email: "example@mail.com"
         }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Lq9JdI
via IFTTT

Laravel 5 - deleting child model data

I have a Model called Campaign which takes the following structure

+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+
| id | campaignName | userId          | clientId | clientContact | contactEmail | campaignObjectives | acNumber | notes | active | created_at          | updated_at          |
+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+
|  1 | test         |               7 |       10 | Mr Fakes      | 12345        | sdfsdfsd           | 12345    |       |      0 | 2016-02-29 11:51:59 | 2016-02-29 13:51:28 |
+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+

I then have a CampaignTypes Model with the following structure

+----+--------------+-----------------+------------+---------------------+---------------------+
| id | campaignType | creativeArrival | campaignId | created_at          | updated_at          |
+----+--------------+-----------------+------------+---------------------+---------------------+
| 14 | Dynamic      | 2016-02-26      |          1 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
+----+--------------+-----------------+------------+---------------------+---------------------+

The relationships in these Models is pretty straight forward. A Campaign can have many CampaignTypes and a CamapignType belongs to a Campaign.

In the Campaign schema I have an active column. This is what I use to delete a Campaign. So the destroy method looks like the following

public function destroy(Campaign $campaign)
{
    $campaign->update([
        'active' => false
    ]);

    Session::flash('flash_message', 'Campaign deleted');
    Session::flash('flash_type', 'alert-success');
    return Redirect::route('campaigns.index')->with('message', 'Campaign deleted.');
}

Now although it does not cause too many problems, I do not currently set any CampaignTypes row as being deleted if its parent Campaign has been deleted.

What would be the best way to delete the child data without actually deleting it?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TKEuLM
via IFTTT

SignatureDoesNotMatch AWS With Laravel 5.1

I have a problem to list files from my bucket in S3 using Laravel 5.1. When I try , it returns the message " SignatureDoesNotMatchThe signature request, calculated does not match the signature you provided. Make sure your key and signature ." I tested this on a Java class and return Ok . Below my setup .

' S3 ' = > [
' Driver ' => ' s3 '
' Key ' => env ( ' S3_KEY ' ) ,
' Secret' = > env ( ' S3_SECRET ' ) ,
" Region " = > env ( ' S3_REGION ' ) ,
' Bucket ' => env ( ' S3_BUCKET ' ) ,
' Scheme ' => ' http '
]
:: Storage disk ( s3 ) -> files ( )

Any idea ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QfPHlg
via IFTTT

Laravel 5 - passinf data to view when they are null

I have a Model called Data. My Data Model has a show page. On this show page I have tabs where data related to this Model can be inputted. So the show view for Data looks something like this.

<div id="cInfo" class="tab-pane in active fade">
    @if (count($dType) == 0)
        @include('forms.dTypes.dtypes')
    @else
        @include('forms.dTypes.dtypesEdit')
    @endif
</div>
<div id="cAndC" class="tab-pane fade">
    @if (count($dCreative) == 0)
        @include('forms.dCreatives.dcreatives')
    @else
        @include('forms.dCreatives.dcreativesEdit')
    @endif
</div>

dType and dCreative are Models that belong to Data. Relationships have been set up appropiately. Now I am having an issue in my DataController, specifically the show function. At the moment I have something like so

public function show(Data $data)
{
    $dataManager = User::select('userName')->where('id', $data->userId)->first();
    $clientName = Client::select('clientName')->where('id', $data->clientId)->first();

    $dType = DataType::where('dataId', '=', $data->id)->get();

    $dCreative = CampaignCreatives::where('dataId', '=', $data->id)->first();

    return View::make('campaigns.show', compact('data', 'dataManager', 'clientName', 'dType', 'dCreative'));
}

My first problem is with dType and dCreative. So when a Data Model is first added, dType and dCreative have not yet been created.
Therefore, when I get to the show page for Data, I get the error Trying to get property of non-object. These two Collections should only be passed to the view if they have been created.

What would be the best way to achieve this?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QGitbK
via IFTTT

Angular JS: Passing input parameters in HTTP service (POST)

I'm new to Angular JS and have been stuck in this problem.

<body class="homepage" ng-app="angularApp">

    <div ng-controller="myCtrl">
        <ul>
            @foreach ($fruits as $fruit) 
            <!-- looping -->
            <input type="hidden" value="{{$fruit->id}}" ng-model="testParameter">
            <button  ng-click="testClick(testParameter)" class="adding_item_to_cart">Add to Cart</button>
            @endforeach
        </ul>
        <p ng-bind="testBind"></p>
    </div>

<script type="text/javascript">
    var angularApp = angular.module('angularApp', []);
    angularApp.controller('myCtrl', function($scope, $http) {
        $scope.testClick = function(id) {
             $http({
                method : "POST",
                url : "/fruits/add/".id
             }).then(function addSucces(response) {
                $scope.testBind =response.data;
             }, function addError(response) {
                $scope.testBind = "Error!";
             });
        }
     });
</script>

</body>

What I've been trying to do is to send a parameter as an input value of HTTP request when the testClick is invoked to run the POST method, based on which fruit (i.e. the contents of the for-loop) has been chosen. (In this example, I'm trying to run a Route method of Laravel 5.2).

So far, I have found some postings on Stackoverflow, which are apparently relevant to this task. The code above is modified several times, following the advice of those postings.

I do understand this causes an error, but I'm clueless as to what is actually wrong and what I need to do instead.

ANY advice will be appreciated!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1nb2zhT
via IFTTT

Single route for multiple pages using Blade - Laravel

I'm trying to implement a system where I use a single route in laravel for different views.

So a route http://ift.tt/1TKfvrU will show 4 views depending on what step the customer is on the checkout process.

At the moment I've managed to do this with 2 views;

I have a main checkout.blade.php and then inside it I have the below;

@if(!Session::has('qwick'))
    @include('pages.checkout-nlog')
@else
    @include('pages.checkout-log')
@endif

the code above shows 2 views depending on whether the user is logged in or not.

I have 2 other blade views I need to somehow show.

Is this possible?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1XUO7Il
via IFTTT

Why are Form and HTML helpers deprecated in Laravel 5.x

The title basically says it all. Why are the From and HTML helpers deprecated since Laravel 5. I know I could use something like laravelcollective/html packages. But I was just wondering why Laravel stopped using/devolving the helpers.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/21CZKG6
via IFTTT

Laravel 5.2 Dingo API InternalRequest NotFoundHttpException

I always get NotFoundHttpException error when trying to access Dingo API InternalRequest.

My Controller:

use Dingo\Api\Routing\Helpers;

class C_Users extends Controller { use Helpers;

public $dispatcher;
public function __construct()
{
    $this->dispatcher = app('Dingo\Api\Dispatcher');
}

public function loginPost(Request $request)
{
    $response = $this->dispatcher
        ->json([
            'email'     => $request->input('email'),
            'password'  => $request->input('password')
        ])
        ->post('api/login');

    $responseArray = json_decode($response, true);

    if (!empty($responseArray) && $responseArray['status'] == 'success')
    {
        return response()->view('home');
    }
    else
    {
        return response()->view('auth.login', [$responseArray['messages']]);
    }
}   

}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TMbi8D
via IFTTT

Delete all the tables in database in one shot

How to delete all the tables in a database in one shot in laravel.

For Migration we use-

        Artisan::call('migrate', ['--force' => true]);

but for deleting all the tables is there any-

Thank You



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1SbCEE0
via IFTTT

dimanche 28 février 2016

Laravel AWS S3 Error

I'm thinking I installed this wrong, but keep getting the same error. Installed league/flysystem-aws-s3-v3. S3 creds are setup in .env file.

Added these to the require in composer.

"aws/aws-sdk-php"
"aws/aws-sdk-php-laravel": "~3.0"
--------------------------------------------

Code:

$s3 = \Storage::disk('s3');
$s3->put($location, file_get_contents($image), 'public');

Getting the following error:

exception 'InvalidArgumentException' with message 'Missing required client configuration options: 

' in /var/www/laravel/vendor/aws/aws-sdk-php/src/ClientResolver.php:328

Did some research online and couldn't find a solution.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VMrWCE
via IFTTT

Laravel 5 - query using a model, get results with a different model

Is it possible to return model query results via different model than the one that originally made the query?

For example, if we have two models, ModelA and ModelB, and we fetch some database results:

$modelA = new ModelA;

$results = $modelA->all();

dd($results);

Instead of a collection of ModelA objects, can it somehow return ModelB objects? The desired output, for example:

Collection {#325 ▼
    #modelA_Table: Array:4 [▼
        0 => ModelB { #297 ▶}
        1 => ModelB { #306 ▶}
        2 => ModelB { #311 ▶}
        3 => ModelB { #318 ▶}
    ]
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oRUdO4
via IFTTT

JWT Token Change Authentication Setting

I am creating a JWT token based REST api. I am succeed to create JWT token on different table('customers'). But when i call my REST api and pass the token it return

error = "User not found"

.

So my question is how can i change the JWT setting to set the JWT authentication on customer table. By default it refer to App\User but i want to change it to App\Customer. Is it possible? if it is possible so how?

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oIqZAF
via IFTTT

How do I get a list of routes from a module/directory in Laravel 5?

I have 3 modules in app folder such as: User Module , Role Module and Permission Module. Also I have different route.php file in each and every module. Now I need to get a route list from User Module.

I got a complete list from all modules using this code:

    $routeCollection =Route::getRoutes();  
    foreach ($routeCollection as $value) {
        echo $value->getPath()."<br>";
    }

Instead of all routes, I want to get a list of routes from a specific module or a specific directory as User Module.

How do I get a list of routes for a specific folder/module/file ? Thanks in Advanced.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LpcQTn
via IFTTT

How to get login with different database table column name inn Laravel 5.2?

I have to implement login functionality in Laravel 5.2. As per laravel official docs, I success ed. But now, problem is that I have to authenticate user on different database table column name. i.e, st_username and st_password. So I don't know how to implement that. I have searched on Internet for this. But there is exapmles with fully manual login functionality. And in some, they uses Auth. But I don't know that which class I need to use (like, use Illuminate.......) for Auth. If any one knows the answer, answer will be appreciated. Here is my code.

Login View

@extends('layouts.app')
@section('content')

<div class="contact-bg2">
    <div class="container">
        <div class="booking">
            <h3>Login</h3>
            <div class="col-md-4 booking-form" style="margin: 0 33%;">
                <form method="post" action="{{ url('/login') }}">
                    {!! csrf_field() !!}

                    <h5>USERNAME</h5>
                    <input type="text" name="username" value="akkivaghasiya5">
                    <h5>PASSWORD</h5>
                    <input type="password" name="password" value="akkivaghasiya5">

                    <input type="submit" value="Login">
                    <input type="reset" value="Reset">
                </form>
            </div>
        </div>
    </div>

</div>
<div></div>


@endsection

AuthController

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        $this->username = 'st_username';
        $this->password = 'st_password';
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
                    'name' => 'required|max:255',
                    'email' => 'required|email|max:255|unique:users',
                    'password' => 'required|confirmed|min:6',
        ]);
    }

Route File

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

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/home', 'HomeController@index');
});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1SboZwE
via IFTTT

how to set an argument to url in Laravel5 pagination5?

I'm create a pagination using laravel5 as this url http://ift.tt/21ur8cO But I want to set a segment to that url with laravel pagination

http://ift.tt/1QFNKeZ Is it possible in Laravel?

Existing code they used

@include('partials.pagination',['results'=>$data])

This is that pagination

<?php
    $num_display = 7;
    $page  = $results->currentPage();
    $last  = $results->lastPage();
    $start = ( ($page - $num_display ) > 0 ) ? $page - $num_display : 1;
    $end   = ( ( $page + $num_display ) < $last ) ? $page + $num_display : $last;

    if($last > 1){
        $html  = '<ul class="pagination pagination-sm pull-right">';
        $class = ( $page == 1 ) ? "disabled" : "";
        $html .= '<li class="' . $class . '"><a href="' .$results->url( $page - 1 ) . '">&laquo;</a></li>';

        if ( $start > 1 ) {
            $html .= '<li><a href="'.$results->url(1).'">1</a></li>';
            $html .= '<li class="disabled"><span>...</span></li>';
        }

        for ( $i = $start ; $i <= $end; $i++ ) {
            $class = ( $page == $i ) ? "active" : "";
            $html .= '<li class="' . $class . '"><a href="'. $results->url($i) . '">' . $i . '</a></li>';
        }

        if ( $end < $last ) {
            $html .= '<li class="disabled"><span>...</span></li>';
            $html .= '<li><a href="' .$results->url($last) . '">' . $last . '</a></li>';
        }

        $class = ( $page == $last ) ? "disabled" : "";
        $html .= '<li class="' . $class . '"><a href="' . $results->url( $page + 1 ) . '">&raquo;</a></li>';
        $html .= '</ul>';
        echo $html;
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1n9SQIL
via IFTTT

laravel : redirect()->back()->with() not sending any messages

I did as directed according to the answer provided to this question but it didn't work for me . So i reasked this question. my controller is

public function save() {

        $med_group = MedicineGroup::create(Request::all());

        if ($med_group) {
            $this->setServerMessage('MedicineGroup created successfully');
            return Redirect::to('admin/user/create')->with('flashmessage',$this->getServerMessage());

        }
    }

I have made setServerMessage() and getServerMessage() in Controller.php

public function setServerMessage($messagearray) {
        if (is_array($messagearray)) {
            $type = $messagearray['type'];
            $html = "<div style='height:auto;padding:7px 0px 6px 20px;margin:0px' class = 'pull-left text-left col-md-8 alert alert-{$type}'>{$messagearray[0]}</div>";
        } else {
            $html = "<div style='height:33px;padding:7px 0px 6px 20px;margin:0px' class = 'pull-left text-left col-md-8 alert alert-info'>{$messagearray}</div>";
        }
        $temp = '';
        if (\Session::get('SERVER_MESSAGE')) {
            $temp = \Session::get('SERVER_MESSAGE');
        }
        \Session::put('SERVER_MESSAGE', $temp . $html);
    }

public function getServerMessage() {

        if (\Session::get('SERVER_MESSAGE')) {
            $temp = \Session::get('SERVER_MESSAGE');
            \Session::forget('SERVER_MESSAGE');
            return $temp;
        } else
            return "";
    }

my view is setup like this

<div class="box-footer text-right">
                @include('flash')
                <input type="submit" class="btn btn-success" value='Save'>
                <input type="reset" class="btn btn-primary" value='Reset' />
                <a href="#" class="btn btn-danger">Cancel</a>
            </div>

and in my flash.blade.php i have written

@if(isset($flashmessage))
   {!! $flashmessage !!}
@endif

what did I miss? i followed this site too but i can't flash a message in my view.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1RyATOX
via IFTTT

Eloquent relationship with several models

I'm new to Laravel and I've been watching the Laracast videos but I didn't understand the Defining Relationships With Eloquent. Then, I moved to the official documentation to understand a little bit more, and by following their examples, I could make something work.

I'm building a small blog website using Laravel 5.2, and I already have few tables in my database. They are users, posts, categories, comments and likes.

So far, I've build a Post and Comment model. Post hasMany Comment, while Comment belongsTo Post, and following the documentation's examples, I've made the following in my controller, in order to show the comments of that specific Post:

public function show($id)
{
    return \View::make('admin/post/show')->with(array(
        'post' => \DB::table('posts')->find($id),
        'comments' => \App\Post::find($id)->comments
    ));
}

And showed in the show.blade.php view like this:

<div class="row">
    @foreach ($comments as $comment)
        {{ $comment->comment }}
    @endforeach
</div>

Is this way of doing it correct? I need also to show the User's name along with the Comment. Also, about the Like model, I will eventually need to show the User's name and the Post's title. Is there a better way of how I just did for these needs, with more than two related models?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1OGzwJv
via IFTTT

Get each element of pagination

I'm creating an ecommerce site that has infinite scroll in the catalog page. I want to know how many times each product is show to an user in the screen (impressions). The problem is how to get the new 12 elements that renders every time a user scrolls down to a new page. Than pass their ids to the server and stores their impressions. Is there a way to access the new elements? I checked laravel documentation and I saw nothing about this.

This is my code that renders the products array in the template:

<div class="product-one">
 @foreach($products as $product)
 <div class="col-md-3 product-left"> 

 <div class="p-one simpleCart_shelfItem"> 
 <a href="{{ route('getprodpage', ['id' => $product->id]) }}">
 <img src="{{ $product->image_url1}}" alt="" />
 <div class="mask">
 <span>Comprar</span>
 </div>
 </a>
 <h4>{{ $product->name }}</h4>
 <p><a class="item_add" href="#"><i></i> 
 <span class=" item_price">
 R$ {{$product->price_min}}
 </span></a>
 </p>

 </div>
 </div>
 @endforeach()
 <div class="clearfix"> </div>
 </div>
<?php echo $products->render(); ?>

And this is the infinite scroll javascript:

$(function() {
    $('.shoes').jscroll({

        loadingHtml: '<center><img src="{{ URL::asset('images/loading.gif') }}" alt="Loading" /> </center>',
        autoTrigger: true,
        padding: 0,
        nextSelector: '.pagination li.active + li a', 
        contentSelector: 'div.shoes',

        callback: function() {
            $('ul.pagination:visible:first').hide();
        }
    });
});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QFDseQ
via IFTTT

How upload big files to S3 in laravel 5 with Queue?

How can I upload big files using Queue to AWS S3 in Laravel 5 ?

I want use queue but I don't get it how is possible pass the file to the Queue handle method ? my code:

////////////My controller

public function uploadToS3Queque(Request $request)
{
if ($request->hasFile('file')) {

    $job = (new UploadToS3($request->file('file')))->delay(10);
  $this->dispatch($job); 

}

}

////////////////my job

class UploadToS3 extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $file;

public function __construct($file)
{
    $this->file = file;
}

public function handle()
{

    Storage::disk('s3')->getDriver()->put('bucket/image.jpg',$this->file); 
}
}

with that code I get this error message:

Exception in Queue.php line 92:
Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

How should I pass the file to the queue?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oI8LiG
via IFTTT

Laravel 5 use Validator

What does use Validator do? I am getting the following error and I cannot find any information on it?

Error:

The use statement with non-compound name 'Validator' has no effect

My app path is:

app/Http/Controllers/Admin/AuthController



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KVYpGo
via IFTTT

Laravel 5.0 - Error by running composer install

On Ubuntu, when I clone my Laravel 5.0 project from GitHub and then hit "composer install", I get the following result:

enter image description here

I can't see the .env file, but I tried copying .env file from other local project and then I get one error loading blade files using @include():

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QFt3Qa
via IFTTT

How to processing an image downloaded from AWS S3 with Laravel 5?

I want download an image from AWS S3 and process it with php. I am using "imagecreatefromjpeg" and "getimagesize" to process my image but it seem that

Storage::disk('s3')->get(imageUrlonS3);

retrieve the image in binary and is giving me errors. This is my code:

function createSlices($imagePath) {

                //create transform driver object
                $im = imagecreatefromjpeg($imagePath);
                $sizeArray = getimagesize($imagePath);

                //Set the Image dimensions
                $imageWidth = $sizeArray[0];
                $imageHeight = $sizeArray[1];

                //See how many zoom levels are required for the width and height
                $widthLog = ceil(log($imageWidth/256,2));
                $heightLog = ceil(log($imageHeight/256,2));


                //more code here to slice the image
                .
                .
                .
                .
            }

            // ex: http://ift.tt/1XTGaTF
            $content = Storage::disk('s3')->get(imageUrlonS3);
            createSlices($content);

What am I missing here ?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UsN9Dt
via IFTTT

Laravel 5.1 Authentication views

I'm using laravel 5.1. In my controller I use the following login method:

public function postLogin(Request $request)
{   
   $email = $request->input('email');
   $password = $request->input('password');

   if (Auth::attempt(['email' => $email, 'password' => $password])) {
       return redirect()->intended('admin/dashboard');
   }

   return redirect('/login')->withErrors([
   'email' => 'These credentials do not match our records.']);
}

My route:

Route::get('admin/dashboard', 'AdminController@index');

My controller:

public function index()
{
    return view("Admin::index");
}

This works and redirects me to the index view after login. When the user is not logged in, it is still possible to access the index view by accessing the url: localhost/admin/dashboard.

How can I redirect the user to a custom page which shows an error to the user that it is not possible to access the url localhost/admin/dashboard when he is not logged in?

Any ideas? Thank you



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UsJxBc
via IFTTT

PHPUnit + Laravel 5.2 + Visit may not be refreshing

I am testing a view in Laravel 5.2, specifically the following blade:

<p>Balance: {{ Auth::user()->total() }}</p>

The PHPUnit test is as follows:

// In the setUp() I create a user and log them in,
// the associated tests for that case work well.
// After setUp() the PHPUnit is "seeing" the
// the user's page: /members/{username}

// Get user as variable.
$user = Auth::user();

// Have user post payment.
$user->pay(600);

// Verify user is expected user
$this->assertTrue(($user->username == 'something'));

// visit: User profile page.
// seeInDatabase: Verify new payment stored in database.
// see: Verify template updated with payment total.
$this->visit('/members/'. $user->username)
    ->seeInDatabase('payments', ['amount' => 600, 'user_id' => $user->id])
    ->see('Point balance: 600');

When I run this test via PHPUnit, the "Point balance" is displayed as 0. When I run the test manually, it is displayed properly.

So, I'm wondering what I am missing in this sequence?

ps. This is a huge part of my app, and I really don't want to avoid automating this part of testing.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KVtCcA
via IFTTT

PHP - Get multiple values between

I have html templates with contain some function like:

<label ng-bind="translate('form.label.email')"></label>

The translate() function is used multiple times in a view. I want to extract all the values from the templates. How can i do that?

This example needs to return form.label.email only



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Rde1lp
via IFTTT

need to print data to the differnet tables in same blade.php for different conditions.

I want to create a event calendar for my website using laravel 5.Can anyone help me? I know a php code of it. But I need a laravel one. Can you suggest some free templates?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TLnnKY
via IFTTT

Gulp - sassIn instead of stylesIn - Laravel 5.2

I know of the function mix.stylesIn('path/to/folder'), but this only compiles css and not sass. Is it possible to compile all sass files in a folder or do I have to use an array of all sass files?

Like:

 mix.sass([
    'app.scss',
    'controllers.scss'
], 'public/assets/css');



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LO2zuD
via IFTTT

How to access Laravel Singletons in a class?

I have registered a singleton in a service provider like so:

$this->app->singleton(MyClass::class);

This can normally be accessed by simply stating it in the parameters like so:

class FooController extends Controller
{
    public function index(MyClass $myClass)
    {
        //...
    }
}

However I cannot seem to be able to access this singleton in other custom classes (i.e. non controller classes). (http://ift.tt/1KUSqBz)

For example like here:

class Bar {
   private $myClass;

   public function __constructe() {
      $this->myClass = ... // TODO: get singleton
   }
}

How do I do this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/213V9dO
via IFTTT

Laravel 5 flash message keep appearing

I'm using flash for users feedback after the user successfully (or failed) in creating an article. I'm using PHP version 5.5.27. Here is my store function in controller :

public function store(ArticleRequest $request)
{

    $data = $request->all();

    Article::create($data);

    Flash::message('Article Created!');

    return redirect ('articles');

}

and here is the app.blade.php in my view :

<div class="container">

@include('flash::message')

@yield('content')

The flash message just keep appearing no matter where I navigate. but if I logged out the user from my app the flash is gone. I've tried using the original Session::message and it's still the same. I've also tried all the solution from Laravel 5 flash message flashes again after navigating away and using back button and it still didn't fix my problem. But when I tried creating a new fresh laravel project it did work nicely. I'm having the TokenMismatchException before this problem and fixing it by editing the VerifyCsrfToken.php file like below :

public function handle($request, Closure $next)
{
    //return parent::handle($request, $next);

    $response = $next($request);

    if (last(explode('\\',get_class($response))) != 'RedirectResponse') {
        $response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
    }

    return $response;

}

Is this problem related to VerifyCsrfToken.php file? How can I fix that? Any help would be appreciated



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1RwZSlH
via IFTTT

eloquent ORM (laravel): select from two tables associated with pivot table

I have tree tables in my database (Posts Tags Post_tag(pivot table)):

  1. Posts(id,content,title,...)
  2. Tags(id,tag_name)
  3. post_tag(id,post_id,tag_id)

Now my problem is about how can I select all posts with same tags to an post for example: select all posts that have similar tags as post 1. I have create the relationships between the posts and tags tables: In posts table:

    public function tags(){
    return $this->belongsToMany('App\Tag');}

In tags table:

    public function posts(){
    return $this->belongsToMany('App\Post');}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1php1I6
via IFTTT

Laravel user login system

I am using Laravel 5.2. I have an admin panel in my project with login page. User with valid email and password can access. But my code gives me error

ErrorException in UrlGenerator.php line 603:
Action App\Http\Controllers\AdminController@authenticate not defined. (View: E:\xampp\htdocs\blog\resources\views\admin\login.blade.php)

InvalidArgumentException in UrlGenerator.php line 603:
Action App\Http\Controllers\AdminController@authenticate not defined.

Here is my login form:

{!! Form::open(['class' => 'form-horizontal', 'role' => 'form', 'method' => 'post', 'action' => 'AdminController@authenticate']) !!}
                        <fieldset>

                            <div class="input-prepend" title="email">
                                <span class="add-on"><i class="halflings-icon user"></i></span>
                                <input class="input-large span10" name="email" id="email" type="text" placeholder="type email"/>
                            </div>
                            <div class="clearfix"></div>

                            <div class="input-prepend" title="Password">
                                <span class="add-on"><i class="halflings-icon lock"></i></span>
                                <input class="input-large span10" name="password" id="password" type="password" placeholder="type password"/>
                            </div>
                            <div class="clearfix"></div>

                            <label class="remember" for="remember"><input type="checkbox" id="remember" />Remember me</label>

                            <div class="button-login">  
                                <button type="submit" class="btn btn-primary">Login</button>
                            </div>
                            <div class="clearfix"></div>
                        </fieldset>
                    {!! Form::close() !!}

Here is my controller file:

<?php

namespace App\Http\Controllers;

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

class AdminController extends Controller
{
    public function showLogin()
    {
        return view('admin.login');
    }        
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('admin.admin_master');
        }
        else {
            return view('admin.login');
        }
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KU82W5
via IFTTT

Laravel artisan make:auth

I am new to Laravel 5 and I am wanting to create an "admin" area so I have created views/admin and controllers/admin folders. Is there a way using artisan or make:auth that will allow me to specify the "folder" that I would like the code to be installed into?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1XSzk0J
via IFTTT

samedi 27 février 2016

Laravel nested relationship foreach loops

I have this relationship betwen item and episode

item:

public function episodes()
    {
        return $this->hasMany(episode::class);
    }

episodes:

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

In controller

$latestanimes = DB::table('episodes')->where('category', 'anime')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

What I'm trying to do is get the title of the anime it belongs to of each episode

                       @foreach($latestanimes as $episode)
                              <tr>
                                <td>
                                    @foreach($episode->item as $parrent)
                                      {{  $parrent->title; }}
                                    @endforeach
                                </td>
                                <td>{{ $episode->number }}</td>
                                <td>{{ $episode->category }}</td>
                            </tr>
                        @endforeach

This gives me "Undefined property: stdClass::$item"

I tried debugging in routes.php

Route::get('/dd/{id}', function($id){

        $episode=App\episode::find($id);
        echo $episode->name. '<hr>';

        $item=$episode->item;
        echo $item->title;

    });

And this works ... Is there a way to access it directly? like

{{ $episode->item->title }}

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1n6pefm
via IFTTT

How to manage access based role-users without method checking ways using laravel 5.2

My actual project needs to implement an ACL for the diferent roles in my users.

For now, I have like 4 roles defined by the client (Administrator, Head of Departament, Secretary and Teachers) but he wants to create more roles whenever he needs it.

Knowing this the clue is I want to know if is there any way to control the system access without checking the access in each method of my system. Laravel provides my the Authorization services but is not enough for the desing of my system, but I think is a deprecated way checking every method.

My idea is implement something before enrouting any request and check if the user has access depending on his roles, in this way I won't need to check it in every method as the actual solution that laravel Authorization services, laravel-acl of Kodeine or similars offers me.

If someone has an idea to set forth this Idea please answer this.

Also I want to know if this could affect the system security and how and how I can handle that.

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1RwjQgh
via IFTTT

ErrorException when using Laravel's elixir to import a CSS file

I'm following a Laracast tutorial, episode 6, and I reached the part where the instructor uses <link rel="stylesheet" href="{{ elixir('css/app.css') }}"/> too call the CSS file, but whenever I do this, the following error is thrown:

ErrorException in helpers.php line 341:

file_get_contents(/home/gabriel/Documents/Rxe/public/build/rev-manifest.json): failed to open stream: No such file or directory (View: /home/gabriel/Documents/Rxe/resources/views/admin/layout.blade.php) (View: /home/gabriel/Documents/Rxe/resources/views/admin/layout.blade.php)

I've followed everything from the beginning, but I'm stuck at it.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1n5THdD
via IFTTT

Laravel save() not defined

I am trying to convert my existing insert methods into query scopes so that I can reuse them and have a more DRY approach.

This is what I want to convert into a Larvel query scope:

$time = new Time;
$time->employee_id  = $input['user_id'];
$time->day          = Carbon::now()->toDateString();
$time->clock_in     = Carbon::now()->toTimeString();
$time->save();

This is what I have now for the query scope:

public function scopeClockIn($query, $userID) {
    $query->employee_id  = $userID;
    $query->day          = Carbon::now()->toDateString();
    $query->clock_in     = Carbon::now()->toTimeString();
    $query->save();
}

This is how I am calling the above query scope:

$time = Time::clockIn($input['user_id']);

But I get the error:

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

I have also tried:

$time = new Time::clockIn($input['user_id']);

but when I try with the new keyword I get an error:

syntax error, unexpected 'clockIn' (T_STRING), expecting variable (T_VARIABLE) or '$'

Google has not been very helpful I have found other questions with the same error message but they are trying to retrieve results not insert them. Hoping someone here can help me figure out what I did wrong.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1S8UWWq
via IFTTT

upload files to rackspace with laravel 5

I am trying to upload files to rackspace cloud with laravel 5.0,I use the documentation of laravel onthid link http://ift.tt/1Lfo0K7 but It gives me an error. please any one can help me?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QkhfXK
via IFTTT

error with migrate refresh

I am getting this error when trying to run: php artisan migrate:refresh:

Rolled back: 2016_02_16_114444_create_posts_table
Rolled back: 2016_01_20_234538_expectations
Rolled back: 2016_01_20_200616_expectation_profile
Rolled back: 2015_12_22_111958_create_profiles_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table


  [Illuminate\Database\QueryException]                                          
  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'follower  
  _id' (SQL: alter table `follower_followee` add `follower_id` int unsigned no  
  t null, add `followee_id` int unsigned not null)                              

  [PDOException]                                                                
  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'follower  
  _id'

This is the migration the error refers to:

<?php

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

class FollowerFollowee extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('follower_followee', function (Blueprint $table) 
        {
            $table->integer('follower_id')->unsigned(); // follower id number,must be positive.
            $table->integer('followee_id')->unsigned(); // followee id number,must be positive.
            $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
            //The 'follower_id' column references to the 'id' column in a 'users' table.
            //When a user is deleted in the parent column ('follower_id'), then also the user in 'id' ('users') is deleted. 
            $table->foreign('followee_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()

{
    Schema::dropIfExists('follower_followee');
    }
}

when trying to run : composer dump-autoload - it returns only this:

Generating autoload files

I honestly can't identify where's that duplication appears. Any help would be lovely.

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1XRAEkp
via IFTTT

Can a REST API implement an MVC pattern

I need to build a REST API but it should implement a MVC pattern. But am confused what should go in the view section

I came up with the below architecture

1) .htacces will rewrite the URL and redirect to index.php 2) index.php will create an instance of httpkernal 3) httpkernal will do all the REST housekeeping and finally select the controller class and controller method depending on the request parameters 5) The View class will be created in the constructor of the Controller class and will be made available to all methods in the controller 6) controller class will have index ,store,update,destroy methods that will be called depending on the HTTP methods (GET,POST,PUT,DELETE) . These methods will intern call the respective models to do all the database operations. The data returned from the models will be passed to the view and the returned data will be returned back to the httpkernal 7) httpkernal will form the http header (success 200 ,error 400 ) depending on the return and print the output 8) Any exception throw anywhere will be caught by the httpkernal and a appropriate http header will be generated

Now the problem is what to put in the view. Actually why would I need a View? Can anyone help me with this? Or should I use a different architecture ? Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VKslpq
via IFTTT

How to pass data to childview in laravel 5

Is there a clean way to pass data to a child view that has been included through blade's @include? Since I know that Im going to be using the same code throughout my website I have decided that a particular variable name must be available for the child view to implement its display.

At first I used something like the following:

foreach($user->$posts as $requiredNameForChildView){
 @include('mychildView') //child view uses $requiredNameForChildView
}

But then things got more challenging with other views since I did not always need to loop through an array of objects as before, not allowing me to assign an alias using the 'as' in the foreach. In these cases Im opening a php environment and assigning $requiredNameForChildView before entering the child view but this does not seem to be inline with Laravel's clean code practices.

What are the best practices behind doing something of this sort?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WQQGtG
via IFTTT

larave 5.1 routes groups takes only the first controller?

Route::group(['prefix' => 'api'], function () {

    Route::controller(null, 'BoxController');
    Route::controller(null, 'CostController');

});

This is a routed group in Laravel 5.1 the urls for the first controller is working but not for the second one 'CostController'.

If I switch the lines the first one works only. I want both controllers url to be prefixed with ...api/box/ and ...api/cost/

Examples on the internet has only one controller in the group, maybe there is another syntax?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/24ujz4K
via IFTTT

laravel how to send request o a controlle with parameter

I am working on laravel 5

this is my controller

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class RequestController extends Controller
{

    public function sendRequest($endPoint, $body)
    {

        return view('response', "d");
    }
}

?>

and in my route i handle it like this:

Route::post("/request/send", 'RequestController@sendRequest');

then in my html i do

<form method="post" action="/request/send">
        <textarea id="code" contentEditable="true" name="body"></textarea>
        <input type="text" value="d" name="endPoint" />
        <input type="button" id="formattCode" value="format"/>
        <input type="submit" value="send"/>
    </form>

as you see, i do have the body and the endPoint in my html

however i am getting this error

ErrorException in RequestController.php line 11:
Missing argument 1 for App\Http\Controllers\RequestController::sendRequest()



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1S8mdIy
via IFTTT

Laravel 5.2 Login with id instead of email

Currently I've got the default Laravel 5.2 authentication mechanism. I'm trying to change that so the user can login with the id instead of the email. I can't really use the username-attribute in my controller, since I don't want the user to select the id. I still want to assign that via auto increment and email it to him. So my registration form is supposed to have the fields email, password and password_confirmation and my login form the fields id and password. Is that possible without rewriting the whole thing? I'd really appreciate any help. Thanks!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/24ugwcO
via IFTTT

Laravel string Localization in config files

I'm having problem using trans() function in config file, I feel it not supposed to be used that way. However I've no clue on what would be the most efficient way to translate string text in config files (files in /config folder).

Original code

<?php

return [
    'daily' => 'Daily'
];

When I try to implement trans() application crashes and laravel return white page without any error messages

<?php

return [
    'daily' => trans('app.daily_text')
];



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/21zhD8J
via IFTTT

PHP Gettext not showing correct language in Laravel

When I change language the first time it works perfectly. However, when I refresh the page the translation is back to english again, even though the language selector still says "Danish" and getLang returns da_DK.... Then when I run php artisan cache:clear it works the first time I refresh, but second time it is back to english again.

Any ideas what could be wrong here?

I am using the package http://ift.tt/1Ngew03 to translate. Laravel 5.2.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TFnLts
via IFTTT

Windows 10 apache virtual host config

I'm new to laravel. Using version 5.1. Trying to use laravel app as virtualhost. For this I've changed my httpd-vhosts.conf as below

NameVirtualHost *:80


<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs\practice\laraveldev/public"
    ServerName laraveldev
</VirtualHost>

Now trying to access the app in browser laraveldev or http://laraveldev but not working.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1n4tk7G
via IFTTT

apache virtual host with laravel 5 "Internal error 500"

I want to learn laravel, and recently installed a fresh copy laravel on an amazon ec2 instance through composer composer create-project laravel/laravel laravel-app with apache2, and php installed. I configure the confd file to change the document root to laravel-folder/public, when i try to go to the public ip address it show a server 500 error.

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.

    #elastic IP address
    ServerName 42.66.33.52 
    ServerAdmin webmaster@localhost
    DocumentRoot laravel-app/public

    <Directory laravel-app/public>
    DirectoryIndex index.php
    Options -Indexes +FollowSymLinks +MultiViews
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted

    </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

I've tried chmod 777 to the entire laravel folder and changed the url in app.php to 42.66.33.52, and it still showing the same error. I'm new to laravel, and I hope someone can point me to the right direction. I've host other PHP website from this server without using laravel framework and it is function normally.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QNlEVj
via IFTTT

Missing argument in Laravel 5 with Eloquent

At the moment I'm working on a statistic part of my cms about Formula 1.

My queries I have in my Model and want to access them from the controller.

That's my query from the Controller:

$maxlaps = Statistic::with('maxLapsTotal')->where('test_id', $id)->first();

That's my query in my Model.

public function maxLapsTotal($testdays)
{
    return $this->select(DB::raw('sum(laps) as laps'))
                ->where('test_id', $testdays)
                ->groupBy('driver_id')
                ->limit(1)->orderBy('laps', 'DESC')->first();
}

In this case, how is it possible to access from the controller using where?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TJG41H
via IFTTT

Session::setId not work in Laravel

I have code for testing :

public function setUp()
{
    parent::setUp();
    Session::setId('test');
}

public function testInitialize()
{
    echo Session::getId() . "\n";
}

and output in testInitialize function is:

bf7535b20443fd1302e2aa27a917a885b522e320

I assume that once laravel sets the session id it can't be set up again, but does somebody have snippet how to destroy session and set up again so the output in testInitialize() will be :

test



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1RuSNSL
via IFTTT

Unknown database issue after re-installing wamp server

After having trouble with wamp server, i've uninstalled it and made a mistake by moving the www folder and download wamp all over again.

So after installing wamp and fixing the problem i had, my project (using laravel) doesn't work anymore:

SQLSTATE[HY000] [1049] Unknown database 'db_name'

I tried php artisan cache:clear but nothing changed

How can I fix this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Tdn3oF
via IFTTT

Laravel 5: Data does not saved through blade form

I want to save a form input through Laravel 5.0 The page reloaded and back to the index page..But data does not save to mysql through routes.

Here is controller:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests\CreateTaskRequest;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Task;
use Input;


class TodoController extends Controller {


    public function index()
    {
    $data=Task::all();
//  $options=Option::whereNotIn('id',$activeCourse)->lists('option_name','id');
        return view('home')->with('data',$data);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //return view('home');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(CreateTaskRequest $request)
    {
        // dd($request->all());

        /*$data=[
                'name'=>Input::get('name'),
                'status'=>Input::get('status'),
                'description'=>Input::get('description'),
                'task_img'=>Input::get('task_img'), 
                'dob'=>Input::get('dob')
             ];*/

                $response=new Task();
                $response->name=$request->input('name');
                $response->status=$request->input('status');
                $response->description=$request->input('description');
                $response->description=$request->input('task_img');
                $response->description=$request->input('dob');

             $response->save();
            // dd('working?');

             //$response=Task::create(['name'=>$request->input('name'),'status'=>$request->input('status'),'description'=>$request->input('description')]);
             if($response){
                return redirect()->back()->with('success','Task Created Successfully');
             }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $data=Task::find($id);
        return view('todo_edit')->with('data',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(CreateTaskRequest $request, $id)
    {
        $data=[
                'name'=>Input::get('name'),
                'status'=>Input::get('status')
             ];

             $response=Task::find($id)->update($data);
             if($response){
                return redirect('/');
             }

    }


    public function destroy($id)
    {
            $response=Task::find($id)->delete();
            if($response){
                return redirect('/')->with('success','Task Deleted Successfully');;
            }   
    }



}

Here is my View Page:

@extends('app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12 ">
        <div class="col-lg-12"> 
            <div  class="col-lg-6">
                {!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
                {!! Form::hidden('_token',csrf_token()) !!}
<!--            <form action="" method="POST" class="form-inline">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">        -->
                <div class="form-group">
                    <input type="text" name="name" class="form-control" placeholder="Enter a task name"></br>
                    </br>
                        <lavel> <input name="status" type="radio" value="Complete"> Complete</lavel></br>
                    <label> <input checked="checked" name="status" type="radio" value="Incomplete"> Incomplete</label></br>
                    <textarea class="form-control" name="description" rows="3"></textarea></br> 
                    <label>File input</label>
                          <input type="file" name="task_img"></br>
                    <input type="date" class="form-control datepicker" name="dob"  style="width:95%"> 

<!--                        <input type="submit" class="btn btn-primary" value="Save">      -->

                    {!! Form::submit('Save', array('class' => 'btn btn-primary')) !!}
                </div>

<!--            </form>   -->
            {!! Form::close() !!}
        </div>

            </div> 



            <h3> Todo Application </h3>
            <table  class="table table-striped table-bordered"  id="example">
                <thead>
                    <tr>
                    <td>Serial No</td>
                    <td>Task Name</td>
                    <td>Status</td>
                    <td>Action</td>
                </tr>
                </thead>
                <tbody>
                    <?php $i=1; ?>
                @foreach($data as $row)

                    <tr>
                        <td>{{$i}}</td>
                        <td>{{$row->name }}</td>
                        <td>{{$row->status}}</td>
                        <td>
                            <a href="{{route('getEditRoute',$row->id)}}" class="btn btn-warning">Edit</a>
                            <form action="{{route('postDeleteRoute',$row->id)}}" method="POST" style="display:inline;" 
                            onsubmit="if(confirm('Are you sure?')) {return true} else {return false};">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <input type="submit" class="btn btn-danger" value="Delete">
                            </form>

                        </td>
                    </tr>
                <?php $i++; ?>

                @endforeach
                </tbody>


            </table>

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

@section('page-script')
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
    $('#example').DataTable();
} );
</script>
@stop




@endsection

And here is the routes :

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/



Route::get('/',
 'TodoController@index');
Route::post('/', 'TodoController@store');

Route::get('/{id}/edit',['as'=>'getEditRoute','uses'=>'TodoController@edit']);
Route::post('/{id}/edit',['as'=>'postUpdateRoute','uses'=>'TodoController@update']);
Route::post('/{id}/delete',['as'=>'postDeleteRoute','uses'=>'TodoController@destroy']);

//Route::get('home', 'HomeController@index');

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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VJWvca
via IFTTT