jeudi 31 octobre 2019

Laravel always gets empty from JSON post

I'm working on Laravel version 5.2. I've been trying to get json data from post. I always get empty data. I also have tried to use solutions found on the internet but there's nothing works. for example,

  1. $request->json()->all();
  2. Input::get('data');
  3. $request->get('data');
  4. $request->data;
  5. Input::all();
  6. json_decode(request()->getContent(), true);
  7. json_decode($request->getContent(), true);
  8. json_decode(request()->get('payload'));
  9. json_decode($request->get('payload'));
  10. $request->input('data');

Here is my javascript code,

    $.ajax({
    method: 'POST',
    url: url,
    contentType: 'application/json',
    headers: {
        'X-CSRF-TOKEN': token
    },
    data: {'data':'foo'},
    success: function(data) {
        console.log(data);
    }
});

And here is my laravel code,

public function postJsonData(Request $request){

    //several methods I am trying to use.
    $data = $request->data;

    Log::info($data);

    return json_encode($data);
}

Now I really have no ideas to move on. I really need help. Thanks for your time.



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

How to call a file from the route

I wanted to call the file from the route on Laravel. I have a PostsController and inside there was a method name index. I created a folder inside views name posts and inside that created a file named index. I tried to print the variable into the index.blade.php file which i assigned into the PostsController, but got error. Can anyone help me. Here is my code

Route :

Route::post('/posts/index', 'PostsController@index');

Controller : `

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostsController extends Controller
{
public function index()
{
    $nameIndex = "Testing";

    return view('posts/index',
    [
        'nameIndex' => $nameIndex
    ]);
}
}

` view file : posts/index.blade.php

My name is :



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

How to change route name from admin panel in Laravel

I have a registration form in my Laravel site. Suppose route name is 'reg_form' for the registration page.

But I want to change my route name for the registration page 7 days after and after from admin panel. How can I do it ?

Anybody help please. Thanks in advance.



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

Best practice for very large data

We need to manage the very large size data. It will be around 50 million records per table.

What will be the best database or some other tools to manage these large-sized data?



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

General error: 1364 Field 'department_id' doesn't have a default value

here's the error

SQLSTATE[HY000]: General error: 1364 Field 'department_id' doesn't have a default value (SQL: insert into `ms_user` (`name`, `username`, `role`, `email`, `password`, `updated_at`, `created_at`)

ms_user model

protected $fillable = [
        'department_id','name', 'email', 'password','username','role',
    ];

create function :

    {
        return ms_user::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'role' => $data['role'],
            'email' => $data['email'],
            'department_id' => $data['department_id'],
            'password' => bcrypt($data['password'])
        ]);
    }

validator function :

 protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255',
            'role' => 'required|in:user,admin',
            'department_id' => 'required|string',
            'email' => 'required|string|email|max:255|unique:ms_user',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

department_id is a dropdown menu that contains data from the ms_department table, department_id becomes the foreign key in the ms_user table and as the primary key in the ms_department



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/36pH7xI
via IFTTT

What method of filter i should use on laravel?

Im now ready all the stuff and ready to use, but then i want to set a filter that ( ' if the item status shows as "freeze", do not show in the drop-down selection again )

For example, i set the first 'description11' as freeze, so i want the dropdown selection for ' description11' don't show up, how to set it ?

VIEW[view]: https://i.stack.imgur.com/PuIBD.png

The Dropdown selection picture:

enter code here

@extends('master')


        @if(\Session::has('success'))
            <div class="alert alert-success">
                <p></p>
            </div>
        @endif

        <form method="post" action="">
            
            @csrf
            <div class="form-group">
                <label for="bit_app_policy_category_code">Code<span class="required">*</span></label>
                <input id="bit_app_policy_category_code" type="text" name="code" class="form-control" placeholder="Please Enter the Code" />
            </div>
            <div class="form-group">
                <label for="bit_app_policy_category_desc">Description<span class="required">*</span></label>
                <input id="bit_app_policy_category_desc" type="text" name="description" class="form-control" placeholder="Please Enter the Description" />
            </div>

            <input  type="hidden"
                    name="parent_id"
                    value=""
            />

            <div class="form-group">
                <label for="bit_app_policy_category_parent">Parent Category</label>

                <select id="bit_app_policy_category_parent"  name="parent_id" class="form-control">

                    @foreach($parents as $parent)
                        <option value=""> </option>
                    @endforeach
                </select>
            </div>

            <div class="form-group">
                <label for="bit_app_policy_category_status">Status<span class="required">*</span></label>

                <select id="bit_app_policy_category_status"  name="status" class="form-control">
                    <option value="Active">Active</option>
                    <option value="Freeze">Freeze</option>
                </select>
            </div>


            <div class="form-group">
                <a href="" class="btn btn-primary">Back</a>
                <a href="" class="btn btn-primary">Back to Home Page</a>
              <input type="submit" class="btn btn-primary"/>
            </div>
        </form>
    </div>
</div>

my index file

@extends('master')

@section('content')

<div class="row">
    <div class="col-md-12">
        <br />
        <h3 align="center">Category Data</h3>
        <br />
        @if($message = Session::get('success'))
            <div class="alert alert-success">
                <p></p>
            </div>
        @endif
        <div align="right">
            <a href="" class="btn btn-primary">Add</a>
            <a href="" class="btn btn-primary">Back to Home Page</a>

            <br />
            <br />
        </div>
        <table class="table table-bordered table-striped">
            <tr>
                <th>Id</th>
                <th>Code</th>
                <th>Description</th>
                <th>Parent</th>
                <th>Status</th>
                <th>Action</th>
                <th>Action</th>
            </tr>
            @foreach($category as $row)

                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>

                    <td><a href="" class="btn btn-warning">Edit</a></td>
                    <td>
                        <form method="post" class="delete_form" action="">
                            
                            

                            <input type="hidden" name="_method" value="DELETE"  />
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>
    </div>
</div>
<script>
    $(document).ready(function () {
        $('.delete_form').on('submit', function () {
            if (confirm("Are you sure you want to delete it"))
            {
            return true;
            } else
                {
                return false;
            }
        });
    });
 </script>
@endsection


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

Get property (none object) laravel

I have a recommends table which has user_id and product_id column and I'm trying to display mostly viewed products but I get an error Trying to get property of non-object from the view, if I dd($viewed) it shows all the products correctly but the problem is it can't display products and throws an error, any idea on how to solve this?

Controller

$viewed = Recommends::with('product')
     ->where('user_id', Auth::user()->id)
     ->select('product_id')
     ->inRandomOrder()
     ->groupBy('product_id')
     ->orderby('product_id', 'DESC')
     ->take(8)
     ->get();

Blade file

 @foreach($viewed as $view)

   <h1>USD: </h1>
   <h2>USD: </h2>
  @endforeach


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

DOMPDF generate tags

I am developing a system that generates and prints PDF labels. I am using the DOMPDF library. The problem is in tag generation, because the user selects the desired tag template and the system must assemble it with the database data. Today I am mounting the label by hand, but there are many label templates. I saw that there is a package that generates tags, but it is for MPDF (https://github.com/PronerInformatica/phppimaco). Does anyone know something like for DOMPDF?



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

Uncaught TypeError: $(...).meanmenu is not a function

any field of my web page is not responding and in console log following error is shown "Uncaught TypeError: $(...).meanmenu is not a function at main.js:20 at main.js:130"

here is the code of main.js:20

$('.main-menu nav').meanmenu({ meanScreenWidth: "767", meanMenuContainer: '.mobile-menu' });



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/36m2Zuc
via IFTTT

Vendor Model Not Found

I installed Jeylabs/AuditLogs and tried to use it. Saving, updating and deleting of records are working as expected and all this logs are being saved in the audit_log table. Now I'm trying to use the auditlog retrieve data. As instructed in the Github page it says that I just need to use AuditLog::all()->last() to retrieve the data. But it's giving me an error that the AuditLog class is not found. I'm not sure what I'm doing wrong. I tried to use this function in the Controller, CustomRepositoryClass and Model but none is working. Not sure what do I do. Below is my code for retrieving the data

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
use DB;
use Jeylabs\AuditLog\Traits\LogsAudit;
use Jeylabs\AuditLog\Traits\CausesAudit;


class Booking extends Model
{
    use SoftDeletes, LogsAudit, CausesAudit;
    public function scopeGetLogs()
    {
        $auditlog = AuditLog::all()->last();
        dd($auditlog);
    }
}

In my controller

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Auth;
use App\Http\Controllers\Controller;
use App\Booking;
use Gate;
use Jeylabs\AuditLog\Traits\LogsAudit;
use Jeylabs\AuditLog\Traits\CausesAudit;

class LogsController extends Controller
{    
    use SoftDeletes, LogsAudit, CausesAudit;
    public function index()
    {
        Booking::getLogs();
    }
}

But this can't read the model AuditLog any idea on how to make this work?



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

Laravel table inheritance. How to create relationships

I have the following tables that represent a Purchase. A Purchase contains many items. An item can be of two possible types MaterialItem / ServiceItem. A Material Item has a Material associated while a ServiceItem only contains a few text fields.

Table "purchases_item_base" contains the columns in common of the two possible item types.

How can I define two relationships in my Purchase model, one for retrieving the associated Material Items and another for the Service items?

    // TABLE 1 purchases
    Schema::create('purchases', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();            
        $table->text("details");            
        $table->timestamps();
        $table->softDeletes();
    });



    // TABLE 2 purchases_item_base
    Schema::create('purchases_item_base', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();
        $table->unsignedBigInteger("purchase_id")->unsigned();          
        $table->decimal("price", 15 , 2);            
        $table->unsignedTinyInteger("priority");
        $table->text("obs");
        $table->timestamps();
    });

    Schema::table('purchases_item_base', function(Blueprint $table) {
        $table->foreign('purchase_id')->references('id')->on('purchases');            
    });



   // TABLE 3 materials
    Schema::create('materials', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();
        $table->string('color');
        $table->string('weight');
        $table->string('brand');
        $table->string('model');
    });



    // TABLE 4 purchase_item_material
    Schema::create('purchase_item_material', function(Blueprint $table) {
        $table->unsignedBigInteger("base_item_id")->unsigned();
        $table->unsignedBigInteger("material_id")->unsigned();
        $table->unsignedInteger("quantity")->default(1);
    });

    Schema::table('purchase_item_material', function(Blueprint $table) {
        $table->foreign('base_item_id')->references('id')->on('purchases_item_base');
        $table->foreign('material_id')->references('id')->on('materials');
    });




    // TABLE 5 purchase_item_service
    Schema::create('purchase_item_service', function(Blueprint $table) {
        $table->unsignedBigInteger("base_item_id")->unsigned();
        $table->string("pn_number");
        $table->text("description");
    });

    Schema::table('purchase_item_service', function(Blueprint $table) {
        $table->foreign('base_item_id')->references('id')->on('purchases_item_base');            
    })


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

