vendredi 30 septembre 2016

Laravel 5 - Compile String and Interpolate Using Blade API on Server

Using the Blade service container I want to take a string with markers in it and compile it down so it can be added to the blade template, and further interpolated.

So I have an email string (abridge for brevity) on the server retrieved from the database of:

<p>Welcome ,</p>

And I want it to interpolated to

<p>Welcome Joe,</p> 

So I can send it to a Blade template as $content and have it render all the content and markup since Blade doesn't interpolate twice and right now our templates are client made and stored in the database.

Blade::compileString(value) produces <p>Welcome <?php echo e($first_name); ?>,</p>, but I can't figure out how to get $first_name to resolve to Joe in the string using the Blade API, and it doesn't do it within the Blade template later. It just displays it in the email as a string with PHP delimiters like:

<p>Welcome <?php echo e($first_name); ?>,</p>

Any suggestions?



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

Unable to get an array from register form Laravel 5.3

I'm using Laravel 5.3 auth:make registration form, I have a multiple select in my form, which returns the count of the selected rows instead of array with the values.

Thats what coming back when I dd($data):

 array:10 [▼
      "_token" => "mBTBYC4yHsI0Ph1Hmj7p6MSstOCRM3cDkCoSZH4b"
      "first_name" => "User"
      "last_name" => "Family"
      "class" => "Software Engineer"
      "year" => "0"
      "tags" => "1" -> that should be an array.
      "phone" => "55555555"
      "email" => "test@test.com"
      "password" => "123123"
      "password_confirmation" => "123123"
    ]

The are I would like to fix looks like this in the html:

<div class="form-group">
    {!! Form::select('tags[]', $tags , null , ['class' => 'form-control' , 'multiple' , 'id'=>'tags' , 'name' => 'tags']) !!}
    @if ($errors->has('tags'))
        <span class="help-block">
            <strong></strong>
        </span>
    @endif
</div>



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

Codeception POST error with Propel

I have an error where i make a POST request using codeception, and I get an sql exception saying I cant insert. But if I try the same POST request on Postman it works wonderfully. This project is using propel as an ORM. Here is my api.suite.yml file:

class_name: ApiTester modules: enabled: - \Helper\Api - Asserts - Laravel5 - Db - REST: url: http://localhost:8000/ depends: Laravel5 config: Laravel5: environment_file: .env.testing

and here is my snippet of code in question:

public function crearActividad(ApiTester $I) {
$I->wantTo('Crear un recurso actividad y verificar que lo obtenemos');
$I->amBearerAuthenticated($this->token);
$I->sendPOST($this->url, [
    'CodProceso' => 1,
    'Nombre'     => 'Actividad Nueva Nueva',
]);
$this->logResponse($I);
$this->checkResponseCode($I, HttpCode::CREATED);
$I->seeResponseIsJson();
$I->seeResponseContainsJson(array(
    'estado' => true,
    'codigo' => config('constants.ESTADOS_PROCESOS.OK'),
    'Actividades' => [[
        'CodProceso' => 1,
        'Nombre'     => 'Actividad Nueva Nueva',
     ]],
  ));
}

The error im getting is this:

Unable to execute INSERT statement [INSERT INTO app.actividad (cod_actividad, nombre, cod_pr oceso) VALUES (:p0, :p1, :p2)]



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

Laravel Blade Dyamic Interpolation of Data Sent to the Template

There is a situation in our application where we've provided clients with the ability to create their own email template, which we store in the database, but when it comes to emailing the template normally we'd just pass it down to blade with some data to fill in the blanks, but the content has blanks that needs to be interpolated as well.

Database Template from Database

$template = "<p>Welcome </p>..."

But this is coming down in the data to the blade template, so we're running a replace over all the template coming out of the database prior to sending it down to blade so blade gets:

Database Template Interpolated on Server

$template = "<p>Welcome Joe</p>..."

Is it possible to send down the $first_name and $template with the data and have the template interpolated as well as the content of the template so:

Blade Template - Multi/Dynamic Interpolation all in Blade Template Instead



Will result in:

<p>Welcome Joe</p>...

Without us doing the template interpolation separately on the server?



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

Laravel 5.3 Adding Cc to Notifications Email

I'm currently using Notifications for email instead of Mailables, since it allows for SMS, Slack, etc to be added later very easily, but you can't chain ...->cc(...) onto the emails. Looking at MailMessage and the inherited class SimpleMessage, as well as Notification. I'm a bit lost as to where the email is being fired off and if I can find a way to add the Cc attribute to it.



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

Combine Ember with Laravel

I'm new to Laravel & Ember.
And I sa some project that bulid like so:
All JavaScript Files found in laravel app/assets directiony, and also the hbs file.
When I get into the public index route its load a view with include script tags for all the files that found in the assets directiony.

So I want to know some things:

1) How I put JS and hbs files in this directiony and make them load from the broswer? cause I read that assets need to be putted in the public directiony?
2) How can I do manipulation on the hbs files ? meaning that I need to wrap the HandelBar template code in Ember.compile function?
3) If I want to use the newest version of Ember how do I write the code in client-side JS And not in ECA6 standart?
4) Which file of Ember I need to include in the view?



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

Laravel relationship through a parent

I created a model for services that are packed with modules and each modules has a price. Multiple modules create the price for that service.

- Service #1
-- Module 1 ($20)
-- Module 2 ($40)

Using belongsToMany

