Tuesday, May 23, 2017

email validation not working in update form using laravel validation

$id = $request->id;
$validation = Validator::make($request->all(), [
   'email' => 'unique:customers,email,'.$request->id
]);



via suresh

How can I add operator ternary in class on the view laravel blade?

I try like this :

@for($i = 0; $i < 5; $i++) 
...
    <div class="image ($i==0) ? 'image-main' : ''">
...
@endfor

But it does not work.

It seems the way of writing is incorrect.

How can I solve this problem?



via Trending News

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

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

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



via abitha shal

Dependency resolving with make not working when bind is done by a provider in Laravel

I'm using Laravel 5.2. I tried to resolve a dependency in laravel out of the IOCContainer as follows.(with App::make method)

App/FooController.php:-

<?php

namespace App\Http\Controllers;

use App\Bind\FooInterface;
use Illuminate\Support\Facades\App;

class FooController extends Controller
{
    public  function outOfContainer(){
        dd(App::make('\App\bind\FooInterface')); // Focus: program dies here!!
    }
}

Bindings for the FooInterface done in the AppServiceProvider as follows

App/Providers/AppServiceProvider.php:-

<?php

namespace App\Providers;

use App\Bind\Foo;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('\App\Bind\FooInterface', function() {
            return new Foo();
        });
    }
}

Structure of the Foo class as follows.

App/Bind/Foo.php:-

<?php

namespace App\Bind;


class Foo implements FooInterface {

} 

Structure of the 'FooInterface' interface as follows:-

<?php

namespace App\Bind;


interface FooInterface {

}

Then I created a routed as follows.

Route::get('/outofcontainer', 'FooController@outOfContainer');

But when I browse this route it throws an exception in informing,

BindingResolutionException in Container.php line 748:
Target [App\bind\FooInterface] is not instantiable.

What is going wrong with this? How to use App:make() with the AppServiceProvider?



via user8057101

Laravel Join multiple table not working

I'm having an issue on Laravel 5.4 when I try to use only one join it works ok and returns correct data, but their add another join it doesn't work.