custom whereIn laravel 5.1 collection

I'm trying to filter some data in Laravel collection, where i want to use whereIn method. But Laravel 5.1 collections does not provide this method. So i am thinking to use Collection::macro in AppServiceProvider, so i can use this method later to other queries. I do not have that much knowledge about how to create this custom collection method. So it would be helpful if someone point me out where i can get the idea how to create custom collection method, or help me to create one!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/331a8Og
via IFTTT

Use variable in a query to access more data in Laravel

I am trying to convert a simple core php code to laravel but I am not able to successfully convert it. Here let me explain you fully. I have two tables in my database,

(1) mainCatData (2) subCatData

Below are the images if table strucutre

mainCatData Table

subCatData Table

The code I am using in core php is below,

The core php code

Above code is working fine and shows me the data in correct format. (One main category heading and all the sub catgeories heading related to the main catgeory and so on.) The main logic I am not able to transfer in Laravel is how to save the "mainCatData_id" column in a variable and use it to get data from "subCatData" values. Thanks



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

Laravel - Paginate a shuffled array

I want to paginate a shuffled array of elements. I know Laravel Paginator expect a Collection. In more details, I want to shuffle a resultset from the database. Therefore I have the following line of code:

$getallFragen = $frage->getAllFragen2()->shuffle()->all();

This line selects all questions and shuffles the collection.

Furthermore I want to shuffle the answers from the questions, which also works correctly. Then I want to paginate the items with one item per page, which also works properly, but I receive duplicate items in the pagination. First I thought, it has to be the collection, but the collection is built correctly and I don´t know, what the problem could be. I could imagine, that my own paginator is not working the way it should. I also create an array, where I store the items, which are allowed in the exam and then make a collection out of the array to make sure, that there are no duplicate entries.

        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $itemCollection = collect($pruefung);
        $perPage = 1;
        $currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
        $paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);

        $paginatedItems->setPath($request->url());

        return view('pruefungssimulation', ["fragen" => $paginatedItems]);

In the frontend I just use @foreach($fragen as $frage) to get all items out of the collection.



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

What are the ways to use RxPHP in Laravel?

I want to use Rxphp in laravel, i have done many searches but not find any way to use it. There is lot of things about Rxjava in android or Rxjs but not for laravel.



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

Not fetching the image from public folder( https://localhost/storage) in Laravel

I am creating a web app. when i am uploading an image its not able to fetch from the public folder and giving me back a 404 error.When i checked the error its not able to access the http://localhost/storage and through me an error. I have attached the error screenshot please check and help me. Check out the codes. Profile Model:

class Profile extends Model implements HasMedia
{
    use HasMediaTrait;

    public function user()
    {
        return $this->belongsTo(User::class);
    }
public function image()
{
    if($this->media->first())
    {


        return $this->media->first()->getFullUrl('thumb');


    }


    return null;
}

    public function registerMediaConversions(?Media $media = null)
    {
        $this->addMediaConversion('thumb')
        ->width(100)
        ->height(100);
    }
}

ProfileController

public function update(Request $request, Profile $profile)
{
    if ($request->hasFile('image'))
    {
        $profile->clearMediaCollection('images');

        $profile->addMediaFromRequest('image')
                 ->toMediaCollection('images');

    }
    return redirect()->back();
}

Show.blade.php

@method('PATCH')
                        <div class="form-group row justify-content-center">
                            <div class='profile-avatar'>
                                <div onclick="document.getElementById('image').click()" class="profile-avatar-overlay">
                                    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 32 32">

                                        <path d="M18 22.082v-1.649c2.203-1.241 4-4.337 4-7.432 0-4.971 0-9-6-9s-6 4.029-6 9c0 3.096 1.797 6.191 4 7.432v1.649c-6.784 0.555-12 3.888-12 7.918h28c0-4.030-5.216-7.364-12-7.918z"></path>
                                        </svg>

                                </div>
                                <img src="" alt="" >

                            </div>
                        </div>

error image: enter image description here



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

Zipping single files along with a folder using Chumper/Zipper in Laravel

I am trying to zip contents from a folder using Chumper/Zipper library in Laravel. The folder contains following files with a folder:

folder items

But after I am zipping, I am not getting the "temp" folder, but I am getting the content of temp folder. I want the single files as well as the folder. I have tried the following code:

 Zipper::make($makepath)->add($files)->close();

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/320bYhg
via IFTTT

Can not drop a song from iTunes on safari browser

I have created a field for drop a song from local or iTunes using angularjs and laravel. On google chrome iTunes dropping is working. But, it isn't working on safari browser. Anybody knows what should I do ? Thank you. I have added it's view here.]1

<tab heading="Upload New File" select="tabSelected('uploadnew')">
    <div class="input-group">
         <label> Asset Name </label>
         <span class="color-red ng-scope">*</span>
         <input type="text" ng-model="uploadnew.assetName" class="form-control" />
    </div>

    <div class="form-group">
         <label> Notes </label>
         <textarea class="form-control" msd-elastic ng-model="uploadnew.notes"></textarea>
    </div>

     <div class="form-group fileUp">
         <div class="inlinehr"><input type="file" class="ng-pristine ng-valid ng-touched" ngf-select="uploadnew.selectFile($files)" ngf-multiple="false"></div>
         <span class="badge" ng-show="!uploadnew.newFile">No File Selected</span>
          <span></span>
          </div>
     <div>

         <div ngf-drop ngf-select ng-model="uploadnew.droppedFiles" class="drop-box"
        ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true">Drop file here</div>
         <div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
      </div>
