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

Advertisement