$data = Player::select(DB::raw('CONCAT(familyName,", ",firstName) AS fullName'))
    ->where('firstname', 'like', '%'.$search.'%')
    ->orWhere('familyName', 'like', '%'.$search.'%')
    ->orderBy('familyName', 'asc')
    ->join('teams', 'players.primaryClubId', '=', 'teams.clubId')
    ->join('person_competition_statistics', 'players.personId', '=', 'person_competition_statistics.personId')
    ->addSelect(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode'])
    ->get()
    ->unique() //remove duplicates
    ->groupBy(function($item, $key) { //group familyName that starts in same letter
        return substr($item['familyName'], 0, 1);
    })
    ->map(function ($subCollection) {
        return $subCollection->chunk(4); // put your group size
    });

return $data;

Returned Error:

QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'familyName' in field list is ambiguous (SQL: select CONCAT(familyName,", ",firstName) AS fullName, `players`.*, `teams`.`teamName`, `teams`.`teamNickname`, `teams`.`teamCode` from `players` inner join `teams` on `players`.`primaryClubId` = `teams`.`clubId` inner join `person_competition_statistics` on `players`.`personId` = `person_competition_statistics`.`personId` where `firstname` like %% or `familyName` like %% order by `familyName` asc)



via PenAndPapers

How to update data when its exist, and not create when its not exist, Laravel 5

I have problem in my database query
I had first import 2 entry like this THIS, and the data inserted correctly

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 50.000          | 2,25    | 0 
11223344      | 100.000| 2.2017| 120.000         | 2,25    | 2700
11223344      | 100.000| 3.2017| 185.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 248.000         | 2,25    | 1417,5

but when i import again with additional row enter image description here, its become like this

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 50.000          | 2,25    | 0 
11223344      | 100.000| 2.2017| 120.000         | 2,25    | 2700
11223344      | 100.000| 3.2017| 185.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 248.000         | 2,25    | 1417,5
11223344      | 100.000| 1.2017| 63.100          | 2,25    | 0 
11223344      | 100.000| 2.2017| 142.700         | 2,25    | 2700
11223344      | 100.000| 3.2017| 205.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 279.400         | 2,25    | 1417,5

the result i want is like this

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 63.100          | 2,25    | 0 
11223344      | 100.000| 2.2017| 155.800         | 2,25    | 2700
11223344      | 100.000| 3.2017| 240.800         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 332.200         | 2,25    | 1417,5

the rebate and total voucher column isnt problem, the main problem is in total_transaction.
this is the code in my Controller function importCsv



    $voucher = Voucher::firstOrCreate(array(
     'wholesaler_id' => $wholesaler_id,
     'target' => $target,
     'week' => $week . '.' . date("Y"),
     'total_transaction' => $sum,
     'rebate' => $wholesaler_type->rebate_percentage,
     'total_voucher' => $total_voucher
     ));



via Faisal Hilmi

How do I get my user_id from the authorised client

I want to retrieve the id of the user that's currently online. But I CANNOT do it with the following code:

Route::middleware('auth:api')->post('/optionelections', function (Request $request) {
        return $request->user();
    });

The reason is because I keep getting the same unauthorised error from Laravel. I've been trying to fix this error for days and I can't seem to find a solution. So I'm trying to do it in a different way but I don't know how. I'm currently using Passport to store my token and my client_id in local storage.

this is my apply_election.vue

    import {apiDomain} from '../../config'
  export default {
    name: 'applyForElection',
    data () {
      return {
        election: {},
        newOption: {'election_id': ''},
        //this is where the user_id should come
        newOption: {'user_id': ''}

      }
    },
    methods: {
      createOption: function () {
        var itemId = this.$route.params.id
        this.newOption.election_id = itemId
        this.$http.post(apiDomain + 'optionelections', this.newOption)
          .then((response) => {
            this.newOption = {'election_id': itemId}
            alert('you applied!')
            this.$router.push('/electionsnotstarted')
          }).catch(e => {
            console.log(e)
            alert('there was an error')
            this.$router.push('/electionsnotstarted')
          })
      }
    },
    created: function () {
      var itemId = this.$route.params.id
      this.$http.get('http://www.nmdad2-05-elector.local/api/v1/elections/' + itemId)
        .then(function (response) {
          this.election = response.data
        })
    }
  }

and this in my OptionElectionsController.php

public function store(Request $request)
    {


        $optionElection = new OptionElection();
        $optionElection->user_id = $request['user_id'];
        $optionElection->option = "something";
        $optionElection->votes = 0;
        $optionElection->election_id = $request['election_id'];
        $optionElection->accepted = 0;

        if ($optionElection->save()) {


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

        }

    }

this is my Auth.js

export default function (Vue) {
  Vue.auth = {
    setToken (token, expiration) {
      localStorage.setItem('token', token)
      localStorage.setItem('expiration', expiration)
    },
    getToken () {
      var token = localStorage.getItem('token')
      var expiration = localStorage.getItem('expiration')

      if (!token || !expiration) {
        return null
      }
      if (Date.now() > parseInt(expiration)) {
        this.destroyToken()
        return null
      } else {
        return token
      }
    },
    destroyToken () {
      localStorage.removeItem('token')
      localStorage.removeItem('expiration')
    },
    isAuthenticated () {
      if (this.getToken()) {
        return true
      } else {
        return false
      }
    }
  }

  Object.defineProperties(Vue.prototype, {
    $auth: {
      get: () => {
        return Vue.auth
      }
    }
  })
}



via hxwtch

Laravel Querybuilder join on LIKE

I am attempting to join two tables using the Laravel's query builder however I seem to be having an issue getting the desired result using the query builder, I can however get it quite simply using a raw SQL statement. I simply want to return all mod rows that have the corrosponding value in the tag column in the tags table.

Working SQL query

SELECT * FROM mod JOIN tags ON tags.tag LIKE '%FPS%'

Query Builder

DB::table('mods')
 ->join('tags', function ($join) {
     $join->on('tags.tag', 'like', '%FPS%');
 })
 ->get();

Currently this is telling me: Unknown column '%FPS%' in 'on clause' but I am unsure how else to structure this. I intend on adding more orOn clauses as well as I will want to get results on multiple tags but firstly I just want to get a single tag working.

Appreciate any help.



via XanT

Laravel, Guzzle - Check if Cookie is set

I wish to check if the cookie is set, when doing the bottom getUsername. Can anyone help me with a quick fix for this? I've tried for hours without luck.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cookie;

class CookieController extends Controller {
   public function setCookie(\stdClass $request){
     $minutes = 60;
     $response = new Response(view('panel.panel'));
     $response->withCookie(cookie('userInfo', $request, $minutes));
     return $response;
    }
   public function getCookie(){
       $val = cookie::get('userInfo');
       return $val;
    }

public function getUsername(){
    $cookie = cookie::get('userInfo');
    return $cookie->message->username;
}

public function getShopID(){
    $cookie = cookie::get('ShopID');
    return $cookie->message->shopID;
}
}
?>



via Codey93

How to pass helper data to all views in Laravel 5 using helper in AppServiceProvider?

I would like to move a helper to be displayed in all views. The helper is ->

helperFunctions::getPageInfo($cart, $total);

At this moment I have to define in every controller that information, as an example:

public function show($id, Request $request)
{
    $category = Category::find($id);
    if (strtoupper($request->sort) == 'NEWEST') {
        $products = $category->products()->orderBy('created_at', 'desc')->paginate(40);
    } elseif (strtoupper($request->sort) == 'HIGHEST') {
        $products = $category->products()->orderBy('price', 'desc')->paginate(40);
    } elseif (strtoupper($request->sort) == 'LOWEST') {
        $products = $category->products()->orderBy('price', 'asc')->paginate(40);
    } else {
        $products = $category->products()->paginate(40);
    }
    helperFunctions::getPageInfo($sections, $cart, $total);
    return view('site.category', compact('cart', 'total', 'category', 'products'));
}

I read and tried to move that helper to AppServiceProvider.php, inside the Boot() function.

public function boot()
{

    helperFunctions::getPageInfo($cart,$total);
    View::share('cart','total');
} 

But im receiving error info:

Undefined variable: total



via s_h

DELETE route using vue-resource and laravel throwing 500 error

I have a route that will be used to delete an item.

Route::delete('items/{item}', 'ItemsController@destroy')->name('admin.items.destroy');

I have a vue component that, when a button is clicked, runs this method to delete the item.

removeItem() {

    let itemCode = this.item.itemCode;

    this.itemCode = this.item = null;

    this.$http.delete('/items/' + itemCode)
      .then(function(response) {
        this.refreshPage()
      });
  }, 

The result is a 500 internal server error when the request is made.

I have not had much success in finding out why.



via DanielPahor

Print Page doesn't break properly on second page

I am trying out a layout in the table print preview when as I notice it doesn't break properly in the second page even though I am using page-break-after: always; see my code then the screen of the output below

CSS declaration

    div.page
          {
            page-break-after: always;
            page-break-inside: avoid;
          }
.footer{
       position:fixed;
       bottom:-10px;
       height:32px;
    }

The footer

<hr class="footer" style="width:100%;height:5px;bottom:20px;background-color:black !important;">
<div class="footer"><img width="120px" height="20px" src="/logo.png"></div>
<div class="footer" style="right:20px"></div>
<div style="left:330px" class="footer" id="dateTime"></div>

The table

 <div class="page"><!--page css here-->
    <h2 id="heading">CHEMICAL TEST</h2>
    <p id="heading"></p>
    <p id="heading">Report No.: RN001</p>
    <hr>
    <center>
    <p id="heading"></p>
    <th>Username</th>
    <th>Name</th>
    <th>Data Calculation</th>
    <th>Status</th>
    <th>Date</th>

    @foreach($reportData as $data)
    <tr>
      <td> <br> </td>
      <td></td>
      <td></td>
      @if($data['method_status'] == 0)
      <td>Inactive</td>
      @else
      <td>Active</td>
      @endif
      <td> <br>  </td>
    </tr>
  @endforeach
    </table>
  <p id="totalresult_dtab">Total : </p>
    </div>
  </center>
</div>

The first page is breaking correctly but after that it's not.

See the first page of the output. enter image description here

Second page that is not breaking properly enter image description here

Can you help me how to break it properly?



via user827391012

hasManyThrough with multiple simple Pivot tables in play using Laravel Eloquent

  • User can have multiple profiles.
  • Each profile will have multiple Projects.
  • Projects will have multiple Tasks.

I want to show all the tasks assigned to user across all projects and profiles in a single view:

public function tasks()
{
    $result = collect();
    $profiles = $this->belongsToMany(\App\Profile::class);
    //now go thru each profile and find all the projects, then tasks
    $profiles->each(function($profile) use (&$result){
         $projects = $profile->projects()->get();
         $projects->each(function($project) use (&$result){
            $tasks = $project->tasks()->get();
            $tasks->each(function($task) use (&$result) {
                $result->push($task);}
          });
    });        
    return $result;
}

This does work but it feels really hobbled together. With multiple pivot tables in play is there a more efficient way to do this with Eloquent/Laravel?



via abbur

sql 42S22 error in Laravel (choosing a column I didn't mention)

I am doing a basic project in Laravel, when trying to delete an entry, it generates this error:

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

and it is true I don't have a column named 'id', instead I have employee_id, but why is it choosing id instead of employee_id?

Please explain from where did it bring this id column?



via M. Gamie

Laravel 5 Can't send data from url

Hi Im currently trying to make a basic crud for my questions resource on laravel 5

so far so good, but now Im having troubles displaying the edit view, because the url is not being created correctly when I try to send the resource id in the url

here's the anchor Im using

<a href=""><button class="submit-form button button btn btn-primary" style="margin: 0 1em;" type="submit">Editar</button></a>

here's the route in my routes file

Route::get('admin/preguntas/editar/{id}','QuestionsController@edit')->name('admin/questions/update');

the method in the controller works just fine, when I manually type this url

/admin/preguntas/editar/4

It shows the view without problems, but when I go from the anchor the url it goes is this one

/admin/preguntas/editar?4

of course the 4 is the id from my resource, but why is not typing the correct url?

thanks in advance



via Anibal Cardozo

Reset Specific Input Field Validation After Submitted AngularJS

Please help, How to reset validations specifically input fields when I checked checkbox. I used $scope.patient.ngModelName.$dirty = false; $scope.patient.ngModelName.$pristine = true; $scope.patient.ngModelName.$submitted = false; and it doesn't work. please kindly help



via kwell

Laravel - Admin section generator [Laravel 5.4]

I have been developing a web site that is kind of an online store and my user needs to access to control the products, stock and other things like that and having a basic CRUD of some of my Models, so I want to install something like GroceryCRUD (called ImageCRUD for Laravel), but the versión in its documentaion needs Laravel 4.2 and I am developing with the most recent version of it (5.4).

In few words, my question is... Is there something like GroceryCRUD for Laravel in this version?.



via Ricardo Villagrana Larios

Factories in Laravel / Design Pattern technique

I'm a little confused about Factories in Laravel.

Factories as all talk about is the ability to create dummies objects, so you can test, or just quickly generate dummy objects for your tests.

You usually use Faker helper to get random data.

Now, I have another frequent use case that require factories, it is object creation.

So, for example, In TreeController@store, I have a static method to create / update settings :

    $championship->settings =  ChampionshipSettings::createOrUpdate($request, $championship);

with

public static function createOrUpdate(Request $request, Championship $championship): ChampionshipSettings
{
    $request->request->add(['championship_id' => $championship->id]);
    $arrSettings = $request->except('_token', 'numFighters');
    $settings = static::where(['championship_id' => $championship->id])->first();
    if ($settings == null) {
        $settings = new self();
    }
    $settings->fill($arrSettings);

    $settings->save();

    return $settings;
}

I guess I would use Factories to manage object creation, but I can't because I already use them for dummy content.

Also, I could use different case in my factories, but it start incrementing complexity that I think I could avoid.

Then, I could use the existing factory, but if I don't specify an attribute, it will generate a random one, so I would need to set all unused attributes to null before creation...

Well, I'm kind of confused about how should I manage my factories...



via Juliatzin del Toro

Correctly configuring routes or htaccess for laravel in wamp

I'm learning laravel. I using this project https://github.com/jeremykenedy/laravel-auth

I follow each step without any problem. When it says 'projects root folder' I'm using the same folder and it seems fine.. not sue what it measn by 'projects root folder'

The project is located on wamp64/www/jeremy to access it I have to go to localhost/jeremy/public Shouldnt it be naturally localhost/jeremy?

And when it read css and images it looks for them into localhost/ not localhost/jeremy/public.

I'm not sure what more info I can give and not sure what exactly is the problem.



via Aschab

Destroying laravel session variable with plain php

I have created a seesion with laravel Session::put('cart', $cart);

How can I destroy it with php like session_destroy(); ? out side of laravel directory.



via Recoman

Validate Stripe expiry date

I am using Stripe for payment processing. I want to validate the card date whether it is expired or not. The date format should be 1-12 months/upcoming years.

For example: 11/19, 12/18, 08/21, 01/20

Controller:

$exp = explode( '/', Input::get( 'card_expiry' ) );
if ( ( $exp[0] <= 12 ) && $exp[0] > 0 && ( is_int( $exp[1] ) ) ) {

} else {
    return back()->withErrors( 'Add a valid card expiry date' );
}

Form:

<div class="form-group">
    <label>Expiry</label>
    
    @if($errors->first('card_expiry'))
    <div class="text-danger"></div>
    @endif
</div>

I tried the above code but its not working.



via Asif Nawaz

Nested Foreaches for Weekly Data

I have a list where customers can submit data weekly. I want to cycle through the weeks in a month (i.e. week 1, week 2...) and either show a value if it exists or show a select dropdown if not.

My problem is that I cant quite get the loops right. The below doesn't work as it outputs the data far too many times and i know the loops are in an incorrect order.

@if($customer->pay_schedule == 'weekly')
    @foreach($weeks as $week)
        @foreach($customer->payment as $payment)
            @if($week['week_start'] == $payment->pay_period_start & $week['week_end'] == $payment->pay_period_end)
                <div class="medium-3 columns">
                    Week 

                @foreach($statuses as $status)
                    @if($payment->pay_status == $status->id)
                        
                    @endif
                @endforeach
                </div>
            @else
                <div class="medium-3 columns">
                    Week 

                <select name="pay_status[]" class="form-control">
                    @foreach($statuses as $status)
                        <option value=""> </option>
                    @endforeach
                </select>
                </div>
            @endif
        @endforeach
    @endforeach
@endif

$customer->payment returns a collection of payments for that customer. So sometimes there is 4 weeks worth of data which is fine for the month.

But sometimes there is for example 3 weeks worth of data with week 4 missing which is the week where I would want a select to show so the data could be the entered.

Another example is there could be no data entered so a select would be needed for all 4 weeks of the month.

Hope that makes sense.



via Awilson089

How to execute a command on a server? php queue laravel ssh

I have a website in the Internet and I need to run command php artisan queue:listen on its server. I installed putty, logged in and tried to execute it, but it says php command not found :C. How should I do it proper way and how long this comand will run?



via Batmannn

Stop all fillable items trying to save to database laravel

I have a form with some items firstname, surname, checkbox

In my model I have

$fillable = [firstname, surname, checkbox]

$appends = [checkbox]

In my database only contains firstname and surname

The purpose of the checkbox is to signal something post saving in an observer.

I want to use mass assignment to set all these items.

However when it comes to saving my model it tries to save checkbox in the database.

How to get over this?

I dont want to singularly assign it with $model->checkbox = Input::get('checkbox') as I will eventually have lots of different items.



via George Hallam

Laravel Passport Get Client ID By Access Token

I'm writing a tiny sms gateway to be consumed by a couple of projects,

I implemented laravel passport authentication (client credentials grant token)

Then I've added CheckClientCredentials to api middleware group:

protected $middlewareGroups = [
    'web' => [
       ...
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        \Laravel\Passport\Http\Middleware\CheckClientCredentials::class
    ],
];

The logic is working fine, now in my controller I need to get client associated with a valid token.

routes.php

Route::post('/sms', function(Request $request) {
    // save the sms along with the client id and send it

    $client_id = ''; // get the client id somehow

    sendSms($request->text, $request->to, $client_id);
});

For obvious security reasons I can never send the client id with the consumer request e.g. $client_id = $request->client_id;.



via Mohammad Walid

Laravel schedule operation

Cron tasks has it's own scheduler: https://laravel.com/docs/5.4/scheduling and I just wondering is it possible somehow to achieve similar effect to run some task every 5 minutes ( wihout overlaping ) when calling command from command. For example:

Task1 is called every 1 minute:

$schedule->command('Task1')->everyMinute()

In this Task1 command I would like to call command Task2 every 5 minutes.

$schedule->command('Task2')->every5Minute()

Would it work having in mind that only Task1 is registered in Console/Kernel.php and Task2 is called from Task1?



via deividaspetraitis

How to redirect user in profile dependency of type?

I have some types of users. How to redirect user to profile dependency of account type?

After succesfull authorization I need to check Auth::user()->type and redirect to specified controller url.

I tried to use middleware for that:

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

            if(Auth::user()->type == "1"){
                return redirect('/center');
            }

           if(Auth::user()->type == "2"){
               return redirect('/doctor');
           }
        }

        return $next($request);
    }
}