</tab>


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

.env file does not exists in laravel

code: public/index.php

<?php
    // $path = base_path() . '/.env';
    if(file_exists('/../.env'))
    {
        echo "yes";
    }
    else
    {
        echo "No";
    }

In this code, I have .env file in my root directory but when I try to know my .env file exists or not then it shows No. I had also tried with base_path() after this it throws 500 error. I don't know why? So, How can I fix this issue? Please help me.

Thank You



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

mercredi 30 octobre 2019

VerifyCsrfToken error with no status or message on line 82 Laravel

In Exceptions/Handler.php i added some logic to send an email with every exception from my flow ( i added this to report method ).

In my flow i have severals forms and from time to time i get an email with an error on line 82 in file: Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php . At this line is this "throw new TokenMismatchException ".

After reading some questions & answers i added csrf token to my forms.

The thing is i can't reproduce this error and the exception doesn't have any error code or message.

Beside that, in laravel.log there's no error about csrf.

My questions are:

  1. Is this error flow breaking? I've made the flow several times and i didn't get any error, but if this exception will be throwed when a customer is in the flow, it will break the flow ( i mean it will be redirected to an error page ) or the client will know nothing?

  2. Why this error is not in laravel.log?

  3. Do you have any idea what can i do to fix this error?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34dQNd1
via IFTTT

Fatal error: Class 'Route' not found in C:\wamp\www\laravel\app\Http\routes.php on line 14

please solve the problem. I can not find a solution in proper. that should be given an above-shown error and that should not solve that time.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/349eD9M
via IFTTT

Laravel fetch raw query result

I don't want laravel to format my query result to an array or object ..etc. All I want, is to run the result set from database and then I will manually do the fetch myself in my custom code.

At the moment, I ran my select query and get my result in an array. The reasons for that, because the result is huge and I want to stream it directly to API.

$result = self::$db->select('select * from customer');

How can I tell laravel, to return my query result set without any format at all?



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

Uncaught SyntaxError: Invalid or unexpected token duplicated

$('#add').click(function () {
      i++;

      // add to button Add to append more input field
      $('#dynamic_field').append(''+
      '<tr id="row'+i+
      '"class="dynamic_added"><td><input type="text" name="title[]" 
        placeholder="Masukan Teks Informasi" class="form-control"></td>' + 
      '<td><button type="button" name="remove" id="' +i+ '" class="btn 
        btn-danger btn_remove">X</button></td>' + 
      '</tr>');
   });

i have a problems with this code:

'"class="dynamic_added"><td><input type="text" name="title[]" 

i dont know what the erros in that line



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

Laravel Eager Load Constraint issue

This is for a HR app I'm working on.

They requested a report to show people who have punched in late. Sure, no problem I thought.

So I have a form with some custom parameters the user can punch in, start_date, end_date, wage, and an array of departments.

public function show()
{
    request()->validate([
        'start_date' => 'required|date|before_or_equal:today'
    ]);

    $start = Carbon::parse(request('start_date'));
    $end = request('end_date') ? Carbon::parse(request('end_date')) : today();
    $wage = request('wage');
    $departments = request('departments');

    $query = EmployeePunch::with([
        'employee' => function($query) use ($wage, $departments) {
            // IF I UN COMMENT THESE, IN THE FILTER BLOCK BELOW, THE EMPLOYEE BECOMES UNDEFINED.
            // if($wage != null) {
            //     $query->where('hourly', $wage);
            // }

            // if($departments) {
            //     $query->whereIn('department_id', $departments);
            // }
        },
        'employee.group',
        'employee.department'
    ])
    ->whereBetween('punch_time', [$start->startOfDay(), $end->endOfDay()])
    // only care about punch in for the day
    ->where('type', 1);

    $results = $query->get();

    $latePunches = $results->filter(function ($i) {
        $day = strtolower($i->punch_time->format('D'));
        $startTime = Carbon::parse(sprintf('%s %s', 
                                            $i->punch_time->format('d-m-Y'), 
                                            $i->employee->group[$day.'_start_time'])
                    );

        return $i->punch_time->isAfter($startTime) 
                && $i->punch_time->diffInMinutes($startTime) >= 5;
    });

    return view('hr.employeeLateReport.show', compact('latePunches'));
}

So, my problem is in my eager loading and I can't figure this out. If I uncomment the filters in the eager loading of employees, in the filter block near the end of the code block, the $i->employee becomes undefined. If omit the filters, everything works peachy. I've checked the queries being produced and it all looks great.

Any help would be greatly appreciated.

Here's the relationship methods

Employee.php

public function punches()
{
    return $this->hasMany(EmployeePunch::class);
}

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

public function department()
{
    return $this->belongsTo(Department::class)->withDefault();
}

EmployeePunch.php

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


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

Custom error message for `requiredIf` validation in laravel

I'm working on a Laravel 5.8 project and trying to show custom validation messages for a validation which uses the requiredIf validation rule.

Here is how I have it set up:

$validation = Validator::make(
    $request->all(),
    [
        ...
        'sum' => [
            Rule::requiredIf(function() use ($request){
                $model = Model::find($request->id);
                return $model->is_special; //returns a boolean value
            }),
            'numeric'
        ],
        ...
    ],
    [
        ...
        'sum.required_if' => 'This cannot be blank',
        'sum.numeric' => 'Must use a number here',
        ...
    ]
);

Now the validation is working correctly and the custom message for the numeric validation shows as should, but the message I get for the requiredIf() method is Laravel's default error message.

I also tried using 'sum.requiredIf' => '...' but that didn't work either and can't seem to find any documentation or example for this scenario.



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

Adding photo display function to the user's model

I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this User:

class User extends Authenticatable implements MustVerifyEmail
{
public function UserProfileImageGallery()
    {
        return $this->hasMany('App\UserProfileImage', 'user_id', 'id')->orderBy('number1')->orderBy('number2')->orderBy('number3')->orderBy('number4')->orderBy('number5')->orderBy('number6')->orderBy('number7');
    }
}

class UserProfileImage extends Model
{
    protected $quarded = ['id'];
    protected $fillable = ['user_id', 'path1', 'number1', 'path2', 'number2', 'path3', 'number3', 'path4', 'number4', 'path5', 'number5', 'path6', 'number6', 'path7', 'number7'];
    public $timestamps = false;
}

I have user list:

$users = User::with('UserProfileImageGallery')->paginate(15);

And I make list:

@foreach ($usersList as $user)
@if ($user->showSecretPhoto == 1)
    // here I want show  $user->UserProfileImageGallery->path7
@else
    $user->UserProfileImageGallery->path1
@endif
@endforeach

How do you embed image (secret or normal) display in a User Model?

I would like to build a function in the model that will choose the right photo for the user. If the user: $ user-> showSecretPhoto has a value of 1 - I want to display his 7th picture: $ user-> UserProfileImageGallery-> path7. Otherwise, I want to display photo 1.

How to do it?



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

Log of Laravel Scheduler

Where do the Laravel stores the log of the scheduler i.e if we set a scheduler at an interval of 2 hours and it has been executed at 12 pm then it should be executed at 2 pm?

How does Laravel know that the scheduler should not be executed at 1 pm?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/321YpO6
via IFTTT

Laravel, redirect unregistered user to login route with parameter

Im using the Laravel base Authentication, when unregistered user attempt to access a link, for example: http://myapp.com/financial/?email=john@web.com

It is redirect to http://myapp.com/login because the user is not registered yet.