class Services extends Model
{
    public function modules()
    {
        return $this->belongsToMany('App\Services\Modules');
        ...

each module links to a price

class Modules extends Model
{
    public function price()
    {
        return $this->hasOne('App\Services\Pricing', 'product')->where('type', 'module');
        ...

and a service_module table that links services to modules. The problem is what kind of relationship should I create to be able to ->sum() the module prices for each service because I created an ugly patch with loops and burning 15 more queries per request

$prices = [];
foreach ($services->modules as $modules )
    $prices[] = $modules ->price['month'];
$price = number_format(collect($prices)->sum(), 2, '.', '');



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

Get relationship from notification

I've set up database notifications for my application.

In my notification class, I've added this:

/**
 * Get the array representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toArray($notifiable)
{
    return [
        'post_id' => $this->post->id,
    ];
}

Which references the id of a Post.

What I want to do is display the Post when the user views their notifications. Of course, I have a posts table, but I'm not sure how I would get the post data given the post_id from the notification array.



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

Should all controllers have only the basic CRUD methods?

In Laravel, are all controllers only supposed to have the basic CRUD methods, as shown in the link below?

http://ift.tt/2ddw44n

That is, should the only methods in a controller be:

  1. index()
  2. create()
  3. store()
  4. show()
  5. edit()
  6. update()
  7. destroy()

Thanks.



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

Trying to update status uisng laravel eloquent relationships

  public function statusUpdate($id, $status)
{

    $adminID = Admin::find($id);

    $adminID->user->status = ($status == 1 ? 0 : 1);
    $data = (['status' => ($status == 1 ? 0 : 1)]);

    $userName = $adminID->user->userName;

    $adminID->update($data);
    $adminID->save();

    session()->flash('flashMessage', $userName . ' Operation Successful');
    return redirect()->back();
}

This is my function above but the status is not updating. The Admin and User models are linked using hasMany and belongsTo relationship. it works because am able to get the status from the user table with the relationship

   $adminID->user->status

But when i click on the link to change the status it doesn't change. my link is below

    <a href="" class="label label-sm label-"></a>



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

Removing Repository Pattern from laravel

I have used a laravel CRUD Generator Infyom Laravel Generator to generate CRUD code. By default it uses Repository Pattern which is confusing for me. Is there any way to remove only Repository Pattern without affecting working app (I am developing it) ?



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

Show in view only object with specified id

i am woking on a project about a restaurant and i need to show on my staff view only the Chef and Su-Chef which has id (Chef-2, Su-Chef 4). I need to show on my view all the Chefs and all the Su-Chefs. The view is organised at the form that is the number is odd (i have the image on left and text on right), if the number is even i have (i have the image on right and text on left) Here is my Controller

public function index()
{
    $staff = Staff::where('visible','yes')->where('delete','no')->orderBy('name','DESC')->get();
    return view('staff.staff', ['staff' => $staff]);
}

And this is my View

<section class="bg-deep-yellow">
    <div class="container">
        <div class="row">
            <!-- section title -->
            <div class="col-md-12 text-center">
                <span class="title-small black-text text-uppercase letter-spacing-3 font-weight-600">I NOSTRI CHEF</span>
                <div class="separator-line-thick bg-black no-margin-bottom margin-one xs-margin-top-five"></div>
            </div>
            <!-- end section title -->
        </div>
        <div class="row margin-ten no-margin-bottom">

            <!-- chef  -->
            <div class="col-md-12 sm-margin-bottom-ten">
                <div class="col-md-5 chef-img cover-background" style="background-image:url();">
                    <div class="img-border"></div>
                </div>
                <div class="col-md-7 chef-text bg-white text-center">

                    <img src="" alt=""/><br>
                    <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Patrick Smith</span>
                    <span class="text-small text-uppercase letter-spacing-3">Chef, Co-Founder</span>
                    <p class="text-med margin-ten width-90 center-col" style="text-align: justify">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
                </div>
            </div>
            <!-- end chef  -->
            <!-- chef  -->
            <div class="col-md-12">
                <div class="col-md-7 chef-text bg-white text-center">

                    <img src="" alt=""/><br>
                    <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Sancho Pansa</span>
                    <span class="text-small text-uppercase letter-spacing-3">Bartender</span>
                    <p class="text-med margin-ten width-90 center-col" style="text-align: justify" >Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

                </div>
                <div class="col-md-5 chef-img cover-background" style="background-image:url();">
                    <div class="img-border"></div>
                </div>
            </div>
            <!-- end chef  -->
        </div>
    </div>
</section>



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

issue loading CSS and JS files in Laravel

I'm having a strange issue in my Laravel 5.2 app. Specifically with loading some CSS and JS files. I have this in the folder public/assets so, I have something like this:

|--public
|----/assets
|-------/css
|------------/auth
|---------------login.css
|----------main.css
|-------/js
|---------email.js
|---------/modules
|------------faq.js

That is my directory, so I'm loading the CSS with:

    <link href="" rel="stylesheet" type="text/css" />
    <link href="" rel="stylesheet" type="text/css" />

And the Javascript files with:

<script src="" type="text/javascript"></script>
<script src="" type="text/javascript"></script>

Also I'm loading another files as well but I'm explaining the basic situation. So, the thing is that the load of login.css and faq.js are giving me 404 error but the other files are loaded correctly, I even checked open the files through the absolute paths and they're loaded fine, also I made chown to www-data of the public folder but nothing works, so I don't know why a 404 error is triggered. What else should I check?

In the console of the browser the links that are loaded are: http://mydomain/assets/js/modules/faq.js http://mydomain/assets/css/auth/login.css

But they give 404 error, and the other files doesn't



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

Laravel controller return to route

I'm running a query within my controller which returns a callback url I would like to set this url to be my home controller so I can work with the data thats returned on the callback.

$loginUrl = $helper->getLoginUrl('http://myapp.app/home', $permissions);

I would like this url to be the controller of my route, currently this path returns the correct data in the url however I get the following error -

Cross-site request forgery validation failed. The "state" param from the URL and session do not match.

Is there a way to return the url back without getting a CSRF error.



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

Call to a member function all() on string Laravel 5

i do sql

        $array_symbols_id = DB::table('symbol')
        ->whereIn('symbol_name', $array_symbols)
        ->pluck('symbol_id')
        ->all();
        print_r($array_symbols_id);

and throw exception

FatalErrorException in CompgenGetter.php line 54:
Call to a member function all() on string

in my array_symbols Array ( [0] => A [1] => S [2] => D [3] => F [4] => S [5] => A )



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

Can't update data with foreign key enabled in laravel

I can't update data with foreign key enabled in laravel. I found nothing onUpdate('cascade') in laravel documentation.

$table->foreign('user_name')->references('name')->on('users')->onDelete('cascade');

How do I update/edit any information which constrained with foreign key?



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

Laravel Undefined variable

I'm having a problem right now I can't display my likes in my view page. This is the line (like_counter) i want to show on my view blade but once I call it i get undefined variable like_counter.

    public function getLikeCounter($post_id) {
    $post = Post::find($post_id);
    $number = null;
    $like_counter = \DB::table('likes')->where('post_id', $post->id)->where('like',!$number)->count();
    return View::make('layouts.viewvideo', ['like_counter' => $like_counter]);
}

View:

<span class="badge"></span>

Routes:

Route::get('/counter/{post_id}', [
'uses' => 'PostController@getLikeCounter',
'as' => 'counter'

]);

Thank you for your help.



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

laravel 'unique' validation property not working

In my Laravel project, I have a form that receives as input name, email etc. and submits the values to a store method in my controller. I created a request to validated the submitted input before storing them in the datebase. Here are the the validation rules and custom messages:

public function rules(){
    return [
        'name' => 'required|unique:users|min:8',
        'email' => 'required|email',
    ];
}


public function messages(){
    return [
        'name.required' => 'You must enter name',
        'name.unique' => 'Sorry, that name is already taken',
        'email.required' => 'An  email address is required',
    ];
}

Ajax and every other part of the code (like the ajax, and laravel) works just fine without the unique validation proberty. But when I include the unique validation, the form does not submit but instead when I look at the developer tools I get the following error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

all_ajax.js:54 Uncaught TypeError: Cannot read property 'name' of undefined

Please what could I be doing wrong?

For the benefit of doubt let me just add the controller method



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

Vue-Multiselect with Laravel 5.3

I'm new to Laravel and Vue and need help implementing Vue-Multiselect.

I don't know how to pass the actual options to the select.

My vue file:

    <template>
    <div class="dropdown">
        <multiselect
                :selected.sync="selected"
                :show-labels="false"
                :options="options"
                :placeholder="placeholder"
                :searchable="false"
                :allow-empty="false"
                :multiple="false"
                key="name"
                label="name"
        ></multiselect>
        <label v-show="showLabel" for="multiselect"><span></span>Language</label>
    </div>
</template>

<script>
    import { Multiselect } from 'vue-multiselect';

    export default {
        components: { Multiselect },

        props: {
            options: {},
            placeholder: {
                default: 'Select one'
            },
            showLabel: {
                type: Boolean,
                default: true
            },
            selected: ''
        }
    };
</script>

My blade file:

    <div class="form-group">
    <drop-down
        :options=""
        :selected.sync="selected"
        :show-label="false"
     ></drop-down>
</div>

In my controller method I tried a few things:

1.

public function edit($id)
{
    ....
    $members_list = Member::orderBy('member_first_name')->pluck('member_first_name', member_id');
     return view('businesses.edit', compact('members_list'));
}

I got this error: [Vue warn]: Invalid prop: type check failed for prop "options". Expected Array, got Object. (found in component: )

  1. I tried:

    $members = Member::orderBy('member_first_name')->pluck('member_first_name', member_id'); $members_list = $members->all(); return view('businesses.edit', compact('members_list')); $members_list = $member->all();

I got this error: htmlspecialchars() expects parameter 1 to be string, array given (View: C:\wamp\www\ccf.local\resources\views\businesses\edit.blade.php)

So I need help with 2 things:

  1. How to send the $members_list as the options
  2. How can I combine the member_first_name and member_last_name fields so I can get options like this:

    option value="member_id" option text = member_first_name member_last_name

Thank you



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

MySQL sub query in Laravel, how to join queries and add second query's result as a new column to first query?

I have two tables:

- PRODUCTS (having: ID, NAME, PRICE)
- LIKES (having: ID, PRODID, NAME)

I would like to query the first table while counting (and returning as a new column) in a sub query all the likes the product has. How could I combine the following queries?

$products = DB::table('PRODUCTS')
                  ->get();

$likes = DB::table('LIKES')
                  ->select(DB::raw('count(*) as total'))
                  ->where('PRODID', '=', 'product id from first table')
                  ->get();

How could I achieve this using Laravel queries? Thanks!



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

Laravel image upload error

While upload image,I'm getting this error always..

/homepages/2/d647964186/htdocs/public/abserve/images/
/homepages/2/d647964186/htdocs/public/abserve/images/
backend-logo.png
/tmp/phpmuphIV
/homepages/2/d647964186/htdocs/public/abserve/images/backend-logo.png
bool(true)

But when I do the same in my local it works perfect for me..But it always showing error in live..

And also I check all the folder permission's it's perfect..

Could someone help me why this error occured!!...

Thank you,



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

Using move() function in user registration process after using make:auth Laravel 5.3

I've added a file upload (Profile picture) to the registration form which generated by the command 'make:auth' in Laravel 5.3 The problem is I get a string and not a file so I can't use the move() function to place the file where it should.

This is my form:

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

    

    {!! Form::file('profile_picture', null, ['class' => 'form-control']) !!}

    <div class="form-group">
        <input id="first_name" type="text" class="form-control" name="first_name" value="" placeholder="First name" required autofocus>
        @if ($errors->has('first_name'))
            <span class="help-block">
                <strong></strong>
            </span>
        @endif
    </div>

    <div class="form-group">
        <input id="last_name" type="text" class="form-control" name="last_name" value="" placeholder="Last name" required autofocus>
            @if ($errors->has('last_name'))
                <span class="help-block">
                    <strong></strong>
                </span>
            @endif
    </div>

    <button type="submit" class="btn btn-primary">Register</button>

</form>

This is my create user function:

protected function create(array $data)
    {
        $user = User::create([
            'email' => $data['email'],
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'password' => bcrypt($data['password']),
            'class' => $data['class'],
            'year' => $data['year'],
            'phone' => $data['phone']
        ]);
        $tags = $data['tags'];
        $user->tags()->sync($tags); //Pivot table of tags
        if($data['profile_picture']){
            $file = File::create(['name' => $data['profile_picture'] , 'user_id' => $user->id]);
            MOVE THE FILE WITH $file->move();
            $file->save();
            $user->files()->attach($file); //Pivot table of files
        }
        return $user;
    }



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

JQuery Ajax: Uncaught TypeError: Cannot read property 'name' of undefined

First of all, I know several people have encountered a bug with a similar error message and I have gone through a lot of them but didn't find one that could solve my own problem.

Using the developer tools, I could see the error messages returned. The two messages are:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

and

Uncaught TypeError: Cannot read property 'name' of undefined

I am submitting student data from this form:

  <form  method="post" id="school_registration_form">
      <input type="hidden" name="_token" value="">

      <input type="text" id="name" name="name">
      <div id="name_error"></div>

      <input type="email" id="school_email" name="school_email">
      <div id="school_email_error"></div>

      <input type="email" id="your_email" name="your_email">
      <div id="your_email_error"></div>

      <input type="text" id="phone" name="phone" >
      <div id="phone_error"></div>

      <input type="password" id="password" name="password">
      <div id="password_error"></div>

      <input type="password" id="password_confirmation" name="password_confirmation" >
      <div id="password_confirmation_error"></div>

      <div class="col-sm-offset-3 col-sm-10">
      <button type="submit" class="btn btn-success">Create Account</button>
  </div>

through this route:

Route::post('store', ['as' => 'school/store', 'uses' => 'SchoolController@store']);

to this function:

public function store(SchoolCreateUserRequest $request){

 $user = User::create([
    'name' => $request->input('name'),
    'inst_email' => $request->input('school_email'),
    'alt_email' => $request->input('your_email'),
    'phone' => $request->input('phone'),
    'password' => bcrypt($request->input('password')),
  ]);

  Auth::login($user);
}

Here are the validation rules for the form request:

public function rules(){
return [
    'name' => 'required|unique:users|min:8',
    'school_email' => 'required|email',
    'your_email' => 'required|email|unique:users',
    'phone' => 'required',
    'password' => 'required|confirmed|min:4',
    'password_confirmation' => 'required'
];

}

and finally the most important part. Here is the JQuery/Ajax code that submits values to the server:

$(function(){

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

    // when form submit button is clicked
    $('#ub_registration_form').submit(function (e) {
      e.preventDefault();

      var name = $('#name').val();
      var school_email = $('#school_email').val();
      var your_email = $('#your_email').val();
      var phone = $('#phone').val();
      var password = $('#password').val();
      var password_confirmation = $('#password_confirmation').val();
      var token = $("input[name=token]").val();
      var route = "school/store";


      $.ajax({
        url: route,
        type: 'post',
        datatype: 'json',
        data: {
          'name'  : name,
          'school_email' : school_email,
          'your_email'  : your_email,
          'phone'      : phone,
          'password'   : password,
          'password_confirmation'  : password_confirmation,
          '_token': $('meta[name="_token"]').attr('content')
        },
        success: function(msg){
          notify('Your account was successfully created.', 'success', "ub");
          logged_in_user();
        },
        error: function(data){
          var name = data.responseJSON.name;
          var school_email = data.responseJSON.school_email;
          var your_email = data.responseJSON.your_email;
          var phone = data.responseJSON.phone;
          var password = data.responseJSON.password;
          var password_confirmation = data.responseJSON.password_confirmation;

          $('#name_error').html(data.responseJSON.name);
          if (name != null && name != "") {
            $('#name').css("border", "1px solid red");
          }

          $('#school_email_error').html(data.responseJSON.school_email);
          if (school_email != null && school_email != "") {
            $('#school_email').css("border", "1px solid red");
          }


          $('#your_email_error').html(data.responseJSON.your_email);
          if (your_email != null && your_email != "") {
            $('#your_email').css("border", "1px solid red");
          }


          $('#phone_error').html(data.responseJSON.phone);
          if (phone != null && phone != "") {
            $('#phone').css("border", "1px solid red");
          }

          $('#password_error').html(data.responseJSON.password);
          if (password != null && password != "") {
            $('#password').css("border", "1px solid red");
          }

          $('#password_confirmation_error').html(data.responseJSON.password_confirmation);
          if (password_confirmation != null && password_confirmation != "") {
            $('#password_confirmation').css("border", "1px solid red");
          }
        }

      });       


    });

  });

Sorry for the lengthy code. Tried to reduce it as much as i could. Thanks for any help.



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

Display Custom Numnber Instead Of Original Number In Send Message

I have US twilio Number,I sent Message From US Number But Receiver Display My Own Indian Number.Instead Of Twilio Number. I was enable Alphanumeric Sender ID In My Twilio Account(Trial Account),If I set From Parameter with my Indian Number I getting Error. Is It Possible?



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

Running raw sql in php laravel

I am trying to call a stored procedure which I have ran in the workbench and works fine, however I am trying to call this in PHP code and it seems to return an empty array. I have tried many other methods that hang off the DB class unprepared and raw returns a boolean value. I have also tried using string concatenation to construct the query as before I was binding, although this made no difference but I thought I would try it anyway.

DB::select('call get_oids(\'' . $sysInfo . '\');');



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

Calculate Column based on another column laravel

I want to calculate amount column based on type column. and display the result in balance column. with condition if debit is sum, and if credit is minus. here is the table calculate

I'm using laravel and this is the code in view

<thead>
    <tr class="txtcenter">
        <th class="all">Date </th>
        <th class="all">Description </th>
        <th class="all">Amount</th>
        <th class="all">Type</th>
        <th class="all">Reference</th>
        <th class="all">Balance</th>
    </tr>
</thead>
<tbody>@foreach($get_period as $statement)
        <tr class="accordion">
            <td></div>
            <td> </div>
            <td>IDR   </div> 
            <td>  </div>
            <td> </div>
            <td>  </div>
        </tr>@endforeach
</tbody>

I'm newbie in laravel and don't know what code to calculate this, maybe php or javascript or anything else. please help me....... Thanks in advance



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

Single Inheritance of Controller Classes in Laravel 5.2

Hi i am trying to do single inheritance in Laravel 5.2 for Controllers.

This is my parent basecontroller class

 <?php

 namespace App\Http\Controllers\Moviesfrontend;

 use Illuminate\Http\Request;

 use App\Http\Requests;
 use App\Http\Controllers\Controller;


 class BaseController extends Controller
 {
     public function __construct($request)
     {
         //code to check whether city is set in session or not
         $selectedcity=$request->session()->get('selectedcity');

     }
 }

In BaseController class construct will fetch the city name stored in session. Now i want to access this city name stored in $selectedcity in my child class.

My child controller class is

  <?php

  namespace App\Http\Controllers\Moviesfrontend;

  use Illuminate\Http\Request;

  use App\Http\Requests;
  use App\Http\Controllers\Controller;

  class HomeController extends BaseController
  {

      public function __construct(Request $request)
      {

          parent::__construct($request);

      }

      public function index(Request $request)
      {
          echo $selectedcity;
      }
  }

Bedefault I guess parent class variables are accessible to child class but this is not working and i am getting error message that $selectedcity not found.

Kindly assist me accessing this variable in chlid class.



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

Authentication required (packagist.org) Laravel instalation

I'm using ubuntu 16.04 and trying to install laravel (any version). Actually i cloned from github the laravel project (http://ift.tt/UDctZi) After cloning I'm running the command as below

root:/var/www/html/laravel$ composer install Loading composer repositories with package information Updating dependencies (including require-dev) Authentication required (packagist.org): Username: This is the issue i'm facing, i don't know what username i have to give, and why its asking authentication.. And if i run composer diagnose the below code was coming

composer diagnose Checking composer.json: OK Checking platform settings: OK Checking git settings: OK Checking http connectivity to packagist: Authentication required (packagist.org): Username: Any suggestions or can anyone tell what was i'm missing here



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

URL to `/` within a subdomain - laravel

I use subdomain functionality in Laravel 5.3. My main app address has format http://example.com When within a subdomain such as http://dev.example.comI use same templates for header.

problem

as a result, the head of my page, which contains url to homepage, defined in blade as renders as http://dev.example.com, while desired is http://example.com

to do

is there any good practice to get make Laravel show the main domain URLs? I could add a variable in controller used for subdomain purposes, but it seems not really professional way to solve the issue.



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

Store CSV File in laravel 5

Hi Friends I am trying to store csv file in local laravel storage folder but I am getting this error Array to string conversion. please suggest me.

Controller

 $user=DB::table('users as u')
        ->join('emp as e', 'u.EmpID', '=', 'e.EmpID')
        ->select('e.DATE as Date', 'e.EmpID as EmpID', 'e.job as Work')
        ->get();
   $data = array();
    foreach ($user as $result) {
        $temp = (array)$result;  
        $temp['L'] = 'L';
        $data[] = $temp;

    }
    Storage::disk('csv')->put('users_'.date('m-d-y').'.csv',$data);

Expected Output in CSV File:

Date              EmpID       Work
25/08/16           123        House Cleaning
28/08/116          345        blahblah

Output Coming like this in CSV File:

The page is showing Array to string conversion Error:
ArrayArrayArray



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

Handle relationship 'hasMany' for form, One questions, multiple answers to edit

I'am trying to find how to handle into a 'One' form the edit of one question and the multiple answers linked to this question.

My relationship is like that :

  public function reponses() // has many answers
  {
      return $this->hasMany('App\Reponses', 'question_id', 'id');
  }

  public function reponseValide() // has many valid answers
  {
      return $this->hasMany('App\Reponses', 'question_id', 'id')->where('is_valid',1);
  }

And use $question = Questions::find($idquestion)->with('reponses')->get() To get a object of the question informations + the answers. Note, the QUESTION and REPONSES are two differents tables on the DB.



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

sum column based on another column laravel

I want to sum column AMOUNT, and the result is fill the column BALANCE. if column TYPE is DEBIT, then it will sum.. but if column TYPE is KREDIT, then it will be minus. this is the table table image

to create that table, i used this query in laravel controller :

$get_result        =  DB::select( DB::raw("SELECT statement.created_at, statement.descript, statement.amount, statement.sign, statement.reference 
                                                    FROM statement,lender 
                                                    WHERE statement.created_at BETWEEN DATE_ADD(' $date_from ',INTERVAL 1 DAY) 
                                                    AND '$date_to' 
                                                    AND statement.lender_id = lender.id 
                                                    AND lender.user_id= $userId ") );

and I used this code in view to display data :

<thead>
                                <tr class="txtcenter">
                                    <th class="all">Date </th>
                                    <th class="all">Description </th>
                                    <th class="all">Amount</th>
                                    <th class="all">Type</th>
                                    <th class="all">Reference</th>
                                    <th class="all">Balance</th>
                                </tr>
                            </thead>
                            <tbody>@foreach($get_period as $statement)
                                    <tr class="accordion">
                                        <td></div>
                                        <td> </div>
                                        <td>IDR   </div> 
                                        <td>  </div>
                                        <td> </div>
                                        <td>  </div>
                                    </tr>@endforeach
                            </tbody>

I do not know how to make the proper code to calculate it all. Please help me. Thanks in advance



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

tokenmismatchexception on uploading a large file laravel 5

I get a token mismatch error when I try uploading a large file in laravel 5. I am using the token field in my form.

TokenMismatchException in VerifyCsrfToken.php line 53:

I already tried few methods:

  1. increasing upload_max_filesize and post_max_size.
  2. changing php.ini file and restarting apache services.
  3. disabling the csrf middleware for that route, but the file is not fetched in this case !

I couldn't find anything besides these in the internet. Is there any other solution ?



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

jeudi 29 septembre 2016

laravel 5.2 session not persist on route change

laravel 5.2 session not persist after route change,

I have not used any middleware. session returns all values in controller when i put session but it forgets when redirect to another route.

here is my routes

Route::auth();

Route::get('login','LoginController@login');

Route::post('login','LoginController@check');

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

Route::post('school/store','HomeController@store');



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

"Cannot read property 'mergeConfig' of undefined" error while Installing VueJS

On Installing VueJS while running Gulp in Laravel Project, I get following:

Me-MBP:simpleb2b AdnanAhmad$ gulp build
/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir-vue/main.js:4
    Elixir.webpack.mergeConfig({
                  ^

TypeError: Cannot read property 'mergeConfig' of undefined
    at /Applications/MAMP/htdocs//myProject/node_modules/laravel-elixir-vue/main.js:4:19
    at /Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:29:16
    at Array.forEach (native)
    at global.Elixir (/Applications/MAMP/htdocs//myProject//node_modules/laravel-elixir/dist/index.js:28:24)
    at Object.<anonymous> (/Applications/MAMP/htdocs//myProject//gulpfile.js:16:1)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)



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

Automatically get "withCount"

I know that you can automatically retrieve relationships by putting the following in a model class:

protected $with = [
    'users', 'scores'
];

But is it possible to do the same with "withCount"?

I tried this but it didn't work:

protected $withCount = [
    'users'
];



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

One-To-One Eloquent Relationship functions

There is something I miss in the eloquent one-to-one relationship:

class MeetingTest extends Model
{
    protected $table = 'meeting_tests';

    public function meeting() {
        return $this->belongsTo('App\Meeting','meeting_id','id');
    }

    public function observation() {
        return $this->hasOne('App\Observation','meeting_test_id','id');
    }

    public function activity() {
        return $this->hasOne('App\TestActivity','activity_id','id');
    }
}

The Observation Class is

class Observation extends Model
{
    protected $table = 'observations';

    public function meetingTest() {
        return $this->belongsTo('App\MeetingTest','meeting_test_id','id');
    }
}

If I run php artisan tinker and

$mtn = App\MeetingTest::create();
$mtn->save();

$ob = App\Observation::create();
$ob->save;

$mtn->observation()->save($ob);

At this point inside the Observation record I can see the meeting_test_id filled with the correct id of the meetingTest, but if I try:

$mtn->observation

it gives me null; and in the Database there is no observation ID in the observation_id field;

this is the migration:

Schema::create('meeting_tests', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('meeting_id')->unsigned();
            $table->integer('observation_id')->unsigned()->nullable();
            $table->integer('activity_id')->unsigned()->nullable();
            $table->timestamps();
        });

I don't understand what is not correct.



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

Prevent lazy loading in view

I have a JSON result from a query that looks like this:

{  
    "id":1,
    "user_id":"1",
    "message":"Hello, world",
    "created_at":"2016-09-22 00:32:20",
    "updated_at":"2016-09-22 00:32:20",
    "stats": [
        ...
    ]
},
{  
    "id":2,
    "user_id":"1",
    "message":"Hello, world",
    "created_at":"2016-09-22 00:32:20",
    "updated_at":"2016-09-22 00:32:20",
},
{
    ... more results
}

Notice that sometimes the result has a stats property and sometimes it does not (despite every record having a stats relationship). Don't ask why, that's just how I have it set up in the backend.

I want to loop through these results in my view, like this:

@foreach ($posts as $post)
    @if (isset($post->stats) && !empty($post->stats)
        
    @endif
@endforeach

However, for post id 2, the loop will also output the $post->stats->total value because it lazy loads the stats.

How can I prevent it from lazy loading the stats relationship?



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

j-42 Laravel-Firebase Configuration

I am new to Firebase. So,

Firebase::delete('/my/path');

In above code segment what should be the value for /my/path?

I have tried event_cals/8 for that. There event_cals is the root node in the firebase tree and 8 is the id(child node name). So when I tried Firebase::delete('/event_cals/8'); it will display following error. PHP error: Argument 1 passed to J42\LaravelFirebase\Client::__construct() must be of the type array, null given, called in D:\SAHACKATHON\vendor\j42\laravel-firebase\src\j42\Larave lFirebase\LaravelFirebaseServiceProvider.php on line 53 and defined in D:\SAHACKATHON\vendor\j42\laravel-firebase\src\j42\LaravelFirebase\Client.php on line 20

So how to solve this issue guys?



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

Is there any way to sync data in Mysql with Firebase?

Since I couldn't find a way to delete and update objects in Firebase using Laravel5, I need a way. So can I know how to pass mysql data to Firebase?



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

get two users in a post in laravel

i have a users table with many users.example 1:mike, 2:nina, 3:john. and i have a posts table with user_id, which is the original creator of the post. and then i editors who can edit the post later on. any user can lock or open. thus if a post is locked only he can edit it while it is locked. so i have a field named locked_user_id in the posts table. I can have the laravel relationships as follows.

in User model:

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

in Post model:

public function user(){
        return $this->belongsTo('App\User');
    }

i can retrieve the author easily by

$posts->user->name

but how do i assume locked_user_id is a username id, and get its value, such as the name of the user who locked the post. can be the author at first and editor later on.



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

Limit results in nested comment system

I've created a nested comment system that outputs comments in the following layout:

| Comment 1
| | Comment 2
| | | Comment 3
| | | | Comment 4
| | Comment 5
| Comment 6
| Comment 7

This works fine for a smaller number of comments, but it becomes a problem when there are hundreds or thousands.

One problem, for example, is that the depth of the comments gets too large, like this:

| Comment 1
| | Comment 2
| | | Comment 3
| | | | Comment 4
| | | | | Comment 5
| | | | | | Comment 6
| | | | | | | Comment 7
| | | | | | | | Comment 8
| | | | | | | | | Comment 9
| | | | | | | | | | Comment 10
| | Comment 11
| Comment 12
| Comment 13

This becomes an issue when displaying the comments to the user as it makes the page/comments harder to read.

What I want to do is limit the number of results at certain depths. For example, in the code snippet above, how would I make it show no more than 5 comments deep and then have a button that says "click for more comments" that reveals the rest of the comments?

Additionally, another problem is showing too many nested comments, like this:

| Comment 1 (top-level comment)
| | Comment 2
| | Comment 3
| | Comment 4
| | Comment 5
| | Comment 6
| | Comment 7
| | Comment 8
| | Comment 9
| | Comment 10
| Comment 11 (top-level comment)
| Comment 12 (top-level comment)

Obviously, for readability reasons, I don't want to show all of the nested comments for each top-level comment. So how could I limit the number of results shown to 5 as well?

I need to combine these two ideas to give me a reasonable way to query the database to form a comment tree.

Here is my current code. I have a Comment.php model with the following relationship:

public function children()
{
    return $this->hasMany('App\Comment', 'parent_id', 'id')->with('children');
}

parent_id is the id of the parent comment.

And to get a comment tree of all comments currently in the database, I do:

$comments = Comment::where('post_id', 1)
    ->where('parent_id', 0)
    ->with('children')
    ->get();

How can I change my code/query to get my desired output?



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

Laravel parameters without explicitly specifying

I want to generate the page url without $name, something like this

http://ift.tt/2dI6Idh

BUT with the route get('/action/{name}', ...) i can get only this

http://ift.tt/2deDi3Jsomename

If i changing route to Route::get('/action', ...) it doesnt work, the error is "Missing argument 1"

My web.php

Route::get('/action/{name}', [
   'uses' => 'DoActionController@getAction',
   'as' => 'returnAction',
]);

My Controller action

public function ($name)
{
    return view('returnaction', ['name'=>$name]);
}

My home page

<body>
@foreach ($yourActions as $yourAction)
    <li> 
        <a href="">  </a> 
    </li>
@endforeach 



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

AdminLTE with Laravel hidden in menu

I'm using this package Laravel-AdminLTE

I changed the adminlte.php to display the item only with permission. But when the user does not permit it shows the header without options wanted to hide it well.

        'ROLES / PERMISSIONS', // want hidden this in my template.
        [
            'text' => 'Roles',
            'icon' => 'unlock-alt',
            'permission'  => 'approve', // if permission is deny
            'submenu' => [
                [
                    'text' => 'All roles',
                    'url'  => 'dashboard/roles',
                ],
                [
                    'text' => 'New role',
                    'url'  => 'dashboard/roles/create',
                ],
            ],
        ],



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

Laravel ResponseCache caches variables incorrectly

I am using the Spatie\ResponseCache to cache all responses in the frontend of my application. Sometimes I do need to parse some variable in the URL, like for search and pagination.

A URL like 127.0.0.1/publications will be cached and when I access 127.0.0.1/publications?start=20 it will show the cached page as per first URL.

How do I bypass this? I do not want to hard code it in the routes, like Route::get('/publications', ['middleware' => 'doNotCacheResponse', 'uses' => 'PagesController@content']) as /publications can be changed in the database.

Any help would be much appreciated



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

After uploading sql file, how can I run that file?

I am building a small website that displays sports data. I get the new data via SQL file. I am able to upload an .SQL file to my server, but get lost after that.

After upload I want to be able to run that same SQL file on the server, using it to populate/create MYSQL tables online.

Any thoughts on how to do this?



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

Call to undefined function - laravel

I want to use a helper functions but I got this error in my view :

Call to undefined function createSubCategories()

path of my helper functions:

Http\Controllers\Utilities\Helpers.php

my hlper :

<?php
namespace App\Http\Controllers\Utilities;


    function createSubCategories($parent_cat_id = 0)
    {

        $subs = DB::table('categories')->where('parent_cat_id', '=', $parent_cat_id)->get();
        if (count($subs) > 0) {
            echo '<ul>';
            foreach ($subs as $sub) {
                echo '<li>' . $sub->title_fa;
                echo $this->createSubCategories(($sub->id));
                echo '</li>';
            }
            echo '</ul>';
        }
    }

in composer.json :

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files":
    [
        "app/Http/Controllers/Utilities/Helpers.php"
    ]
},

I used composer dump-autoload.

my view:





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

What is the query to delete a particular object from Firebase using Laravel 5?

I am new to Firebase. Still I couldn't find a way to delete a particular object from Firebase.

$evnt = EventCal::where('id', '=', $id)->delete();

I have tried out above query to delete. But still it doesn't produce a result in Firebase. I am using 'Mpociot\Firebase\SyncsWithFirebase' to sync data with firebase.



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

Swift_IoException in FileByteStream.php Unable to open file for reading

I am trying to upload a csv file in php laravel But i'm getting an error unable to open a file for reading.

Here is my mail code public function sendReports($to,$emailId,$filePath) { $this->recepient = $to; $data = [ "emailId" => $emailId, "filePath" => $filePath ]; Mail::send('emails.sendReports',$data, function($message) use ($filePath) { $message->from('$this->recepien'); $message->to($this->recepient)->subject('PMS Forgot Password'); $message->attach($filePath); }); }



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

Call to undefined function Laravel

I have problem when I'm checking if collection is empty or not, Laravel gives me error

"Call to undefined method Illuminate\Database\Query\Builder::isEmpty()".

Tho it work in other Controller, but when controller is in Sub folder is suddenly stops working.

Here is my code:

$group = UserGroup::where('id', $request->group_id)->first();
    if($group->isEmpty()){ // I get error from here
      return redirect()->back();
    }



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

Database [] not configured Laravel 5

I create new db in phpmyadmin and new tables.

Then i do

    public function next(Request $request){
    $langs = DB::connection('mydb')->select('select * from lang');
    }

and get

Database [compgen] not configured.

in my .env

DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=123

in my config/database.php

        'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'test'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', '123'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => 'test_',
        'strict'    => false,
    ],



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

laravel 5.* - package driven development - best practices

this is not a code question about laravel 5.*, it's more like to know if you guys develop your applications using packages ("package driven development" ? Not sure if this is the right definition).

What I mean is: Instead of building an application and create controllers in app/Http/Controllers/, you wrap everything in a package and then 'require' that package using composer (like a wordpress plugin).

I'm trying to think in a way to isolate the core Laravel from my specific application and save time later when it's time to upgrade when a new Laravel version is available.

In my case I'm having some issues moving from version 5.2 to 5.3 because I have some customization in the registration and login process - It might be because I'm not using the right approach to write the code (patterns), so I'd like to hear from more experienced Laravel developers.

Thanks!



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

Laravel 5.x Ajax Post from an array not working

I have been looking everywhere for solutions and I am convinced I am doing everything right.

I have a list of IDs in an array that I need to channel through to the controller for deletion but the request object always gives me an empty array when I do $request->all() but if I dump the request object itself I am able to see it and its related properties and methods.

JavaScript

var data = [id: 14, id:77, id:138]; //We will convert this to a json string

$.ajax({
  type   : 'POST',
  url    : '/orders/cancel',
  data   : JSON.stringify(data), //Outputs [{"id":"x"},{"id":"x"}]
  headers: { 'X-CSRF-TOKEN':token },
  success: function(){ //the usual },
  error: function(){ //the usual }
});

Laravel Route

Route::any('/orders/cancel', 'BackOrderedOrdersController@cancelAction');

The Controller

namespace My\Namespace;

use Illuminate\Http\Request;
//other irrelavant `use` statements omitted
class BackOrderedOrdersController extends Controller
{
   public function cancelAction(Request $request)
   {
      dd($request->all()); //This just outputs '[]' : empty array
   }
 }

The response status is 200 meaning everything is fine but the posted data does not reach the controller for some reason.

This is also a first time I had to work with Ajax Post without my data coming from a form and also I am a bit reluctant in terms of whether that is the issue.

My bet is around this content type defined as application/x-www-form-urlencoded;charset=UTF-8 by FIREBUG output even when I specified data type as json. I am partially aware of what this content-type and encoding is all about entails but in this instance.

Can someone pinpoint me to the right direction as to where the data gets missed? Is it a JQuery issue, Laravel issue or what?



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

Saving a Static Data into database Without Clicking any Button

I have a question. Is it possible to save a static data into the database without clicking any button in laravel 5.0?



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

how to use multiple session driver in laravel

In Laravle5.3 I want to use multiple session driver,in the frontend I just use redis as the driver but in the backend have to use database as the driver,I tried but cant find a way to solve this problem,first I just use middleware before the session start,but you know if change the drive,the other data will disappear,it did`t work,how can i configure this,thanks a lot.



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

Validation for dynamic radio buttons Laravel 5

I want to validate my dynamic radio inputs. I have this in my view view.blade.php:

echo "<span class='error'>".$errors->first('sar')."</span><td></tr>";

for($i=1; $i<11; $i++){
echo"<td>"; ?>
<input class='radio-inline' name='sar[<?php echo $number; ?>]' type='radio' value='<?php echo $i; ?>' ><?php    echo "</td>";} 

Controller:

//valida pontas -- 
$this->validate($request, [
    'sar' => 'required'
]);

I have tried: inside view $vf = 'sar['.$fcid.']'; $errors->first($vf) and inside my controller: 'sar[$i]' => 'required'

So the for loop dynamically creates radio buttons with names like 'sar[1]' in my this validate i dont know how I would validate each dynamically created radio input... Any ideas on how to approach this would be greatly appreciated..



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

Laravel package file publishing with interaction or

Suppose a user calls vendor:publish without specifying any tags:

artisan vendor:publish --provider="Vendor\Package\PackageServiceProvider"

This will execute all of the providers publishes regardless of tags.

But some of my files are mutually exclusive versions of each other, only one should be published.

Can I somehow hide publishes from vendor:publish? Is it posssible that some files are only published if the tag is explicitly asked for instead of publishing everything if no tag is specified?

Is interactive publishing somehow possible? Something like this:

artisan vendor:publish --provider="Vendor\Package\PackageServiceProvider"
Do you need migrations? [Y|n]



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

Laravel Route:list not working throwing run time exception

when i tried to display all routes

by using php artisan route:list

it showing some runtime exception like this

  [RuntimeException]
  Session store not set on request.

how can i get my list of routes



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

How to format Excel cell with PHPExcel_Reader_HTML

I am using PHPExcel_Reader_HTML and passing it my HTML to generate excel file, but the problem is that it does not highlight the excel cell color as in the 'HTML' table (see image blow), I am using Laravel5

<?php



$content = $title;
$content .= '<table border="1">';
$content .= '<tr>';
foreach($fields as $f )
{
    if($f['download'] =='1') $content .= '<th style="background:#f9f9f9;">'. $f['label'] . '</th>';
}
$content .= '</tr>';

foreach ($rows as $row)
{
    $content .= '<tr>';
    foreach($fields as $f )
    {
        if($f['download'] =='1'):
            $conn = (isset($f['conn']) ? $f['conn'] : array() );
            $content .= '<td> '. htmlentities(AjaxHelpers::gridFormater($row->$f['field'],$row,$f['attribute'],$conn)) . '</td>';
        endif;
    }
    $content .= '</tr>';
}
$content .= '</table>';
$path = "../storage/app/".time().".html";
file_put_contents($path, $content);

// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($path);

// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
// Delete temporary file
unlink($path);

// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');

// It will be called file.xls
header('Content-disposition: attachment; filename="'.$title.' '.date("d/m/Y").'.xlsx"');

// Write file to the browser
$objWriter->save('php://output');

Note: ( My question is different then the questions been asked on stackoverflow, my coding scenario is different then all..)



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

SQL error Many-to-Many migration file Laravel 5

I'm trying to create a new pivot table in my application. I want to connect my users table to my customers table. It must be a many-to-many relationship. I have created a migration file. It looks like this:

<?php

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

class CreateUsersCustomersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('customer_user', function (Blueprint $table) {
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->string('customer_fb_id')->unsigned()->index();
        $table->foreign('customer_fb_id')
            ->references('facebook_id')
            ->on('customers')
            ->onDelete('cascade');

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

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

When i run php artisan migrate i get the following error message:

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 
1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL 
server version for the right syntax to use near 'unsigned not null, `created_at` timestamp 
default 0 not null, `updated_at` times' at line 1 (SQL: create table `customer_user`
(`user_id` int unsigned not null, `customer_fb_id` varchar(255) unsigned not null, `created_at`
timestamp default 0 not null, `updated_at` timestamp default 0 not null)
default character set utf8 collate utf8_unicode_ci) 

In the users table the ID is an integer and in the customers table facebook_id is a string. In my opinion i'm doing it the right way, so I have no idea what i'm doing wrong?

Thanks in advance!



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

Laravel FFMPEG Error Encoding Failed using Laravel Queue

I am using "php-ffmpeg/php-ffmpeg": "~0.5" with Laravel 5. I am using this library for compression and conversion of recorded videos. I will explain the scenario first.

When I execute following code from controller it works like charm.

$ffmpeg = FFMpeg::create();
$video = $ffmpeg->open(public_path()."/videos/harsh.webm");
$video
    ->filters()
    ->resize(new \FFMpeg\Coordinate\Dimension(640, 480))
    ->synchronize();
$video
    ->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(10))
    ->save(public_path().'/videos/converted/kaushik.jpg');
$format=new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264'); 
$format-> setKiloBitrate(300);
$video->save($format,public_path().'videos/converted/kaushik.mp4');``

But when I put this code in a queue job then it fails with following error

[FFMpeg\Exception\RuntimeException]
Encoding failed [Alchemy\BinaryDriver\Exception\ExecutionFailureException]
ffmpeg failed to execute command '/usr/bin/ffmpeg' '-y' '-i' '/opt/lampp/htdocs/candidate/public/videos/harsh.webm' '-async' '1' '-metadata:s:v:0 ' 'start_time=0' '-s' '640x480' '-vcodec' 'libx264' '-acodec' 'libmp3lame' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes57ece7d794da4wdw13/pass-57ece7d794e2a' 'videos/converted/kaushik.mp4' ``

I am able to convert video in MWV and WEBM using following

$video->save(new \FFMpeg\Format\Video\WMV(), 'export-wmv.wmv');
$video->save(new \FFMpeg\Format\Video\WebM(), 'export-webm.webm');

only mp4 fails if I use the

$format=new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264');

What would be the issue?

Sorry for my code markup in this question, I tried lot but faild, I am new to it!



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

Menu filter permission with Laratrust

I'm using AdminLTE and Lara Entrust created a MyMenu Filter.php file to filter my options in accordance with the permission menu.

adminlte.php

'menu' => [
    'MAIN NAVIGATION',
    [
        'text' => 'Blog',
        'url'  => 'admin/blog',
        'permission'  => 'create-post',
    ],
    // CODE...
 ],

'filters' => [
    // CODE...
    App\MyMenuFilter::class,
],

MyMenuFilter.php

<?php

namespace App;

use JeroenNoten\LaravelAdminLte\Menu\Builder;
use JeroenNoten\LaravelAdminLte\Menu\Filters\FilterInterface;

class MyMenuFilter implements FilterInterface
{
    public function transform($item, Builder $builder)
    {
        if (isset($item['permission']) && \Laratrust::can($item['permission'])) {
            return false;
        }

        return $item;
    }
}

My option in the "blog" menu need the create-post permission. But the "if" in mymenufilter.php returns false quando o usuário tem a permissão and does not create the menu.

But if I put a permission that the user does not have, it appears.



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

Laravel whereRaw not returning anything

I have written my sqlquery in workbench first before actually moving it over to laravel code, and I can confirm this works. Here is my sql query written in workbench

SET @info = 'hello';

SELECT device_type_id 
FROM arecibo.device_type_mappings
WHERE @info LIKE concat('%', name , '%') COLLATE utf8_unicode_ci;

I want to now convert this to code but am having troubles as it is not returning anything back. I have googled around to see what I might be missing but to no avail I could not find anything. Here is my attempted code:

$deviceTypeId = DB::table('device_type_mappings')
        ->select('device_type_id')
        ->whereRaw('? LIKE concat(\'%\', name , \'%\') COLLATE utf8_unicode_ci;', [$sysInfo])
        ->get();

if possible I would like to use the model, but it was complaining that there was no select method exposed.

I am using laravel 5.3



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

code optimization laravel.i want to retrived a avilable group where member not already exist

there is a three table

user,memember,group_member(relation mem_id,group_id) many to many

i have define a relation for group on member model

public function group(){
        return $this->belongsToMany('Model\Group', 'group_member', 'mem_id', 'group_id');
    }

using above relation i can retrieve a member asigned group using

   Model\Member::with('group')->find('member_id')

now i want those group where member is not assigned . i have done using

$arg['ids'] = $member->group->lists('_id');
        $group = Group::where('user_id',$user_id)->whereNotIn('_id',$arg['ids'])->limit($arg['limit'])->offset($arg['offset'])->get();

there is a another option rather then subquery ??



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

"Error validating verification code. Please make sure your redirect_uri is identical to the one you (truncated...)

I'm using Laravel/Socialite to generate a login for Facebook OAuth.

That URL is <my domain>/auth/facebook?appUser=a@b.com

As a means of "stabbing in the dark" i've added the following Auth redirect URIs into the Facebook app:

http://<my domain>/auth/facebook/callback

http://<my domain>/auth/facebook/callback/

http://<my domain>/auth/facebook/callback?appUser

http://<my domain>/auth/facebook/callback?appUser=%3F

http://<my domain>/auth/facebook/callback?appUser=%2F

http://<my domain>/auth/facebook/callback?appUser=%3F%2F

But once the Facebook login happens, i'm redirected to:

http://<my domain>/auth/facebook/callback?appUser=a%40b.co.uk&code=<code>

and the above URL then generates an error of Error validating verification code. Please make sure your redirect_uri is identical to the one you (truncated...)

I have tried urlencodeing my domain, the parameters in the URL, the value of the parameter in the URL but no no avail.

Can somebody offer some advice here please?



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

Laravel 5 create pagination from json data in blade view

I have done the query below, and I am able to get the json data from console log, my question is how to make a pagination link using the json data?

$viewData = DB::table('tbl_contents')
                ->where('record_type', '=', 'Event')
                ->where('status', '=', 1)
                ->paginate(3);

return json_encode($viewData);



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

Laravel resolve helper returns string

I have a binding in my AppServiceProvider:

$this->app->bind(
    'App\Services\Avatars\Contracts\AvatarServiceInterface',
    'App\Services\Avatars\GravatarAvatarService'
);

If I inject the AvatarServiceInterface into a controller constructor or method then it correctly returns an instance of the GravatarAvatarService class. However, if I try to use the resolve helper in a controller method (or anywhere else for that matter), e.g.:

$instance = resolve('App\Services\Avatars\Contracts\AvatarServiceInterface');
var_dump($instance);

...it is just returning a string of whatever I'm asking it to resolve. In the example above it returns:

'App\Services\Avatars\Contracts\AvatarServiceInterface' (length=53)

The resolve helper was working for me up until a few days ago. I've tried running composer update to get the latest version of the framework but that hasn't solved this issue.

Anyone have any ideas?



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

mercredi 28 septembre 2016

How to strict video file to upload using ValidateRequest in laravel

I have a user registration form, where i am using file input box to upload image. Now the problem is , if i will select video file to upload it will pass ValidateRequest . In ValidateRequest, i already define the rule for image, below is the code:

class UserValidateRequest extends Request {

public function __construct() {

}

protected $messages = [
    'required.password' => 'We need to know your e-mail address!',
];
protected $rules = [      
    'first_name' => 'required|regex:"[a-zA-Z 0-9]"',
    'last_name' => 'regex:"[a-zA-Z 0-9]"',
    'image' => ' mimes:jpeg,jpg,png,gif |max:2048',           
];  

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize() {
    return true;
}

public function messages() {
    return [
        'password.regex' => 'Password shall be 8-20 characters, must have a number and an alphabet',           ,
        'image.mimes' => 'Upload Gif || JPG || JPEG || PNG Images Only'
    ];
}

  public function attributes() {
      return[];
  }

}



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

Sending Laravel Queue Message Using SQS Amazon

I'm using sqs queue in my laravel. Right now I have successsfully pushed my queue job to sqs server as shown in the picture below : enter image description here

The problem is, the message is never got executed. So how to process this message on SQS...?? Thanks a lot



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

Admin LTE with Laratrust

I'm using Laratrust and try implements: I created these files

App\MyMenuFilter.php

<?php

namespace App;

use JeroenNoten\LaravelAdminLte\Menu\Builder;
use JeroenNoten\LaravelAdminLte\Menu\Filters\FilterInterface;

class MyMenuFilter implements FilterInterface
{
    public function transform($item, Builder $builder)
    {
        if (isset($item['permission']) && Laratrust::can($item['permission'])) {
            return false;
        }

        return $item;
    }
}

I changed this config\adminlte.php

'menu' => [
    'MAIN NAVIGATION',
    [
        'text' => 'Blog',
        'url'  => 'admin/blog',
        'permission'  => 'create-post', // Here
    ],
    #code
]

'filters' => [
    #code
    //JeroenNoten\LaravelAdminLte\Menu\Filters\GateFilter::class,
    App\MyMenuFilter::class,
],

But show this error:

Class 'App\Laratrust' not found (View: /var/www/html/multi-auth/vendor/jeroennoten/laravel-adminlte/resources/views/page.blade.php)



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

Enable features of Laravel project to update and delete json objects with firebase

I am using firebase and mysql as the backend. I can insert data to firebase using laravel project. But deleting and updating operations only valid for mysql. I want to make active those features for firebase also. I am using 'Mpociot\Firebase\SyncsWithFirebase' to sync data with firebase. It is perfectly working for insertion only. But there's already built in methods for all the database operations in the syncsWithFirebase php file. I need a solution for that guys.

 public function store(Requests\EventRequest $request){

    $request->all();

    $current=Carbon::now();
    $t=substr($current,11,-3);
    $d=substr($current,0,-9);
    $st=explode(":",$t);
    $currentTime=$st[0].$st[1];
    $postTime=$_POST['time'];
    $time=explode(":",$postTime);

    $insertTime=$time[0].$time[1];
    $date=$_POST['eventDate'];
    if(strcmp($d,$date)==0) {
       if ($currentTime > $insertTime) {


           Session::flash('errorTime', 'Time is passed.');
           return redirect()->back()->withInput();
       }
    }
    $events=EventCal::all();
    foreach($events as $ev){
        $ti=substr($ev->time,-8,5);

        if( (strcmp($ev->eventDate,$date)==0) && (strcmp($ev->venue,$_POST['venue'])==0) && (strcmp($ti,$postTime)==0) ){

            Session::flash('errorDate', 'There is already an event for this time,Venue and Starting Date');
            return redirect()->back()->withInput();
        }
    }



    $input=Request::all();

    if (Input::hasFile('photo')) {
        $file = Input::file('photo');
        // getting image extension
        $extension = $file->getClientOriginalExtension();
        // renameing image
        $fileName = rand(11111, 99999) . '.' . $extension;
        // uploading file to given path
        $file->move('images', $fileName);
        $input['photo'] = "images/$fileName";
    }


    EventCal::create($input);
    flash()->success('Successfully Added','Good Job');
    return redirect('/evntform');

}

Above is the code for inserting which works fine.

 public function index5($id){

    $evnt = EventCal::where('id', '=', $id)->delete();
    return redirect('/dcalendar');
}

And above code is to deleting which is not sync with firebase. I tried to find the answer for several time and even asking from my friends on stack. So if anyone can find a solution to my problem it will be a great worthy to me.



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

how to make a html view for all master data view

I am beginner on laravel, its possible to make a html view (view_master.blade.php) for display all master data view, such as users data use this view_master.blade.php , students data also use this view_master.blade.php to display data.



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

Where to locate and how to setup view helpers in Laravel 5

I want to create what I believe in Laravel is called a view helper (I'm new to Laravel so I'm not certain of the vocabulary)... in other words one or more methods that are available in all views.

Where in the directory structure would I place such a thing, and how should I use it, in a manner that's compatible with Laravel 5?

Thanks



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

Separating methods into many controllers?

I noticed that many of the examples in the Laravel docs seem to have Controllers where the class has only one use/method.

For example, in this part of the doc, they have a UpdatePasswordController class with a single method, update():

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class UpdatePasswordController extends Controller
{
    /**
     * Update the password for the user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // Validate the new password length...

        $request->user()->fill([
            'password' => Hash::make($request->newPassword)
        ])->save();
    }
}

Normally, I would put a method called updatePassword() in my UserController class (along with signIn(), signUp(), resetPassword(), etc.), but I'm wondering if it's better to create multiple classes, each with a single action?



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

Include Bootstrap glyphs in Laravel Collective link

I'm using Laravel Collective's link_to_route() method to create a link. I want to include a Bootstrap glyph with this link.

As it is now, it's printing the actual Html code.

Any tips on how to do this?

My current code:

<div class="col-lg-1 well">
    {!! link_to_route('companiesindex', "<span class='glyphicon glyphicon-log-in' aria-hidden='true'></span> Companies") !!}
</div>



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

Laravel Cannot find Image

I am having a problem with accessing images. 1. I can upload and receive an image to the database no problem however I have my images manually saved under the public/avatar folder and i can receive the images from there by using . but i cannot figure out how to save to that location ive tried Storage::disk('local')->put('/uploads/avatars/',$image); but it does not work. 2. when i try to save from using the controller it saves everything in storage/app/public and i do not know how to access those files from the model, or how to save them somewhere else.



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

Issue with redirect() when using conditional to evaluate multiple form buttons

So I've built a small conditional to evaluate which button is pressed in my form (as there are 2), this works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.

I suspect the problem has something to do with my conditional and the use of '$this'.

Here is my check_submit method:

public function check_submit()
{
    if(!is_null(Input::get('add_to_invoice'))){
        $this->invoice_add_item();
    } elseif(!is_null(Input::get('complete_invoice'))) {
        $this->invoice_complete();
    }
}

Here is one of the 2 methods which I am currently testing:

    public function invoice_add_item()
{
    $input = Request::all();
    $invoice_items = new Expense;
    $invoice_items->item_id = $input['item_id'];
    $invoice_items->category_id = $input['category'];
    $invoice_items->price = $input['price'];
    $invoice_items->store_id = $input['store'];

    if(Input::has('business_expense'))
    {
        $invoice_items->business_expense = 1;
    }
    else{
        $invoice_items->business_expense = 0;
    }
    $invoice_items->save();
    return redirect('/');
}

Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.

Any help would be greatly appreciated.

Thanks!



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

Laravel 5 error when using whereIn

I migrated my laravel app from 4 to 5 and i am having an issue with this query:

$ids = AssetCustomTag::whereIn('custom_tag_id', $custom)->lists('asset_id')->all();

where $custom is an array of ids.

The error thrown from laravel is this one.

Declaration of AssetCustomTag::create(array $input) should be compatible with Illuminate\Database\Eloquent\Model::create(array $attributes = Array)

Not sure what that means as I am very new to laravel.



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

How do I display mysql data in datatables using Laravel?

I have a table payments. I would want to display the contents in datatables. I have tried to follow the http://ift.tt/1S0sDK7 to achieve this but I am not successful. I am using laravel 5. The latest version.

Kindly find my code below and possible direct me.

for the route:

<?php
use Yajra\Datatables\Datatables;
use DB;

Auth::routes();

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

Route::get('/payments', [
    'as'   => 'payments',
    'uses' => function () {
        $payments = App\payments::select([
'name','amount', 'trans_id', 'msisdn', 'time_paid', 
'account', 'organizationaccountbalance']);

      return Datatables::of($payments)->make();
    }

the view: payments.blade.php

@extends('layouts.master')

@section('content')
<table class="datatable">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Amount</th>
        <th>Transaction ID</th>
        <th>Mobile Number</th>
        <th>Time Paid</th>
        <th>Account</th>
        <th>Organisation Account Balance</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
  <script>
    $(document).ready(function(){
      $('.datatable').DataTable({
            processing: true,
            serverSide: true,
            ajax: ''
        });
    });
  </script>
     @endsection
]);

Anytime I try to view /payments is get the error below:

FatalThrowableError in web.php line 23: Class 'App\payments' not found

    in web.php line 23
    at RouteServiceProvider->{closure}() in Route.php line 176
    at Route->runCallable() in Route.php line 147
    at Route->run(object(Request)) in Router.php line 642
    at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 53
    at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41
    at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137
     ......................

What am I doing wrong, anyone?

Thank you.



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

Order by relationship's value

If I have a table called users:

| id | username | password |

And a table called user_stats:

| id | user_id | num_posts |

How can I get all users and sort them by the number of posts they have?

My User.php model has this relationship:

public function stats()
{
    return $this->hasOne('App\UserStat');
}

And my UserStat.php model has this relationship:

public function user()
{
    return $this->belongsTo('App\User');
}

I know I can do a join using the query builder, like:

$users = User::join('user_stats', 'users.id', '=', user_stats.user_id')
    ->get();

But is there a better way to do it using just the Eloquent ORM?



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

Larval 5.3 Seeder - undefined method table?

I'm trying to learn Laravel, but it seems the documentation is written with faulty examples... I want to create a table migration, run it, and seed it with some content.

First:

php artisan make:migration create_projects_and_tasks_tables

With the following content:

<?php

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

class CreateProjectsAndTasksTables extends Migration
{
    /**
      * Run the migrations.
      *
      * @return void
      */
      public function up()
      {
          Schema::create('projects', function (Blueprint $table) {
              $table->increments('id');
              $table->string('name')->default('');
              $table->string('slug')->default('');
              $table->timestamps();
      });

      Schema::create('tasks', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('project_id')->unsigned()->default(0);
          $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
          $table->string('name')->default('');
          $table->string('slug')->default('');
          $table->boolean('completed')->default(false);
          $table->text('description');
          $table->timestamps();
      });
  }

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

It migrated Ok. So I want to seed the projects table.

First:

php artisan make:seeder ProjectsTableSeeder

The contents:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ProjectsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $projects = array(
            ['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
        );
        DB::table('projects')->insert($projects);
    }
}

All set, I tried to rollback the migration, migrate and seed it:

php artisan migrate:refresh --seed
Rolled back: 2016_09_28_160459_create_projects_and_tasks_tables
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_09_28_160459_create_projects_and_tasks_tables

[Symfony\Component\Debug\Exception\FatalThrowableError]                   
  Call to undefined method Illuminate\Database\MySqlConnection::setTable()

And that's it. My table is empty, and the method DB::table() seems to not exist anymore in the framework, even if the 5.3 docs shows it. What can I do?

I'm using the Laravel Homestead vagrant box, so php version or composer isn't the issue. I'm also using MySQL as my database driver.



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

Laravel 5.2 reCaptcha fails after succeeds

So, I have placed the reCaptcha in my login form. I click on "im not a robot" and click on the right images and it says it succeeded, but when I submit the form it returns me the message of "The Captcha field is not correct." and it also thrown and exception saying:

'Illuminate\Foundation\Validation\ValidationException' with message 'The given data failed to pass validation.'

I am using "greggilbert/recaptcha" in my Laravel 5.2 project. I have set my keys and everything is working great in production and in other localhost's but not in mine.

My team and I work in the same git repository and it works for everyone but not for me. I have re-installed the plugin, also the whole composer (by deleting vendor and then composer install).

I have cleared the configuration with php artisan config:clear and I've done the composer dump-autoload and have re-publish the ServiceProvider with php artisan vendor:publish --provider="Greggilbert\Recaptcha\RecaptchaServiceProvider"

Does somebody have any idea on how to fix this? Please!

Thank you a lot for reading this! Happy coding!



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