But where to call this middleware once?



via Blablacar

Laravel fromTable not working on model updateOrCreate function

I am trying to change the model's table when using the update or create function, but it always uses the default database table which would be "Payouts" I am trying to change the table to "skyrim" by using the fromTable function.

$cluster_payout = 'skyrim';
    $user_payout = Payout::fromTable($cluster_payout)->updateOrCreate(
    ['user_id' => 1],
    ['game_id' => 1, 'locked' => 1]);

After executing the code, it uses the Payout Database and Payouts Table.

If I do

Payout::fromTable($cluster_payout)->first();

It'll use the Payout database with the Skyrim table. Any ideas?



via rebirth1078

Laravel named route pass variable

I'm trying to pass variable to a named route:

return redirect()->route('Company.Dashboard.Subscription.Index')->with(compact('message'));

But in blade i cant access the message variable.

Any ideas?

Thanks!



via user3844579

Production Request Generation Suggestion

I am creating an application in Laravel 5.3 using MYSQl.In the Project i have to generate a production request(i.e to produce chemical) the request is generated by a specific user.That production request is going to be accepted or rejected by the head of that user later on after the request has been generated.I am confused how to perform this task efficiently in my project.Should i simply create a table for this production requests or use laravel Queues? Kindly Please help



via Muhammad Mahin Dar

proc_open() fork fails in Laravel controller

I get an error saying: proc_open(): fork failed - Cannot allocate memory in a Laravel controller. The generate function is called with axios (Vuejs SAP).

This is what my controller looks like

use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use GifCreator\AnimGif;
use simpleimage\SimpleImage;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class GifController extends Controller
{
    //
    public function generate(Request $request)
    {
        if(!$request->ajax()) return;

        $cmd = 'ls';
        $process = new Process($cmd);
        $process->run();

        // executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        echo $process->getOutput();        

    }
}

free -m on server:

|       | total  | used  | free | shared | buff/cache | available |
| ----- | ------ | ----- | ---- | ------ | ---------- | --------- |
| Mem:  | 2000   | 243   | 577  | 20     | 1178       | 1541      |
| Swap: | 4095   | 0     | 4095 |        |            |           |

EDIT:

As Hilmi pointed out I've now tried adding a swap space, and now the command runs successfully sometimes – about half of the time.

Is there a way to retry the Process if it fails?



via kmaar

Accessing Object Properties VueJS

I want to render a list, based on data I provide via my API. I made a screenshot of the current output. The problem is, that I cannot access my object properties. I get an error when loading the page. How do I access the properties correctly? @ did not work.

<div class="row">
    <div class="col-lg-12">
        <ibox title="Einsätze">
            <table class="table">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Strasse</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="incident in incidents">
                    <td>@</td>
                </tr>
                </tbody>
            </table>
        </ibox>
    </div>
</div>

export default {
    name: 'dashboard',
    mixins: [MFSApi],

    template: "#dashboard",

    components: {
        ibox
    },

    data() {
        return {
            searchAddress: '',
            incidents: []
        }
    },

    mounted: function() {
        this.getAllIncidents(function(response) {
            this.incidents = response.data["data"];
        }.bind(this))
    },

    methods: {

    },

    created() {
        console.info('Dashboard component triggered');
    }
}

enter image description here



via sesc360