My question is: how do i get the url parameter email of the original link (http://myapp.com/financial/?email=john@web.com) of the user tried access in my login page?

Obs: im using Laravel 5.7



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/36hfYNB
via IFTTT

How to make a react-in-laravel project to run on LAN

I finished my project comprising react for front-end and laravel for API server side. I was ever running "npm run dev" until i finished project. Now i would like it to run on my LAN, in that i can use a local address to access the system. How can I Do That Please??



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

Private sub-package 'Class not found' PHP error is fixed after running 'composer dumpautoload'?

I have a Laravel 5.8 project that is dependent on a private package from a private repository.

The private package is dependent on another private package from the same repository.

When I run composer install, the sub-package is intalled and shows in the vendor folder, but I still get a PHP exception 'Class not found' until I run composer dumpautoload

The following questions don't touch on my issue:

Composer package class not found

Composer won't install private package dependencies

Laravel : Code worked after composer dumpautoload

Google has been unable to help me on this one

Project composer.json

{
    ...
    "repositories": [
        {
            "type": "composer",
            "url": "https://PRIVATE-REPOSITORY"
        }
    ],
    "require": {
        "php": ">=7.0",
        "PRIVATE-PACKAGE": ">=1.0.0"
    }
    ...
}

Private package composer.json

{
    ...
    "require": {
        "php": ">=7.0.0",
        "PRIVATE-SUB-PACKAGE": ">=1.0.0"
    },
    "autoload": {
        "psr-4": {
            "PACKAGE\\NAMESPACE\\": "src/"
        }
    }
    ...
}

Private sub-package composer.json

{
    ...
    "autoload": {
        "psr-4": {
            "SUBPAKCAGE\\NAMESPACE": "src/"
        }
    }
    ...
}

I am not having any problems installing the sub-package, as other questions have mentioned, it is the autoloading that seems to be the issue.

The PHP error message

Message: Class 'SUBPACKAGE\NAMESPACE' not found

is coming from code inside the first package, where the sub-package is used.

I know the PHP syntax is correct because I am able to fix the error with

composer dumpautoload -o

but why is it necessary?

I expect composer install or composer update should be sufficient; I have no problem with sub-dependencies from external packages.

Am I missing anything here?



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

Redirect to previous url except in other urls

I want to redirect a user to the previous url when he login except when a user clicks the reset password . So if a user clicks reset password then tries to login it shouldn't redirect back to reset password page. So far when a user clicks reset password and then tries to login it I get this error The GET method is not supported for this route. Supported methods: POST.. How can I redirect to previous url excepts in other urls like(reset-password)?

I have tried this session(['link' => url()->previous()])->except('password-reset'); and I got an error Call to a member function except() on null

LoginController

 public function showLoginForm()
 {
 session(['link' => url()->previous()]);
 return view('auth.login');
 }

Route

 Route::post('password-reset', 'Auth\ForgotPasswordController@sendPasswordResetToken')->name('password.reset');


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

Using two variable how to access controller function

I want to access a controller function from blade file in laravel.

My Code:

Blade.php

use App\Http\Controllers\myController;
$newControl = new myController;

$function = 'myfunction()';

echo $newControl->$function;


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

laravel links() returns empty htmlstring even though there are more data

links() returns empty HtmlString

links() works fine in other blades with other controllers.
I tried render() but not working as well.

$result = DB::table(some table)->
some queries
->orderByRaw('start_time')
// ->paginate(20);
->get();
 dd($result);
Collection {#357 ▼
  #items: array:1152 [▶]
}

if I link() or render(), it shows empty even though there are more than 1k rows.
It shows 20 rows in blade, but only paginators.

$result = DB::table(some table)->
some queries
->orderByRaw('start_time')
->paginate(20);
dd($result->links());
HtmlString {#348 ▼
  #html: ""
}

HtmlString should show listing below that <ul> like that because I have many rows..
Can anybody help what could be problem?

HtmlString {#328 ▼
  #html: """
    <ul class="pagination">\n


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34kiDEB
via IFTTT

Reuse controller action but modify response in Laravel

Assume I have a base controller which return json response as

class BaseController extends Controller {

    public function test(Request $request) 
    {
        ..
        $data = ...
        return response()->json(['data' => $data);
    }          
}

Now I have another controller which extends from BaseController and want to reuse the test action

class MyController extends BaseController {

    public function test(Request $request) 
    {
        ..
        $data = parent::test($request);
        $data = $data->getData();

        $data->foo = 'bar'; // customize

        return response()->json(['data' => $data);
    }          
}

Are there any better way to rewrite the above codes?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/31Tq6IY
via IFTTT

How to fix "failed to open stream" error in Laravel project?

I want to upload image file to server. And I have failed to open stream: HTTP wrapper does not support writeable connections" error in "move_uploaded_file" function. How can I fix it?

$image_src = $_FILES['ex_image']['tmp_name'];
$src = asset('assets/images/excavator/'.$title.'.png');
move_uploaded_file($image_src,$src);


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34f3zrK
via IFTTT

How to deal with conditioned based validation in laravel?

I have a situation and unfortunately not sure how to sort it out in proper way. I have below script

$validator = Validator::make(
    $request->all(), 
    [
        'game_id' => 'required|integer'
    ],
    $messages
);

if ($validator->fails()) {    
    $response = $validator->messages();
}else{
    $response = $gameService->setStatus($request);
} 

Now each game has different type, I wanted to add validation on behalf of type. For example if a game is Task Based then I would add validation for time which would be mandatory only for Task based game otherwise it would be an optional for other types.

I have three types of games

1 - level_based 2 - task_based 3 - time_based

In the type table, each game has type.

So is there any way to add validation? I want to do it, inside validation function.

Thank you so much.



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

In docker composer container raise error : Carbon 1 is deprecated

I tried to run under docker my laravel 5.5 / postgres 9 app and in composer container I got error :

Carbon 1 is deprecated, see how to migrate to Carbon 2. https://carbon.nesbot.com/docs/#api-carbon-2 You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.

My composer.json:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "barryvdh/laravel-debugbar": "^2.3",
        "graham-campbell/markdown": "^8.0",
        "intervention/image": "^2.3",
        "khill/lavacharts": "3.0.*",
        "laravel/framework": "5.5.*",
        "laravel/socialite": "^3.0",
        "laravel/tinker": "~1.0",
        "laravelcollective/html": "^5.4.0",
        "nwidart/laravel-modules": "^2.2",
        "doctrine/dbal": "~2.5",
        "wboyz/laravel-enum": "^0.2.1"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0",
        "stolz/laravel-html-tidy": "^0.1.1",
        "xethron/migrations-generator": "^2.0",
        "filp/whoops" : "~2.0" 
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "Modules\\": "Modules/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ],

        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]

    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

docker-compose.yml :

version: '3'

services:

    web:
        build:
            context: ./web           # directory of web/Dockerfile.yml
            dockerfile: Dockerfile.yml

        environment:
            - APACHE_RUN_USER=#1000

        container_name: lprods_web

        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        ports:
            - 8086:80
        working_dir: ${APP_PTH_CONTAINER}



    db:
        image: postgres:9.6.10-alpine
        container_name: lprods_db
        ports:
            - '5433:5432'
        restart: always
        environment: 
            POSTGRES_USER: 'postgres'
            POSTGRES_PASSWORD: '1'
            POSTGRES_DB: 'wprods'
        volumes:
            - ./init:/docker-entrypoint-initdb.d/


    adminer:
        image: adminer
        container_name: lprods_adminer
        restart: always
        ports:
            - 8087:80
        links:
            - db

    composer:
        image: composer:1.6
        container_name: lprods_composer
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: composer install  --ignore-platform-reqs

and web/Dockerfile.yml :

  FROM php:7.1-apache

    RUN apt-get update && \
    apt-get install -y \
    python \
    libfreetype6-dev \
    libwebp-dev \
    libjpeg62-turbo-dev \
    libpng-dev \
    libzip-dev \
    nano \
    git-core \
    curl \
    build-essential \
    openssl \
    libssl-dev \
    libgmp-dev \
    libldap2-dev \
    libpq-dev \
    netcat \
    sqlite3 \
    libsqlite3-dev \
    && git clone https://github.com/nodejs/node.git \
    && cd node \
    && git checkout v12.0.0 \
    && ./configure \
    && make \
    && make install

    RUN npm install cross-env

    RUN  docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-webp-dir=/usr/include/  --with-jpeg-dir=/usr/include/


    RUN  docker-php-ext-install gd pgsql pdo_pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
    && a2enmod rewrite

    COPY virtualhost.conf /etc/apache2/sites-enabled/000-default.conf

I am not sure which steps have I to take? To add command

RUN ./vendor/bin/upgrade-carbon

In the end of web/Dockerfile.yml file ?

Thanks!



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

how to dynamically option the selected in html just using php?

I'm trying to dynamically the select option selected just using php in laravel but I'm getting this error:

Use of undefined constant selected - assumed 'selected' (this will throw an Error in a future version of PHP) (View: C:\xampp\htdocs\laralast\resources\views\view.blade.php)

below is my view blade

<select class="form-control" name="assign_to" id="assign_to">
    <option selected disabled>Select support</option>
    @foreach($supports as $support)
    <option value="" ></option>
    @endforeach
</select>

Can you help me with this.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/332XoGY
via IFTTT

Summary with pagination in laravel grid view

is there any way to show summary with pagination in laravel gridVIew like below

page: 1234 summary 1-10 of 100



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

mardi 29 octobre 2019

how can i get user details from google after sign in through my app by using php curl without using google api in code

hello guys i am new here and i want to know about how can i get the user details after sign_in from my app by using google sign_in method with core php. All i want to know is that when i logged in with my google id from third party login in my app i want Json data of user profile detail.

I have tried the socialite and get the solution but i do want it to get done with core php method

Here is my redirect to google method :-

public function redirectToGoogle()
{
$url = 'https://accounts.google.com/o/oauth2/v2/auth?scope='.urlencode('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email').'&redirect_uri='.urlencode(env('GOOGLE_REDIRECT')) . '&response_type=code&client_id=' . env('GOOGLE_CLIENT_ID') . '&access_type=online';

   return redirect($url);
}

And this is my callback method:-

public function callback(Request $request)
{
  $url = $request->getRequestUri();
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL,$url);
  $result=curl_exec($ch);
  curl_close($ch);
  var_dump(json_decode($result, true));
}

From this code i get null value as output, but i accepted json data of logged in user as result



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32ZaepK
via IFTTT

how timestamp's timezone works in a database and/or Laravel

I have a question regarding timezone for timestamps.

How the timezone in app.php is used? I realized that the behavior is different if I create a timestamp using Carbon or if I query the value (timestamp) from the DB.

Note: My MySQL use system's timezone which is GMT+8 or Asia/Kuala_Lumpur.

  1. Example #1
    • Set timezone="UTC" in app.php
    • Create a Carbon instance
>>> new Carbon\Carbon;
=> Carbon\Carbon @1572404830 {#3496
     date: 2019-10-30 03:07:10.625282 UTC (+00:00),
   }
>>>
  1. Example #2
    • Set timezone="Asia/Kuala_Lumpur" in app.php
    • Create a Carbon instance
>>> new Carbon\Carbon;
=> Carbon\Carbon @1572404816 {#3520
     date: 2019-10-30 11:06:56.316851 Asia/Kuala_Lumpur (+08:00),
   }

For example #1 and #2, this is for me, expected. You got different value based on the timezone. Things got a little weirder (at least for me), when we query a timestamp from the DB.

  1. Example #3
    • Set timezone="UTC" in app.php
    • Query from DB
>>> RefCyberCity::whereDataSource('ccms')->take(1)->first()->updated_at
=> Illuminate\Support\Carbon @1572083605 {#3531
     date: 2019-10-26 09:53:25.0 UTC (+00:00),
   }
  1. Example #4
    • Set timezone="Asia/Kuala_Lumpur" in app.php
    • Query from DB
>>> RefCyberCity::whereDataSource('ccms')->take(1)->first()->updated_at
[!] Aliasing 'RefCyberCity' to 'App\RefCyberCity' for this Tinker session.
=> Illuminate\Support\Carbon @1572054805 {#3491
     date: 2019-10-26 09:53:25.0 Asia/Kuala_Lumpur (+08:00),
   }

We can see that both output 2019-10-26 09:53:25.0 but the timezone is different.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32YfxFH
via IFTTT

can laravel be used for only PHP. if yes then what other framework is good for java

question about laravel about laravel framework and its usage



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

Laravel with Litespeed and Apache2 and ProxyPass gives a 403 after login

I have a Laravel project set up on OpenLitespeed server on a port. The IP address is 127.0.0.1:8016. I am using apache2 reverse proxy to pass requests to the OpenLitespeed server. The Laravel application works okay but after logging in I get a Laravel's 403 on all the pages that require authentication to view. I have even tried stopping the OpenLitespeed server and moving the project to apache2 but I still get the same problem. Both apache2 and OpenLitespeed are running on the same server. How can I fix this?

This is my apache conf file

<VirtualHost *:80>
    ServerAdmin admin@mysite.com
    ServerName mysite.com
    ServerAlias *.mysite.com
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8016/
    ProxyPassReverse / http://127.0.0.1:8016/
    ProxyPassReverseCookieDomain .mysite.com 127.0.0.1
    ErrorLog "logs/mysite.com-error.log"
    CustomLog "logs/mysite.com-access.log" common
</VirtualHost>

This is my Laravel's trustedproxy.php

return [

        'proxies' => "127.0.0.1",    
        'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,

    ];


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

How to call out the "description" to replace the "parent_id" in laravel?

so here is my question, i have done everything and my senior request me to replace the parent_id now into description as the coder know what is the integer number represent but the users doesn't know. Here is the picture My current view looks like !

As you can see inside the red column, there are two id : 1.( 999162, Testing3, Test3, 999161, active ) and 2.( 999163, testing4, test, 999162, active )

My desired output is the 1.( 999161 calls the 999161 description instead of id ). Lets take 999163 as example : the desired output should be like 999163, testing4, test, test3, active.

I don't know how to call the description to replace the parent_id,can someone help ?

 <div class="row">
    <div class="col-md-12">
        <br />
        <h3 align="center">Category Data</h3>
        <br />
        @if($message = Session::get('success'))
            <div class="alert alert-success">
                <p></p>
            </div>
        @endif
        <div align="right">
            <a href="" class="btn btn-primary">Add</a>
            <br />
            <br />
        </div>
        <table class="table table-bordered table-striped">
            <tr>
                <th>Id</th>
                <th>Code</th>
                <th>Description</th>
                <th>Parent</th>
                <th>Status</th>
                <th>Action</th>
                <th>Action</th>
            </tr>
            @foreach($category as $row)
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>

                    <td><a href="" class="btn btn-warning">Edit</a></td>
                    <td>
                        <form method="post" class="delete_form" action="">
                            
                            

                            <input type="hidden" name="_method" value="DELETE"  />
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>
    </div>
</div>


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

What happened to Pushmix

Just recently i had setup account with pushmix in other to send notifications to my laravel app, everything was working nicely , but this morning i tried to access my pushmix account and all the website is showing 404 not found,anyone knows what happened to pushmix, if they are upgrading or something else, or anyone knows an alternative i can use to send push notifications in my web app that would be as effective and free like pushmix.

I tried using other browsers and other devices to access their website but to no avail.



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

Sorting results in Laravel

I am beginner in Laravel. I have project in Laravel 5.8.

I have this code:

Schema::create('user_profile_images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('path1', 255);
            $table->smallInteger('number1')->default(0);
            $table->string('path2', 255);
            $table->smallInteger('number2')->default(0);
            $table->string('path3', 255);
            $table->smallInteger('number3')->default(0);
            $table->string('path4', 255);
            $table->smallInteger('number4')->default(0);
            $table->string('path5', 255);
            $table->smallInteger('number5')->default(0);
            $table->string('path6', 255);
            $table->smallInteger('number6')->default(0);
            $table->string('path7', 255);
            $table->smallInteger('number7')->default(0);
            $table->ipAddress('ip');
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

User.php

public function UserProfileImageGallery()
    {
        return $this->hasMany('App\UserProfileImage', 'user_id', 'id');
    }

I need to display the user's path (path1, path2, path3, path4 ... path7) in order of number (number1, number2, number3 ... number7).

for example:

$path1 = "www1";
$number1 = 2;
$path2 = "www2";
$number2 = 1;
$path3 = "www3";
$number3 = 3;

In result I need:

www2, www1, www3

How can I make it?



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

How to display included files in multiple navigation pages

I intend to display a jumbotron in multiple pages of my application, I have been able to display it on the home page, how do I replicate such on other pages.

I'm using Laravel 5.8 and Bootstrap 4 .It displayed on the default home page('/'), I have tried replacing ('/') with the page name in the route file which is 'training' (from ...->name('training')) i.e but it didn't display. I have also tried replacing it with '/Training' and 'pages/training' but it still didn't work.

The code in the master blade file (resources/views/layout/app.blade.php) is;

@if (Request::is('training'))
     @include('inc.showcase')
@endif

The code for the showcase file (resources/views/inc/showcase.blade.php) is;

<div class="jumbotron text-center">
    <div class="container">
        <p>Welcome to My Page</p>
    </div>
</div>

The code for the child blade (resources/views/pages/training.blade.php) is;

@extends('layout.app')

@section('content')
    <h1>Training</h1>
@endsection

That of the route file (routes\web.php) is;

Route::get('/Training', 'PageController@getTraining')->name('training');

And that of the controller (app\Http\Controllers\PageController.php) is;

public function getTraining(){
        return view('pages/training');
    }

I expect the Jumbotron to display in the training page but nothing displays at all, except for the home page when i use (/)



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

Get user ID while login from the LoginController.php laravel

I want to get user id immediately after the user has logged in. I have tried getting the user id using request but its not working. It prints the following error:

"Too few arguments to function App\Http\Controllers\Auth\LoginController::redirectTo(), 0 passed in C:\Users\owden\Documents\donation_system\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RedirectsUsers.php on line 15 and exactly 2 expected"

Below is my LoginController.php.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Support\Facades\Auth;

use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected function redirectTo(Request $request, $id)
    {
        if(Auth::user()->usertype == 'admin')
        {
            return 'dashboard';
        }
        elseif(Auth::user()->usertype == 'organization') {
            $user = User::find($id);
            return redirect ('/profile/{'.$id.'}');
        }else{
            return 'approval';
        }
    }
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

And the routes:

Route::get('/profile', 'ProfilesController@index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfilesController@edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfilesController@update')->name('profile.update');


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

Displaying posts in custom formation

I would like to output posts in order provided by this image (every 3 posts)

posts formation that is needed

here is my blade code:

<section class="blog_area p_120">
    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <div class="blog_left_sidebar">
                    @foreach ($raksti as $raksts)
                    <article class="blog_style1">
                        <div class="blog_img">
                            <img class="img-fluid" src="" alt="">
                        </div>
                        <div class="blog_text">
                            <div class="blog_text_inner">
                                <div class="cat">
                                    <a class="cat_btn" href="#"></a>
                                    <i class="fa fa-calendar" aria-hidden="true"></i> 
                                    <i class="fa fa-comments-o" aria-hidden="true"></i> 05
                                </div>
                                <a href="#">
                                    <h4></h4>
                                </a>
                                <p></p>
                                <a class="blog_btn" href="#">Lasīt vairāk</a>
                            </div>
                        </div>
                    </article>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</section>

For those small blocks the "article" tag have class ="blog_style1 small"

I guess that there need to work with a "for" loop, so can anyone help me to achieve this task and explain a little how that works?



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

Laravel 5.4 pushing new object to array

I am trying to push an object to a user model.

The user model, has the below parameter:

User.posts.

Where posts is an array.

First I tried the below:

$user->posts()->save($Post);

This didn't add the new Post object to the user.posts (but it didn't return an error).

I also tried $user->posts()->push($Post);

and $user->posts = array_add($Post)...but this is requiring three parameters.

Sorry, I am new to laravel...How to push an object instance to the array (posts) of the user model?

Thanks,



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

simple laravel echo route takes 30s to return response

I built a project on laravel 5.7, now while developing the project worked just fine as it should,after that i took some time off some other developers worked on it and when i came back i had this weird issue of extremely slow response time, now the code works fine on live environment, but on localhost i face extreme slow response times, i added laravel debugger to the project and created a simple route which return "here2" it took more than 30s please view the screen shot

laravel debugger screenshot

i was working with WAMP stack when i faced this issue, i basically had two issues artisan commands taking long time to respond and the code itself, when i shifted over to LAMP stack, i was amazed the two issues i mentioned above was replicated exactly the same in Ubuntu, i though it might be an OS, but its not,

i even installed a fresh copy of laravel alongside this project and that works just fine,

i tried every possible command out their to resolve this issue like

composer dump-autoload  
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan config:cache
php artisan route:cache
php artisan optimize

i even deleted vendor and there-installed it but the issue remains the same, i did R&D on it for days but still couldn't find a solution, can anyone help me out?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/36bk4a9
via IFTTT

Can't "except" category in Posts controller

I have table with ID, Category_id, title etc... I need to output every category except nr. "10"

I allready outputted only category_id = 10, but dont know how to output others except category 10.

Here is controller:

public function index()
{   
    $sponsored = Raksti::where('category_id', '10')->get();
    $kat = RakstuKategorijas::all();
    $raksts = Raksti::all();
    $raksti = collect($raksts)->except('category_id', '10');

    return view('home',[
        'sponsored' => $sponsored,
        'kat' => $kat,
        'raksti' => $raksti,
    ]);
}
}

I don't get any errors - code output all posts including category 10



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

Undefined property in models laravel

I want to check the product if is liked or not, if the product is liked it will show liked else it will be like. I'm getting an error Undefined property: stdClass::$isLiked I use model to check if the product is liked in the view, how can I fix the problem?

Product.php

 public function getIsLikedAttribute()
 {
    $like = $this->likes()->whereUserId(Auth::id())->first();
    return (!is_null($like)) ? true : false;
 }

Blade file

@foreach($products as $product)
  <h2>USD </h2>
   <h2></h2>

@if ($product->isLiked)
    liked
   @else
    like
   @endif
@endforeach


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

Is there any way to set user permission on specific CMS Pages on OctoberCms?

I have created an website with OctoberCms and there are some CMS pages like 'about us', 'contact us' and many more.

I wanna create a role for such an user who will only be able to edit 'about us' page but not 'contact us' page.

Any suggestion is appreciated. Thanks in advance.



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

How to get details of team boards' cards like which member archived it

I am using trello api in laravel to get boards of a team and want to check which member archived the card of team's board. But I can't find any solution in trello api documentation. Please help me !



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

how to get image from one laravel project to another laravel project?

I want to get an image to show on the main website. i already uploaded the image from admin side and don't know know how to get it on main website, since both admin and main website are different projects and one is running on 127.0.0.1:8000 (main website) and 127.0.0.1:8080(admin panel).



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34e0sQy
via IFTTT

Laravel SESSION DRIVER file and database

I always encounter this error in my laravel apps.It seems like my app is looking for SESSION table. But my session driver is file.

Error Code : 942 Error Message : ORA-00942: table or view does not exist Position : 29 Statement : select * from (select * from "SESSIONS" where "ID" = :p0) where rownum = 1 Bindings : [ 6FIQK2ZudGtfcRksXb0E9lIJtcq3OcNIsjSWNAU1] (SQL: select * from (select * from "SESSIONS" where "ID" = 6FIQK2ZudGtfcRksXb0E9lIJtcq3OcNIsjSWNAU1) where rownum = 1)

This is the .env configuration

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

Same with the session.php

'driver' => env('SESSION_DRIVER', 'file'),

How to remove this error. Which php file should i edit.



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

Laravel - Api: Find online users and send notifications

I am building a web service for an android application. When a request comes to the server, I need to send notification to some online users who satisfy some criteria. So, in the first place, I need to know which users are online, get their attributes in database then find the appropriate ones and send notification.

Finding the online users and sending notification are what I have no idea how to implement. I would be appreciated for any suggestion.

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34gTSJr
via IFTTT

BadMethodCallException : Method Illuminate\Database\Query\Builder::offers does not exist

I am trying to do php artisan db:seed on Laravel 5.6.39 and getting an error:

BadMethodCallException : Method Illuminate\Database\Query\Builder::offers does not exist.

Offer Model code:

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

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

}

Task Model

public function offers()
{
    return $this->hasMany(Offer::class);
}

Databaseseeder file

factory(App\Task::class, 10)->create()->each(function ($task) {
    return $task->offers()->save(factory(App\Offer::class)->make());
});

What am I not doing right?



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

How can I save a form as a file in Android or in Website?

The project I am working on involves android application communicating with web page.

Pictorial representation of app interface.

There is a form that takes input from users and there is a canvas in that form that takes signature from user. I am saving canvas data as image. Is there any way that I can save the whole form as a single file ?

  • I need to be able to save entire form including signature in a single file.
  • I need to be able to fetch that data and display it to user again.

I will appreciate the solution in either end, whether it be in android or in website. I am using laravel 5 to develop website.

I tried searching the question (yes even in google and youtube) but was not able to find the solution i required. Below are the few links i stumbled on:

How can I save a styled DIV as a PDF

Android development: How can i store pdf file in a android app as local file and read that pdf file?

Save a <canvas> as a file in a form



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

lundi 28 octobre 2019

Join Within Join and Count of Records SQL in Laravel

I've gotten stumped by this SQL query for my Laravel project, so first I'll describe the relationships.

cartages has the following fields: id, date_ending

cartage_batches has the following: id, cartage_id

cartage_items has the following: id,batch_id,amount