php_oci8_12c.dll - not found

  Warning: PHP Startup: Unable to load dynamic library 
  'C:\xampp\php\ext\php_oci8_12c.dll' - %1 is not a valid Win32 application.
  in Unknown on line 0

Hello, I am trying to connect php laravel with my oracle database and when I run this command:

    composer create-project laravel/laravel laravel "5.4.*" 

I get the error above. My php.ini seems to be fine, I have this:

    extension=php_oci8_12c.dll  ; Use with Oracle Database 12c Instant Client



via Gimv13

Laravel with Mailgun timed messages

I have found a way to delay sending e-mail through Mailgun API. I am wondering if external HTML can be used somehow to include in the mail?

Now I am doing it like this:

    $mgClient->sendMessage($domain, array(
        'from'    => 'XY<webmaster@xy.com>',
        'to'      => 'XY<xy@xy.com>',
        'subject' => trans('content.subject_confirm_event_registration'),
        'html'    => '<myHtmlCode />',
        'o:deliverytime' => Carbon::now()->hours(2)->toRfc2822String()
    ));

But the problem is when I try anything complex, which has like 100 lines of code, it doesn't look well, and I would like a solution where I can put external file in it so that it looks like this:

    $mgClient->sendMessage($domain, array(
        'from'    => 'XY<webmaster@xy.com>',
        'to'      => 'XY<xy@xy.com>',
        'subject' => trans('content.subject_confirm_event_registration'),
        'html'    => file.blade.php
        'o:deliverytime' => Carbon::now()->hours(2)->toRfc2822String()
    ));



via Norgul

Laravel sign in form does not work

I'm learning Laravel 5.3 and I have made a simple login form which goes like this and is saved in the file login.blade.php under the auth directory in resources/views:

    <html>
    <body>
        <form method="post" action="login">
            <input type="text" name="email" placeholder="email" size="40"><br>
            <input type="password" name="password" placeholder="password" size="40"><br>
            <input hidden name="_token" value="">
            <input type="submit" value="Send">
        </form>
    </body>
</html>

And in web.php I have added this:

    Route::post('/login','Auth\LoginController@login');
Route::post('logout','Auth\LoginController@logout');

So it is very simple and clear ,however whenever I try to login with my correct credentials it won't work and stays in the login page.

Here is the print screen of my users table:

enter image description here

Note that db is already connected and there's no need to mention that..



via dasoudeabiat

What is best practice in Laravel in terms of writing mysql query?

What is best practice in Laravel should I go with eloquent or with MySQL stored procedures and stored functions?



via Deepesh singh

Add custom conditional validation rule to the same attribute

I'm trying to add some custom validation logic for file uploads for my admin panel. Right now my file fields can return either Illuminate\Http\UploadedFile or string|null if file is not uploaded or changed or whatever. So, what i'm doing is, i created a custom rule that looks like this:

'image' => [
                'required',
                'admin_file:mimes:jpeg;png,dimensions:min_width=800;min_height=600'
           ]

I then parse all the arguments i pass, and the thing is, i naturally want all of them applied only if my value is an instance of UploadedFile. I use the following code for my custom validation:

class AdminFileValidator
{
    public function validate($attribute, $value, $parameters, Validator $validator)
    {
        $rules = implode(
            "|",
            array_map(function($item) {
                return str_replace(";", ",", $item);
            }, $parameters)
        );

        $validator->sometimes($attribute, $rules, function() use ($value) {
            return $value instanceof UploadedFile;
        });

        return true;
    }
}

The problem is, adding additional rules to an attribute via sometimes doesn't work that way, these added rules are not being processed by a validator.

I'd like to ask, is there any way to validate these rules without revalidating the whole thing manually?



via Eternal1

How to insert id from both tables into pivot table using laravel query builder

I have three tables in database

  1. users
  2. locations
  3. location_user (columns: user_id, location_id)

I'm fetching records from locations table in multiple-drop-down field of user registration form. While filling form user has to select value from drop-down and then submit.

After submitting the form I want to insert data into users table. At the same time I also want to insert id from users table into user_id column of location_user and selected value of locations from drop-down of user registration form into location_id column of location_user table.

I know how to get this to work using eloquent but I as i mentioned in the question I want to know how to deal with this task using query builder of laravel.



via viraj

How to correctly insert datetime into MYSQL database using HTML form?

I have what seems to be a relatively simple issue that has caused more problems than I thought it would. As you probably know, HTML5 no longer supports the "datetime" input for a form field, and only supports "datetime-local". When I try to insert "datetime-local" into my database through a form on my website, I obviously get an error because of the extra character included in "datetime-local". What I am trying to do, and why I need a datetime field as opposed to just a date and/or time in their own respective fields is because I want to use Carbon to display my datetime in different formats. How can I insert datetime through HTML form into mysql table without manually inserting the value into my database?

EDIT: Here is all of the relevant code that I am trying to achieve this with. I am using Laravel to build this application

game/create form:

<select name="season_id">

        @foreach ($seasons as $season)

        <option name="season_id" value=""> </option>

        @endforeach

</select>

<label for="inputDateTime" class="sr-only">DateTime</label>
    <input type="datetime-local" name="gdatetime" id="inputDateTime" class="form-control" placeholder="DateTime" required autofocus>

<label for="inputOpponent" class="sr-only">Opponent</label>
    <input type="text" name="opponent" id="inputOpponent" class="form-control" placeholder="Opponent" required autofocus>

<label for="inputLocation" class="sr-only">Location</label>
    <input type="text" name="location" id="inputLocation" class="form-control" placeholder="Location" required autofocus>

<label for="inputField" class="sr-only">Field</label>
    <input type="text" name="field" id="inputField" class="form-control" placeholder="Field" required autofocus>

game controller:

$game = Game::create(request(['gdatetime', 'opponent', 'location', 'field', 'season_id']));

Also, in my Game model, I have defined this:

protected $dates = ['gdatetime'];



via hoolakoola

foreach loop inside html table design in laravel

I have an array of data to display using table in html .but the foreach loop which i m using is not giving the desired format . Below is the array data

$data =  Array
(
    [0] => Array
        (
            [id] => 10
            [asset_name] => Mini Paver
            [qty] => 3
            [est_start_date] => 02/05/2017
            [days] => 2
            [comments] => Comment 2
            [bundle_name] => 1XRoller 1XPaver
        )

    [1] => Array
        (
            [id] => 11
            [asset_name] => Roller
            [qty] => 2
            [est_start_date] => 03/07/2018
            [days] => 4
            [comments] => Comment 2
            [bundle_name] => 1XRoller 1XPaver
        )
)

my view html code :

@foreach($data as $value) 

<table class="" style="width: 100%;border:1px solid #ccc">
<thead>
 <tr>
    <th colspan="4"> <p><?php echo $value['bundle_name'];?> </p></th>
  </tr>
<tr>
    <th style="text-align: center">id</th>
    <th style="width:5%;text-align: center">Asset Category</th>
    <th style="width:5%;text-align: center">Days</th>
    <th style="width:5%;text-align: center">Qty</th>
</tr>
</thead>
<tbody>

    <tr>
        <th style="text-align: center"><?php echo $value['id'];?> </th>
        <th style="width:5%;text-align: center"><?php echo $value['asset_name'];?></th>
        <th style="width:5%;text-align: center"><?php echo $value['days'];?></th>
        <th style="width:5%;text-align: center"><?php echo $value['qty'];?></th>
    </tr>

</tbody>
</table>
@endforeach

By using above for each loop i m getting the below html format like bundle name is repeating .enter image description here

But i need the output should be like as below : enter image description here

that means i want the bundle name shluld come only one time and the rest of details should display as in rows . How do i do that ? any suggestions please ? Thank you .



via 5367683

v-for doesn't go through my dynamic multidimensional array on Vue 2

I'm working on Laravel with Vue js 2 and on the mounted method I'm creating a multidimensional array with no problem (I can see the data with the vue-devtools), but I can't print it on my page using v-for.

However, when I dynamically create a simple array, I can print it with no problem.

My Vue code:

<script type='text/javascript'>
  var av = new Vue({
    el: '#validaciones',
    data: {
      vChallenges: ['CH1', 'CH2', 'CH3'],
      vPlayers: ['p1', 'p2', 'p3', 'p4'],
      vContest: [
          { ch: 'CH1', pl: ['p1', 'p2', 'p3', 'p4'] },
          { ch: 'CH2', pl: ['p1', 'p2', 'p3', 'p4'] },
          { ch: 'CH3', pl: ['p1', 'p2', 'p3', 'p4'] }
      ],
      vDynamicPlayers: [],
      vDynamicContest: [],
    },
    mounted: function() {
      for (i = 0; i < this.vChallenges.length; i++) {
        this.vDynamicContest[i] = { ch:this.vChallenges[i], pl:[] };
        for (j = 0; j < this.vPlayers.length; j++) {
          this.vDynamicContest[i].pl.splice(j, 1, this.vPlayers[j]);
        }
      }
      for (j = 0; j < this.vPlayers.length; j++) {
        this.vDynamicPlayers.splice(j, 1, this.vPlayers[j]);
      }
    }
  })

This is what I'm trying to print which shows nothing:

<div v-for="challenge in vDynamicContest">
  <b>Challenge: @</b>
  <span>Players:</span> 
  <span v-for="player in challenge.pl">
    @
  </span>
</div>

When I change vDynamicContest to vContest It works fine:

Challenge: CH1 Players: p1 p2 p3 p4

Challenge: CH2 Players: p1 p2 p3 p4

Challenge: CH3 Players: p1 p2 p3 p4

And there's no problem printing the dynamic array:

<div v-for="player in vDynamicPlayers">
  <b>Player: @</b>
</div>

Please help!

I was modifying the arrays with the push method but on this site https://vuejs.org/2016/02/06/common-gotchas/ they explained vue doesn't pick up the array changes that way, so I'm using splice as they recommend but I still can't show the multi array values.



via somezombie

How to use ajax with Laravel ?

Guys i have made a blog using Laravel framework, today I just heard about ajax, What I heard is in short: it loads data quickly. My issue is that I have many routes , controllers with views.

What steps do i need to use so called ajax javascript?



via Mansoor Ahmad

I won't get value in array or object in laravel

I already get data like this Using laravel query builder

[0]
    Category_id:1,
    product:food
[1]
    Category_id=1
    product:fish
[2]
   Category_id=1
   product:vegetable

But I want this formate

category_id 1{
          product
                { "Food","Fish","Vegetable"}

}



via Shahnaouz Razu Sharif

Redirect After Login for each role create with Shinobi Package Laravel

i have a question, i want to redirect users to diferent pages after login based in the role, if is admin redirect to admin/users if is normal redirect to admin/norma for example i have the next files

LoginController.php

    <?php

     namespace App\Admin\Http\Controllers\Auth;

     use App\Admin\Http\Controllers\Controller;
     use Illuminate\Foundation\Auth\AuthenticatesUsers;
     use Illuminate\Http\Request;

     class LoginController extends Controller
     {
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */

protected $redirectTo = 'admin/users';

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

/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function validateLogin(Request $request)
{

    $this->validate($request, [
        $this->username() => 'required', 'password' => 'required', //'g-recaptcha-response' => 'required|recaptcha',
    ]);
}

}

And i use Laravel 5.3 and the Shinobi Package for roles and permissions https://github.com/caffeinated/shinobi

I already create 4 roles in the system database table roles - Administrador/Free/Gold/Diamond

I thinks is something how this

    if($user->rol = 'Administrador){
       protected $redirectTo = 'admin/users';
    }else{
       protected $redirectTo = 'admin/normal';
    }

But i dont know how exactly make to work, thanks for all.



via Alan Cordova

laravel 5.4 form dropdown from database

I want to fetch drop down option value & name from database, to do that my controller code is

 $roles = Role::pluck('role','user_id');
 return view('users.add_role',compact('roles'));

to fetch this data from drop down list my view file code is

<select name="role" class="form-control" >
          @foreach($roles as $role)
            <option value=" ">  </option>
          @endforeach
</select>

but it says error

Trying to get property of non-object (View: C:\xampp\htdocs\auth2\resources\views\users\add_role.blade.php)

if i just only use

<select name="role" class="form-control" >
      @foreach($roles as $role)
        <option value=" ">  </option>
      @endforeach
</select>

then it shows role column of the table, but it not pass option value to database. so what is the correct way to generate option value & name from database?



via Masum

Laravel Form Validation on POST request

I have a form which is divided into 2 parts. The first part of the form is displayed with "GET" request when the user clicks a button. when the user fills this form and clicks next, the page is redirected to the next part of the form with a "POST" request which first saves the form and then displays the next part. The problem is when i try to validate the 2nd part of the form, laravel gives and error saying method not allowed.

my first controller:

public function create(Request $request)
{

    $validator = Validator::make($request->all(), [
        'unit_code' => 'max:25',
        'unit_title' => 'max:255',
        'project_title' => 'max:255',
        'project_ref_number' => 'max:255',
        'storage_location' => 'required|max:255',
        'keeper_name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect()->back()
                    ->withErrors($validator)
                    ->withInput();
    }

    $notification = Notification::create([
        'unit_code'         =>$request->unit_code,
        'unit_title'        =>$request->unit_title,
        'project_title'     =>$request->project_title,
        'project_ref_number'=>$request->project_ref_number,
        'storage_location'  =>$request->storage_location,
        'keeper_name'       =>$request->keeper_name,
        'user_id'           =>Auth::user()->id
        ]);

    return view('Notification.notification_for_lmo')->with('notification', $notification);
    //return redirect()->route('show.material_List')->with('notification'); 

}

routes:

/*route to personal information form for notification*/
    Route::get('/personal_information_notification_form', 'HomeController@getNotificationForm');

    /*submit personal information and go to next part of the form*/
    Route::post('personal_information_notification_form/submit/', 'NotificationController@create')->name('submit.personal_info_for_notification');

    /*route to material list form for notification application*/
    Route::get('personal_information_notification_form/material_list/', 'NotificationController@showMaterialListForm')->name('show.material_List');

    /*submit the material list*/
    Route::post('/personal_information_notification_form/add_lmo/', 'NotificationTypeAController@create')->name('submit.add_lmo');

2nd controller:

public function create(Request $request)
{
    /*this loop is because im adding rows dynamically to the table*/
    $count = count($request->input('item_name'));

    for ($i=0; $i<$count; $i++){

        $validator = Validator::make($request->all(), [
            'material_type' => 'required|max:25',
            'item_name' => 'required|max:255',
            'risk_level' => 'required|max:255',
            'quantity' => 'required|max:255',
            'volume' => 'required|max:255',
            'notification_id' => 'required|max:255',
        ]);

    }

    if ($validator->fails()) {
        return view('Notification.notification_for_lmo')->withErrors($validator)->withInput();
    }

    for ($i=0; $i<$count; $i++){

        $data  = NotificationTypeA::create([
            'material_type'  =>$request->material_type[$i],
            'item_name'      =>$request->item_name[$i],
            'risk_level'     =>$request->risk_level[$i],
            'quantity'       =>$request->quantity[$i],
            'volume'         =>$request->volume[$i],
            'notification_id'=>$request->notification_id
        ]);
    }



        $admin = Admin::find(1);
        $user = Auth::user();
        $notification = Notification::find($request->notification_id);
        $admin->notify(new NewNotificationApplicationSubmitted($user->name, $notification->id));

        return redirect()->route('show.go_to_notification')->with('message', 'We have notified '.$user->name.' that he/she is added to SSBC')->with('status', 'info');

    }

In the second controller, there is a for loop because the user fills the data in a table form. (the blade file is big so i am not posting it here.)

What is the problem with this and why is this happening?

first blade:

<div class="well">
                    <form class="form-horizontal" role="form" method="POST" action="">
                        

                        <fieldset>
                            <legend>
                                SECTION 1 - Personal Details
                            </legend>
                            <div class="row">
                                <div class="col-xs-12">

                                    <div class="form-group">
                                        <div class="col-xs-12">
                                            {!! Form::label('unit_code', 'Unit Code (if teaching):', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('unit_code', $value = null, ['class' => 'form-control']) !!}
                                        </div>
                                        <div class="col-xs-12">
                                            {!! Form::label('unit_title', 'Unit Title (if teaching):', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('unit_title', $value = null, ['class' => 'form-control']) !!}
                                        </div>
                                        <div class="col-xs-12">
                                            {!! Form::label('project_title', 'Project Title (if FYP/research):', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('project_title', $value = null, ['class' => 'form-control']) !!}
                                        </div>
                                        <div class="col-xs-12">
                                            {!! Form::label('project_ref_number', 'Ref. No (if FYP/research):', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('project_ref_number', $value = null, ['class' => 'form-control']) !!}
                                        </div>
                                        <div class="col-xs-12">
                                            {!! Form::label('storage_location', 'Storage Location:', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('storage_location', $value = null, ['class' => 'form-control' ]) !!}
                                        </div>
                                        <div class="col-xs-12">
                                            {!! Form::label('keeper_name', 'Name of the Keeper:', ['class' => 'control-label']) !!} <br>
                                            {!! Form::text('keeper_name', $value = null, ['class' => 'form-control' ]) !!}
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </fieldset>
                        <div class="row">
                            <div class="form-group">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-primary btn-block">Next</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

2nd blade:

<form class="form-horizontal" role="form" method="POST" action="">
                        

                        <fieldset>
                            <div class="row">
                                <div class="col-xs-12">
                                    <div class="row">
                                        <legend>
                                            SECTION 2 – Details of the Biohazardous Materials
                                        </legend>
                                        <div class="col-xs-8">
                                            <h4>List of Living Modified Organism (LMO)</h4>
                                        </div>
                                        <div class="col-xs-4">
                                            <input type="checkbox"/>Applicable
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <div id="LMOtablediv">
                                                <input type="button" id="addmoreLMObutton" value="Add" onclick="insRow(event)" />
                                                <table id="addLMOtable" border="1">
                                                    <thead>
                                                        <tr>
                                                            <td>No.</td>
                                                            <td>Notification ID</td>
                                                            <td>Material Type</td>
                                                            <td>Name</td>
                                                            <td>Risk Level</td>
                                                            <td>Quantity</td>
                                                            <td>Volume</td>

                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>1</td>
                                                            <td><input type="text" name="notification_id" id="notification_id" value=""></td>
                                                            <td>{!! Form::text('material_type[]', null, array('id'=>'material_type'))!!}</td>
                                                            <td>{!! Form::text('item_name[]', null, array('id'=>'item_name'))!!}</td>
                                                            <td>{!! Form::text('risk_level[]', null, array('id'=>'risk_level'))!!}</td>
                                                            <td>{!! Form::number('quantity[]', null, array('id'=>'quantity'))!!}</td>
                                                            <td>{!! Form::number('volume[]', null, array('id'=>'volume'))!!}</td>

                                                            <td><input type="button" id="delLMObutton" value="Delete" onclick="deleteRow(this)"/></td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>

                        <div class="row">
                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-10">
                                    <button type="submit" class="btn btn-primary">Submit</button>
                                </div>
                            </div>
                        </div>
                    </form>



via Mill3r

get an error that says, "No query results for model [App/dummy]"?

What I am trying to do is be able to post comments from a form to the post. I know the names for my models are bad. It should have been called post instead of dummy. I got this error when I called my new controller I made for the comments table. Also, I created a new function in the dummy model so my code can be more clean and organized. I was able to post comments before I made the new function in the dummy model and before I called a different controller. Here are the files that I think the errors is in:

Here is the route:

Route::post('post/{post}/comments', 'commentController@store');

Here is the dummy model which should have been called post and has the new function i created for it to make the code shorter in the commentController file:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class dummy extends Model
{
    protected $guarded = [];

    public function comments(){
      return $this->hasMany(Comments::class, 'post_id');
    }

    public function addComment($body){
      $this->comments()->create(compact('body')); 
    }
}

Lastly here is the commentController file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; //this one is for sql builders
use App\Dummy;
use App\Comments;
use Illuminate\Http\RedirectResponse;
use DateTime; //to create a new date object yo need to include this namespace



class commentController extends Controller
{
  public function store(Dummy $post){
    $date = new DateTime();
    $timestamp = $date->getTimestamp();
    $id = $post->id;

    $post->addComment(request('body'));

    return view('post', compact('post', 'timestamp', 'id'));
  }
}



via Lami

Validating forms on laravel

Hi i getting this error When I try to validate a form, with this

$this->validate($request, [
    'documento' => 'required|unique:cliente|max:55',
]);

htmlentities() expects parameter 1 to be string, array given (View: C:\sisVentas\resources\views\ventas\cliente\create.blade.php)

this is my view please help.

@extends ('layouts.admin')
@section ('contenido')
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <h3>Nuevo Cliente</h3>
            @if (count($errors)>0)
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li></li>
                        @endforeach
                    </ul>
                </div>
            @endif
        </div>
        {!!Form::open(array('url'=>'ventas/cliente','method'=>'POST','autocomplete'=>'off', 'files'=>'true'))!!}
        
        <div class="row">
            <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                <div class="form-group">
                    <label for="empresa">Empresa</label>
                    <input type="text" name="empresa" value="" class="form-control"
                           placeholder="Empresa...">
                </div>
            </div>
            <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                <div class="form-group">
                    <label for="contacto">Direccion</label>
                    <input type="text" name="direccion" value="" class="form-control"
                           placeholder="Direccion...">
                </div>
            </div>

            <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                <div class="form-group">
                    <label>Tipo Documento</label>
                    <select name="tipo_documento" class="form-control">
                        <option value="J">J</option>
                        <option value="G">G</option>
                        <option value="V">V</option>
                        <option value="E">E</option>
                    </select>
                </div>
            </div>
            <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                <div class="form-group">
                    <label for="Numero de documento">Numero de Documento</label>
                    <input type="text" name="documento" id="documento" required value=""
                           onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control"
                           placeholder="Numero de Documento...">
                </div>
            </div>
            <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                <div class="form-group">
                    <label for="razon_social">Razon Social</label>
                    <input type="text" name="razon_social" value="" class="form-control"
                           placeholder="Razon social...">
                </div>
            </div>
        </div>
        <div class="row">
            <div class="panel panel-primary">
                <div class="panel-body">
                    <div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
                        <div class="form-group">
                            <label for="nombre">Nombre</label>
                            <input type="text" name="pnombre" id="pnombre" class="form-control" placeholder="Nombre...">
                        </div>
                    </div>
                    <div class="col-lg-5 col-sm-5 col-md-5 col-xs-12">
                        <div class="form-group">
                            <label for="telefonos">Telefonos</label>
                            <input type="text" name="ptelefono" id="ptelefono" class="form-control"
                                   value="" placeholder="Telefonos...">
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
                        <div class="form-group">
                            <label for="correo">Correo</label>
                            <input type="text" name="pcorreo" id="pcorreo" class="form-control"
                                   value="" placeholder="correo...">
                        </div>
                    </div>

                    <div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
                        <div class="form-group">
                            <button type="button" id="bt_add" class="btn btn-primary">Agregar</button>
                        </div>
                    </div>

                    <div class="col-lg-8 col-sm-8 col-md-8 col-xs-12">
                        <table id="detalles" class="table table-striped table-bordered table-condensed">
                            <thead style="background-color: #ccc">
                            <th>Opciones</th>
                            <th>Nombre</th>
                            <th>Contacto</th>
                            <th>Correo</th>
                            </thead>
                            <tfoot>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            </tfoot>
                            <tbody>

                            </tbody>
                        </table>
                        <div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
                            <div class="form-group">
                                <button class="btn btn-primary" id="guardar" type="submit">Guardar</button>
                                <button class="btn btn-danger" type="reset">Cancelar</button>
                            </div>
                        </div>
                    </div>

                {!!Form::close() !!}
                @push ('scripts') <!-- Trabajar con el script definido en el layout-->
                    <script>
                        //////////
                        $('#guardar').hide();

                        $(document).ready(function () {
                            $('#bt_add').click(function () {
                                agregar();
                            });
                        });
                        var cont = 0;
                        var total = 0;
                        subtotal = [];


                        function agregar() {
                            nombre = $('#pnombre').val();
                            telefono = $('#ptelefono').val();
                            correo = $('#pcorreo').val();
                            if (nombre != "" && telefono != "") {

                                total = total + subtotal[cont];
                                var fila = '<tr class="selected" id="fila' + cont + '"><td><button type="button" class="btn btn-warning" onclick="eliminar(' + cont + ')" >X</button></td><td><input type="text" name="nombre[]" value="' + nombre + '"</td><td><input type="text" name="telefono[]" value="' + telefono + '"</td><td><input type="text" name="correo[]" value="' + correo + '"</td></tr>';
                                cont++;
                                limpiar();
                                $('#detalles').append(fila);
                                $('#guardar').show();
                            } else {
                                alert("Error al ingresar los detalles del contacto, revise los datos del contacto ");
                            }


                        }
                        function limpiar() {
                            $('#pnombre').val("");
                            $('#ptelefono').val("");
                            $('#pcorreo').val("");


                        }

                        function eliminar(index) {
                            $("#fila" + index).remove();
                            evaluar();
                        }


                    </script>
    @endpush

@endsection

and this is my controller

<?php

namespace sisVentas\Http\Controllers;

use Illuminate\Http\Request;
use sisVentas\Http\Requests;
use sisVentas\Persona;
use sisVentas\Contacto;
use Response;
use sisVentas\Evento;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use sisVentas\Http\Requests\PersonaFormRequest;
use DB;

class ClienteController extends Controller
{

 public function __construct()
    {
$this->middleware('auth');
    }
    public function index(Request $request)
    {
        if ($request)
        {
            $query=trim($request->get('searchText'));
            $clientes=DB::table('cliente')
            ->where ('empresa','LIKE','%'.$query.'%')
            ->orwhere ('tipo_documento','LIKE','%'.$query.'%')
            ->orwhere ('documento','LIKE','%'.$query.'%')
            ->orwhere ('direccion','LIKE','%'.$query.'%')
            ->orwhere ('razon_social','LIKE','%'.$query.'%')
            ->orderBy('codigo_cliente','desc')
            ->paginate(7);
            return view('ventas.cliente.index',["clientes"=>$clientes,"searchText"=>$query]);
        }
    }
    public function create()
    {
        return view("ventas.cliente.create");
    }
    public function store (Request $request)

{
        $this->validate($request, [
    'documento' => 'required|unique:cliente|max:55',

]);


     try {

            DB::beginTransaction();
        $persona=new Persona;
        $persona->tipo_documento=$request->get('tipo_documento');
        $persona->documento=$request->get('documento');
        $persona->empresa=$request->get('empresa');
        $persona->direccion=$request->get('direccion');
        $persona->razon_social=$request->get('razon_social');
        $persona->save();
        $id = $persona->codigo_cliente;
        $evento=new Evento;
        $user = Auth::id();
        $evento->cod_usuario=$user;
        $evento->tabla='Cliente';
        $evento->accion='Nuevo Ingreso';
        $evento->codigo_referencia=$id;
        $mytime = Carbon::now(' America/Caracas');
        $evento->fecha =$mytime->toDateTimeString();
        $evento->save();
            $nombre=$request->get('nombre');
            $telefono = $request->get('telefono');
            $correo = $request->get('correo');
          $cont = 0;
             while ($cont < count($nombre)) {
                # code...
                $detalle = new Contacto();
                $detalle->idempresa=$id;
                $detalle->nombre=$nombre[$cont];
                $detalle->telefono=$telefono[$cont];
                $detalle->correo=$correo[$cont];
                $detalle->save();
                $cont=$cont+1;
          }
            DB::commit();
         } catch (\Exception $e) {
            DB::rollback(); 
        }
        return Redirect::to('ventas/cliente/create');




}



    public function show($id)
    {
        return view("ventas.cliente.show",["persona"=>Persona::findOrFail($id)]);
    }
    public function edit($id)
    {
        return view("ventas.cliente.edit",["persona"=>Persona::findOrFail($id)]);
    }
    public function update(PersonaFormRequest $request,$id)
    {
        $persona=Persona::findOrFail($id);
        $persona->tipo_documento=$request->get('tipo_documento');
        $persona->documento=$request->get('documento');
        $persona->empresa=$request->get('empresa');
        $persona->direccion=$request->get('direccion');
        $persona->razon_social=$request->get('razon_social');
        $persona->update();
        $evento=new Evento;
        $user = Auth::id();
        $evento->cod_usuario=$user;
        $evento->tabla='Cliente';
        $evento->accion='Modificacion';
        $evento->codigo_referencia=$id;
        $mytime = Carbon::now(' America/Caracas');
        $evento->fecha =$mytime->toDateTimeString();
        $evento->save();

        return Redirect::to('ventas/cliente');
    }
    public function destroy($id)
    {
       $persona=Persona::findOrFail($id);
       $clientes = DB::table('cliente')->where('codigo_cliente', '=', $id)->delete();
        $persona->update();
         $evento=new Evento;
        $user = Auth::id();
        $evento->cod_usuario=$user;
        $evento->tabla='Cliente';
        $evento->accion='Eliminar';
        $evento->codigo_referencia=$id;
        $mytime = Carbon::now(' America/Caracas');
        $evento->fecha =$mytime->toDateTimeString();
        $evento->save();
        return Redirect::to('ventas/cliente');
    }
}



via Jorge Ortiz

Laravel Collective Form and Custom Bootstrap component

I have this submit button in my view,using Laravel Collective package:

{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}

and as you can see it add a Bootstrap class and create a button.

Now my purpose is to create a custom button like this:

<button type="button" class="btn btn-default btn-lg">
    <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Star
</button>

that has a span to keep the glyphicon. How could I do that?



via Stefano Maglione

Memory exhaused in Laravel unit tests

I wrote unit tests for my controller. My class is

class ApiControllerTest extends TestCase

and it contains test methods like this

public function testAgeDistribution()
    {
        $response = $this->action(...,
            ['datasetName'=>'AgeDistribution',
              'min_longitude'=>-80.60, 'max_longitude'=>-78.60,
                'min_latitude'=>43.20, 'max_latitude'=>44,
                'zoom'=>12
                ]);



        $this->assertResponseOk();

        $json = json_decode($response->content());

        $this->checkMainThings($json, 'AgeDistribution', 'Population', 7, 100, 7);
    }

All methods are similar but with different parameters and checks.

In the beginning of handler function I have a row

$start_memory = memory_get_usage();

And I see (in debugger) that each new test it has more and more memory used.

In other words, memory is not freed between tests.

How to free memory in PHP or what potential error I have in tested methods?



via Dims

Show an alert from hour X to hour Y

Hi I want to show an alert from hour X to hour Y

I have:

$currhour = date('H')

    if($currhour > 18 || $currhour < 22)
       return 'yes alert';
    else
       return 'no alert';

Assuming the $currhour is equal to 11. Here is a problem beacause I want to show this alert only if the currhour is on the interval 18 - 22. Another case is when the interval 18 - 9 (the next day).. here will work well because 11 it's < than 18 and 11 it's > than 9..

How can I solve all of the case?



via Argift65

is there a way to include a blade template instead of plain html using phpwkhtmltopdf?

I am using phpwkhtmltopdf package to convert my html to PDF. how can i convert .blade.php to pdf?

i tried this

$pdf = new Pdf;
$pdf->addPage('temp');
$pdf->saveAs('test2.pdf');

but it does't work and give me the following error :

QSslSocket: cannot resolve SSLv3_client_method QSslSocket: cannot resolve SSLv3_server_method Error: Failed loading page http:///var/www/html/project/views/temp (sometimes it will work just to ignore this error with --load-error-handling ignore) Exit with code 1 due to network error: HostNotFoundError



via wahdan

How to secure API endpoints without user authentication

I am creating a SPA using angular2 & lumen 5.4. Lets just say there are two routes. One GET route that returns JSON data to display, and one POST route for uploading files to the database. Its an in-house app that will have no login (this is out of my hands).

How can I properly secure the endpoints? For the POST upload form I could include a hidden token but that isn't secure at all. All of the authentication tutorials for lumen involve user login which is not an option for me.

Any examples or tutorials would really help since I have always used user authentication in the past



via ghan

Broken Laravel after performing optimization commands

I got some problem loading a class from a package so i try to run -as suggested by a lot of user- these commands in order to make my class searchable by my files:

php artisan optimize
php artisan config:cache 
php artisan route:cache

Last one command give me back this error as output:

[LogicException]
Unable to prepare route [/] for serialization. Uses Closure.

After this i run again my site and ive got this lovely mex:

Whoops, looks like something went wrong.

And i cant even browse my site now! what happend? How can I fix it?



via JahStation

Select rows with timestamp of difference of 1 Hour or more

I have a table in a database and I want to fetch records from it but with a little complex condition.

Every 30 minutes, three records are added into the table. Now I want to retrieve the records but those with one hour difference. So basically, if 3 records are added at 1 PM and then 3 are added at 1:30 PM and then another 3 at 2PM, I want to be able to fetch the records added at 1PM and 2PM but leave out 1:30PM.

I would give my code that but I am using Laravel basically and I think not everybody would be able to understand Eloquent, the query builder Laravel uses.

P.S:

public function hours24()
{
    $data = new Main();
    $temp = $data->order_by('updated_at', 'desc')->first();
    $time = strtotime($data->updated_at);
    $data = $data->where('updated_at', '>=', date('Y-m-d H:i', strtotime('-1 day')))->where('updated_at', '>=', $time + 3600)->get();
}

The problem with above is I am adding 3600 seconds everytime to $time which is a fixed time and so it will only work for the first row since after that each row would techincally be more than an hour apart. There seems no way to increase 3600 for each row.



via Henry Spike

Laravel online exam application user interface

I have setup a back end environment for online exam application(it is like class marker

) Now i am really confused about how to handle the graphical user interface. how should i display questions. when to use ajax. also heard about step forms? how to display answers after he has taken exam. How to prevent the user to go back to that test page by clicking back button? Doing all this with security to be the top priority. Please help



via Ahmed Khan

Ambiguity in question mark for regex and prepared statement placeholder of Laravel 5.1

Working in Laravel 5.1 I need to get the data for this query :

$query = "top";
$data['rawQuery'] = "category_names REGEXP '(?<![a-zA-Z])".'{?}'.'((es)?|(s?))(?![a-zA-Z])';
 $data['bindParams'] =  [$query];
 $result = DB::table($this->table)
                    ->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
                    ->select($selectedColumns)
                    ->get();

I am unable to put my bind param to proper position which should be like this:

 select * from product_categories where category_names REGEXP '(?<![a-zA-Z])top((es)?|(s?))(?![a-zA-Z])

Whereas I am getting this:

select * from product_categories where category_names REGEXP '(tops<![a-zA-Z]){?}((es)?|(s?))(?![a-zA-Z])

The difference is that , my query value is setting to wrong place. Please show some light on this .



via subhajit

Collapse two collections to one in laravel

I need help with collapse my collections. Its my code

public function showFriends(){
            $request1 = DB::table('friends_users')
                ->join('users', 'users.id', '=', 'friends_users.user_id')
                ->where([['friend_id', '=',Auth::user()->id],['accepted', '=',true]])
                ->orWhere([['user_id','=',Auth::user()->id],['accepted','= ',true]])
                ->get();

                $request2 = DB::table('friends_users')
                ->join('users', 'users.id', '=', 'friends_users.friend_id')
                    ->where([['user_id','=',Auth::user()->id] , ['accepted','=',true]])
                    ->get();

                    $all = collect($request1,$request2)->collapse();
        return $all;

    }

Problem is in $all variable because it return empty collection. Thank you for help.



via kacper1230

Route with dot (IP address) not found, returns 404

I use Lumen 5.4.

This is how my route is setup:

$app->get('/ip/{ip}', GeoIpController::class . '@show');

The {ip} route parameter should be an IP address, with dots in it. However, it seems there is a problem when a route has dots in it. It returns a 404 not found error.

I am aware I could pass the IP address in as a simple GET request parameter, but want the IP to be part of the URL and to be handled like a route parameter.

For testing purposes, I use php -S localhost:8080 -t public to serve the application.



via wujt

Show warning from hour to another hour in PHP/ Laravel

I want to show a warning from an hour to another..

Here is what i've tried

$currentHour = date('H');
if ($currentHour >= 18 || $currentHour < 5) {
            echo 'warning <br>';
        }else{
            echo 'no warning';
        }

But I have the next problem. I want to show this warning from 18 to 5 in the morning..

If my current hour is 16

16 >= 18 => false
16 < 5 => false

How can I resolve this problem...? I want to show this message from 18 to 5 morning



via ypfmclartyo

Laravel Eloquent - how to sort by sub array values

Hello I have the following Eloquent query

$usersSessions = User::with('tracker_sessions')
                   ->whereHas('tracker_sessions', function($q){
                      $q->where('created_at','>=', Carbon::now()>subDays('7'));
                    })
                    ->with('tracker_geoip')->get()->all();

which returns the following structure :

draw: null,
  recordsTotal: 5,
  recordsFiltered: 5,
  data: [{
      id: 164,
      name: "Test User",
      first_name: "Test",
      last_name: "User",
      email: "test_user@gmail.com",
      tracker_sessions: [{
          id: 156,
          uuid: "abea7a1a-84ee-48ab-a2e9-35365e8f57e3",
          user_id: 164,
          device_id: 1,
          agent_id: 7,
          client_ip: "127.0.0.1",
          referer_id: 11,
          cookie_id: null,
          geoip_id: null,
          is_robot: 0,
          created_at: "2017-05-22 16:08:24",
          updated_at: "2017-05-22 09:08:24",
          language_id: 1
        },
        {
          id: 155,
          uuid: "61e27c18-4eb9-4d27-954a-836a4e9d1b04",
          user_id: 164,
          device_id: 1,
          agent_id: 7,
          client_ip: "127.0.0.1",
          referer_id: null,
          cookie_id: null,
          geoip_id: null,
          is_robot: 0,
          created_at: "2017-05-22 16:08:23",
          updated_at: "2017-05-22 09:08:23",
          language_id: 1
        }
      ],
      tracker_geoip: [{
        id: 1,
        country_code: "BG",
        country_code3: null,
        country_name: "Bulgaria",
        region: "EU",
        city: "Sofia",
        postal_code: "1000",
        area_code: null,
        dma_code: null,
        metro_code: null,
        continent_code: "EU",
        created_at: "2016-12-22 16:22:30",
        updated_at: "-0001-11-30 00:00:00",
        pivot: {
          user_id: 164,
          geoip_id: 1
        }
      }]

So the question is : “How can I sort the users by their latest tracker_sessions ?”

I tried to join the tracker_sessions table , but it didn't work .



via user3102290

How to update data from database in a view?

Using laravel 5.2. I am printing currency values from database in a view:

<div class="hidden">
@foreach ($currencies as $currency)
    <div class="currency-">
        <div class="cur-id"></div>
        <div class="cur-name"></div>
        <div class="cur-sell"></div>
        <div class="cur-buy"></div>
        <div class="cur-reserve"></div>
        <div class="cur-short"></div>
        <div class="cur-wallet"></div>
    </div>
@endforeach
</div>
@endsection

Code above lists all currencies from database with its fields. Question is - how can i update these values without page reload with Ajax? I need to make a GET request with ajax then replace data with actual one.



via Alexander Kim

Cannot POST /oauth/token

I'm having this error trying to log in with an existing user using Laravel Passport and vue.js. But when I log in it gives a 404 Uncaught (in promise) error. When I look at network it says "Cannot POST /oauth/token"

This is my login.vue script

import {localhost} from '../../config'
  export default {
    name: 'logIn',
    data () {
      return {
        email: 'elector_user@arteveldehs.be',
        password: 'elector_password'
      }
    },
    methods: {
      handleLoginFormSubmit () {
        const data = {
          client_id: 2,
          client_secret: 'PAzgzdNUY65z0xWRXobb0TnA7DHYHNtNwIgVykpl',
          grant_type: 'password',
          username: this.email,
          password: this.password
        }
        this.$http.post(localhost + '/oauth/token', data)
          .then(response => {
            console.log(response)
          })
      }
    }
  }

This is my Kernel.php

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Barryvdh\Cors\HandleCors::class


    ];

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            //\App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',

        ],
    ];
protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

This is my RouteServiceProvidor.php

public function map(Router $router)
    {
        Passport::routes();

        $this->mapWebRoutes($router);
        $this->mapApiRoutes($router);

    }

protected function mapApiRoutes(Router $router)
    {
        $router->group([
            'middleware' => ['api'],
            'namespace' => $this->namespace,
        ], function ($router){
            require  app_path('Http/routes.php');
        });
    }

this is my app.php

Laravel\Passport\PassportServiceProvider::class,
        Laravel\Tinker\TinkerServiceProvider::class,



via hxwtch

Advertisement