What I would like to be able to do is query the cartage table to be grouped into year and month pulled from the date_weekending field. But also grab the count of cartage_items in the cartage_batches in each months cartages.

I know it would involve a join within a join but I'm not entirely certain how to accomplish that best from within Laravel.

I'd appreciate any and all help. Thank you!



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

Doesnthave inside wherehas with hasMany relation

Good day, so I have a model called "Recibo", on this model I have a relationship hasMany like this:

public function  recaudarRecibo(){
     return $this->hasMany('App\RecaudaRecibo','ID_RECIBO','ID_RECIBO');
 }

Because a "RECIBO" (receipt) could be in one or more "RECAUDACION" (takings), then, a "RECAUDACION" could pay one or more "CUOTA"(dues) so on the model "RecaudaRecibo" I have another relationship:

public function compromisoCuotaPago(){
    return $this->hasMany('App\CompromisoCuotaPago', 'ID_RECAUDA', 'ID_RECAUDA')->where('SEC_RECAUDA', $this->SEC_RECAUDA)->where('ID_RECIBO', $this->ID_RECIBO);
}

->where('SEC_RECAUDA', $this->SEC_RECAUDA)->where('ID_RECIBO', $this->ID_RECIBO);

Here is the fun part: Currently I'm developing a report, this is my eloquent query for now:

$recaudaciones = Recibo::whereHas('recaudarRecibo', function($q) use ($anio){
                $q->whereRaw("YEAR(FEC_PAGO) = $anio")
                ->whereRaw("IND_DIR_EXT = 'D'")
                ->doesntHave('compromisoCuotaPago')
                ->where("COD_ESTADO_PAGO", 1);
            })->where("COD_TIPO_APORTE", 1)
            ->where("ID_LINEA_INGRESO", $lineaIngreso->ID_LINEA_INGRESO)
            ->get();

The problem is that whereHas('recaudaRecibo') can't have a relationship 'compromisoCuotaPago' but when I print the query this happens:

select *
 from `M_RECIBO` where 
 exists (
 select * from `R_RECAUDA_RECIBO` where `M_RECIBO`.`ID_RECIBO` = `R_RECAUDA_RECIBO`.`ID_RECIBO` and YEAR(FEC_PAGO) = 2019 
 AND MONTH(FEC_PAGO) = 10 and IND_DIR_EXT = 'D' and not exists 
 (select * from `R_COMPROMISO_CUOTA_PAGO` where `R_RECAUDA_RECIBO`.`ID_RECAUDA` = `R_COMPROMISO_CUOTA_PAGO`.`ID_RECAUDA` 
 and `SEC_RECAUDA` is null and `ID_RECIBO` is null) and `COD_ESTADO_PAGO` = 1) and `COD_TIPO_APORTE` = 1 and YEAR(FEC_VCTO) = (2019 - 1) 
 and `ID_LINEA_INGRESO` = 4;

and SEC_RECAUDA is null and ID_RECIBO is null

So, the relationship is not right, It's good when I use it from an object but when I make a query like that it gives null. Any ideas?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/36e8kn5
via IFTTT

Heroku website deployment error: "Forbidden You don't have permission to access this resource."

I'm deploying my Laravel website to Heroku where I am getting a Forbidden You don't have permission to access this resource. error as soon as I visit my deployed website.

Here is an image showing the error:

I have tried changing the permission of my Laravel root folder using the: chown -R 777 command to change the permissions for every user to be able to read and write, with the hope to work, but it didn't. Next, i tried changing the permissions from the .htaccess file by writing Require all granted which also didn't work unfortunately.

For more information, here is my .htaccess file

Require all granted

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

php_value upload_max_filesize=32M
php_value post_max_size=32M
php_value max_execution_time 300
php_value max_input_time 300

When I visit the domain, the website should be displayed. I also tried to deploy more Laravel applications with the hope to see whether they would work, but still I get the same Permission issue.



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

Call a partial from a text that is stored in a database in laravel

I have a partial, that I can call with @include('partials/_tags') in a blade file. At the moment I create content using a rich-text-editor and store the data in the database. This is working fine. Now, I also want to insert partials into the the text-editor so that the partials are then displayed. Unfortunately, only the text @include('partials/_tags') is displayed, not the partial itself. I call the content from the database and display it then like the following.

@extends('main')
@section('title','Contact us')

@section('content')
  @foreach($pagedata as $data)
    <!-- Display the content including the partial here -->
    {!! $data->content !!}<br>
  @endforeach
@endsection

The content with the partial information is stored in the database like the following.

Test content <br><div>@include('partials/_tags')</div><div><br></div>Further content

How can I achieve, that the partial is displayed and not the code that calls the partial?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32QGo6G
via IFTTT

Facebook page API to update hours

I want to update the facebook page Hours section using Graph API. How to update "No hours available" and "Open for selected hours" section.

   $hours = {"mon_1_open":0,"mon_1_close":0,
   "mon_2_open":0,"mon_2_close":0,
   "tue_1_open":0,"tue_1_close":0,
   "tue_2_open":0,"tue_2_close":0,
   "wed_1_open":0,"wed_1_close":0,
   "wed_2_open":0,"wed_2_close":0,
   "thu_1_open":0,"thu_1_close":0,
   "thu_2_open":0,"thu_2_close":0,
   "fri_1_open":0,"fri_1_close":0,
   "fri_2_open":0,"fri_2_close":0,
   "sat_1_open":0,"sat_1_close":0,
   "sat_2_open":0,"sat_2_close":0,
   "sun_1_open":0,"sun_1_close":0,
   "sun_2_open":0,"sun_2_close":0}

This my hours' array.



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

How replace input name in Laravel validation?

I am beginner in Laravel. I use in my project Laravel 5.8.

I have this code:

<form  method="post" name="contactformXX"
action="" enctype="multipart/form-data">

<input type="text" value=""
name="form_link1" maxlength="150">
</form>

I show error with this code:

@if ($errors->any())
<div class="row alert alert-danger">
<li>Uzupełnij poprawnie wszystkie wymagane
pola! </li>
</div>
@endif

When I post empty form I have error:

"Uzupełnij poprawnie wszystkie wymagane pola! Format form link1 jest nieprawidłowy."

How can I replace name input traditional name: "form link1" => "facebook url"?



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

Call to undefined method App\Product::getProductStock()

BadMethodCallException Call to undefined method App\Product::getProductStock() This error occurred while accessing the model function in controller

My Controller

        $user_id = Auth::user()->id;
        $user_email = Auth::user()->email;


        // To prevent out of stock material from ordering
        $userCart=DB::table('cart')->where('user_email',$user_email)->get();
        // echo "<pre>"; print_r($userCart); die;
        foreach ($userCart as $cart) {

            $product_stock= Product:: getProductStock($cart->product_id,$cart->size);
            echo $product_stock;

            if ($product_stock==0) {
                return redirect('/cart')->with('flash_message_error','Product is Stock sold out. Buy another product');
            }

            if ($Cart->quantity>$product_stock) {
                return redirect('/cart')->with('flash_message_error','Reduced product stock & Try Again');
            }

        }

Model

public static function getProductStock($product_id,$product_size)
{
    $getProductStock=ProductsAttribute::select('stock')->where(['product_id'=>$product_id,'size'=>$product_size])->first();
    return $getProductStock->stock;
}


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

BadMethodCallException Method App\Http\Controllers\TaskController::destory does not exist

I'm using laravel 5.8 and this is my routes/api.php file.

Route::get('/tasks', 'TaskController@index')->name('tasks.index');
Route::post('/tasks', 'TaskController@store')->name('tasks.store');
Route::get('/tasks/{task}', 'TaskController@show')->name('tasks.show');
Route::put('/tasks/{task}', 'TaskController@update')->name('tasks.update');
Route::delete('/tasks/{task}', 'TaskController@destory')->name('tasks.destroy');

And this is function destroy() inside TaskController,

public function destroy(Task $task)
{
    $task->delete();

    return response()->json([
        'message' => 'Successfully deleted task!'
    ]);
}

But when I call the function I get this error,

BadMethodCallException Method App\Http\Controllers\TaskController::destory does not exist.

It would be really great if someone can help.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/368ZDui
via IFTTT

How can i use passed array to selected option then use it to update my chart data in js?

Trying to make dynamic data from controller pass to view in selected option then use it in js to update my chart data

//FROM CONTROLLER TRYING TO PASS ARRAY To select option then use that value to update datasets

$keyboard = array(1,2,3,4,5,6,7,8,9,10,11,12);
$mouse    = array(5,3,2,1,4,6,7,10,12,13,14);
$monitor  = array(5,4,3,2,1);

//SELECT OPTION

  <option value="{ json_encode($keyboard) }">Keyboard</option>
  <option value="{ json_encode($mouse) }">Mouse</option>
  <option value="{ json_encode($monitor) }">Monitor</option>

//CHART

        data: {
            labels:['January', 'February', 'March','April','May','June','July','August','September','October','November','December'],
            datasets: [{}]
        },
        options: {
          title: {
            display: true,
            text: ['ITEM REPORT']
        },
        legend: {
            display: false
            }
        }
    });

// This.value has the value of selected itemvalue { json_encode($) }

// example i want to get { json_encode($monitor) } which is array(5,4,3,2,1);

     $("select").on('change', function() {  

      var passdata = this.value;

        chart.data.datasets = [{data: [passdata]}]
        chart.update()
    });
});

https://jsfiddle.net/Lt27v6ru/2/ (this is link for jsfiddle)



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

How to multiply decimal value in laravel?

I want to multiply quantity and price. Both are decimal value .

$grand_total = $grand_total + (decimal('$result->balance',15,2) * decimal('$result->purchase_price',15,2));

What is the right way ?



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

dimanche 27 octobre 2019

Why am I getting a carbon instance from a collection?

I have this collection of riv_queries.

$riv_queries = RivQuery::where('id', Auth::user()->id)->first();
RivQuery {#157 ▼

#attributes: array:12 [▼
    "id" => 88
    "riv_from" => "2019-10-15"
    "riv_to" => "2019-10-15"
    "department_id" => 109
    "type_id" => 0
    "record_type_id" => 1
    "cal_year" => 2018
    "accordion" => 0
    "city_id" => 0
    "region_id" => 8
    "prov_id" => 837
    "tx_date" => "2019-10-15"
  ]

My problem is whenever I want to get 'riv_to' or 'riv_from' I always get this as a result

dd($riv_queries->riv_to);
Carbon @1571068800 {#638 ▼
  date: 2019-10-15 00:00:00.0 Asia/Manila (+08:00)
}

But i only expect result like this

"2019-10-15"

What am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/367965v
via IFTTT

@Yield doesnt seem to work on Laravel Snippets

Im trying to make things work for a laravel app page but it seems like it gave me an error. The following below are my codes. NOTE: I have already installed the extension for Laravel Snippet.

enter image description here

Can you guys give me advise on this? thank you.



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

How to create a subdomain automatically in Laravel

I am creating a SaaS app using Laravel and I am trying to create subdomains for each user signup. For example, 1. User comes to www.somewebsite.com and signs up 2. During the signup user provides their business name e.g. mybiz 3. I want my Laravel app to dynamically create a dynamic subdomain mybiz.somewebsite.com 4. Whenever user logs into the website they are automatically redirected to mybiz.somewebsite.com and they stay on this URL during the entire session.

At no time I as an admin would like to create a subdomain manually. I am using Apache on Ubuntu for my Laravel install.



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

how can i fix "Trying to get property of non-object"

i have a favorite list in my website for the users and they can add their favorite house to the wishlist

it goes well but he can not see the wishlist page and an error comes like this:

Trying to get property 'image' of non-object

it's my relations

class Home extends Model {

protected $guarded = [];



public function favorite(){

    return $this->hasMany(favorite::class,'house_id');
}

}

class favorite extends Model {

protected $guarded = [];

public function house(){

    return $this->belongsTo(home::class);
}

}

my index function in controller:

public function index() {

     $favorite=favorite::where('user_id',auth()->user()->id)->get();

     return view('favorite.index',compact('favorite'));
}

my index:

@foreach($favorite as $fav)

                                <tr>
                                    <td>
                                        <a href="property-detail.html"><img src="" alt=""
                                                                            width="100"></a>
                                    </td>
                                    <td><a href="property-detail.html"></a></td>
                                    <td>خانه خانواده</td>
                                    <td>اجاره</td>
                                    <td>
                                        <div class="price"><span></span><strong>تومان</strong>
                                        </div>
                                    </td>
                                    <td>
                                        <a href="#" class="action-button"><i class="fa fa-ban"></i> <span>حذف</span></a>
                                    </td>
                                </tr>
                            @endforeach


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

create index for following LARAVEL eloquent query

Hi please help me out for creating an index for the following query

                        $products = \App\items::with([
                 'item_store' => function ($query) {
                $query->select('size', 'item_id', 'item_store_id');
              },

            'pics' => function ($query) {
                $query->select('img_url', 'item_id');
            },

            'brand' => function ($query) {
                $query->select('item_id', 'brand_id');
            },
            'brand.brand' => function ($query) {
                $query->select('brand_id', 'brand_name');
            }

             ])
         ->select('item_id', 'short_name', 'price','price_above')
         ->orderBy('Price', 'Asc')->whereIn('category_id', $arr)
         ->groupBy('Sku')
         ->paginate(20);

my database structure is [st] https://screenshots.firefox.com/JAmaKENMYRhQkEjx/ourweds.com



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3443R4y
via IFTTT

how can chart js call datasets base on value from select option?

trying to get value from select option dynamically then use the value to create new chart depend on value

doesn't work

"new Chart(context).Bar(callchart);"

but this works

"new Chart(context).Bar(keyboard);"

when you call it statically

@foreach($item_name as $in) item_name}}" value=""> @endforeach

var Mouse= { labels: ['January','February','March'],

datasets: [
    {
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: [30,120,90]
    },
]
};

var keyboard = { labels: ['March', 'Apr', 'May'],

datasets: [
    {
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: [50,100,140]
    },
]
};

var Spoon ={ labels: ['June', 'July', 'August'],

datasets: [
    {
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [1,2,3]
    },
]
};

var context = document.querySelector('#graph').getContext('2d');

if(window.bar != undefined) window.bar.destroy();

window.bar = new Chart(context).Bar(keyboard);

$("select").on('change', function() {

//GETING VALUE FROM SELECT OPTION

var callchart =this.value;

var context = document.querySelector('#graph').getContext('2d');

if(window.bar != undefined) window.bar.destroy();

//CREATING CHART USING VALUE FROM SELECT OPTION

window.bar = new Chart(context).Bar(callchart);

});

Uncaught TypeError: Cannot read property 'length' of undefined



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