vendredi 30 novembre 2018

Laravel restore data from log table

I would like to restore my data from log table which was created on every. I use replicate function for copying all data while update and save to clone table, It works fine to store log data in clone table but i am not sure that how can i restore the data from clone table Here is my code while update

public function update(Request $request, $id){
        $bannerone = Bannersec1::findOrFail($id);

        // every time while edit this will copy old data new clone table 
            $clone = $bannerone->replicate();
            unset($clone['created_at'],$clone['updated_at']);
            $clone['clone'] = $bannerone->id;
            $clone['cloneUser'] = Auth::user()->id;
            $data = json_decode($clone, true);
            Bannersec1clone::create($data);

        // save edited data to database
        $input = $request->all();
        $bannerone->update($input);

        return redirect()->route('bannerone.index')->with('success','Banner Update Successfully');
    }

and this is my code while edit

public function edit($id){
    $bannerone = Bannersec1::findOrFail($id);
    $replicate = Bannersec1clone::where('clone',$id)->orderBy('created_at', 'DESC')->get();

    return view('back.index.banner1.edit', compact('bannerone','replicate'));
}

//So is there any way that i can restore my data from clone table? suppose if i click in test1 -> revision then it will replace with my current data enter image description here



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

maatwebsite/laravel-excel returns corrupted file while exports in Live Server, but working in Localhost

  • PHP version 5.6
  • Laravel 5.2
  • maatwebsite/excel: 2.1.0

The code below works fine in localhost, but when i check with Live Server (AWS Light Sail), returns Corrupted Excel/PDF File. I have given all required permissions recommended by maatwebiste. And when i try to dd() the result inside the function the server returns 500 Internal server error response. When i check with some forums someone saying the problem occures with while spaces inside the function and before the < ? php Tag, I tried with the solution but returns the same. Any Help Would be well appreciated.

 public function export(Request $request, $type = 'pdf')
    {
        try {
            $data = $this->getReport($request->All(),new ServiceReport());
            return Excel::create('service_report', function ($excel) use ($data) {
                $excel->setTitle('ServiceReport');
                $excel->setDescription('Service Repor');
                $excel->sheet('AxisPro-ServiceReport', function ($sheet) use ($data) {
                    $sheet->setOrientation('portrait');
                    $this->setColumnHeader($sheet,['Invoice No','Date','Customer']);
                    if (!empty($data)) {
                        foreach ($data as $key => $row) {
                            $i = $key + 2;
                            $sheet->cell('A' . $i, $row->invoice_no);
                            $sheet->cell('B' . $i, sql2date($row->transaction_date));
                            $sheet->cell('C' . $i, $row->customer_name)->setAutoSize(false);
                        }
                    }
                    $sheet->setPageMargin(0);
                    $sheet->setBorder('A1:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
                    $sheet->row(1, function ($row) {
                        $row->setBackground('#d9d9d9');
                    });
                });
            })->download($type);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }



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

Array values set in pivot table along with index value laravel

I have three tables playlist, music and pivot table playlist_music, i want to add playlist and music in pivot table playlist_music. my array of music is music_ids : [1,2,3]. I have to store index also in pivot table, so my code is :

public function create(array $attributes = [])
{
$playlist = parent::create($attributes);
if (isset($attributes['music_ids'])) {
    $playlistMusic = $attributes['music_ids'];
    $music = [];
    foreach ($playlistMusic as  $index => $music ) {
        $tracks[$music['music_id']] = ['index' => $index];
       $tracks[$music['music_id']] = $music;
    }
    $playlist->music()->sync($music);
}
return $playlist;
}

how can i store individual values from array music_ids to the field music_id in pivot table. It is in belongsToMany relationship. please suggest me. Any help would be appreciated.



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

Laravel - Delete Data without Refresh using Ajax

I want to delete my data in table without refreshing it how to do it thanks? any help please thank you.

Here is my View I used href to get the specific ID and delete single row.

 @foreach ($clients as $client)
           <tr>
               <td></td>
               <td></td>

    //I want to click this then delete without refresh//   <td><a href="/admin/clients/archTrash/" class="btn btn-info">Active</a></td>

//I want to click this too then delete without refresh// <td><a href="/admin/clients/archTrashPermanent/" class="fa fa-trash btn btn-danger"></a></td>
           </tr>      
           @endforeach



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

Laravel 5 - How to show variable within view with escaped html?

$var_from_controller = "<div style="color:red">Picture inside html  </div>"

@blade

<div id="my-container">
  {!! $var_from_controller !!}
</div>

It will render as a string. But I need HTML AND asset() output.

How can I do this??



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

Laravel 5.7 Response Status Code Always Returns 200 Even For 422 Errors

I am stuck with a major issue. I have being developing a application for a while. I had set some responses to send the 422 response error code which was initially working fine, but I recently tested those modules again and now those responses only send a 200 status. I tried setting different status codes and it is always sending 200 status code. I have used request->validate to validate the file type, this also sends a 200 status code in error situations. I checked my current status with my GIT commits and I couldn't find any instance that shows a modification that impedes this. Would really appreciate some help regarding this. I am too far off to roll back to the working state.

My Code That should send a different status code instead of 200

$validated = $request->validate(['inputFile' => 'required|mimes:xlsx,xls']);
    if($validated){
        $exists = DB::table($this->tables['tblperiod'][0])->where([[ $this->tables[ 'tblperiod'][1][1], $request->month ],[ $this->tables['tblperiod'][1][2], $request->year ]])->exists();
        if(!$exists){
            $this->doExcel($request);
            $uploadData = $this->getRecentUpload($this->tables['tblallocation'][0], $this->tables['tblallocation'][1], $this->tables['tblperiod'][0], $this->tables['tblperiod'][1], $request->month, $request->year);
            return response()->json(['success' => 'Data set of '. $request->month .' '. $request->year .' has been successfully imported and ready for reports.', 'upload' => $uploadData, 'month' => $request->month, 'year' => $request->year]);
        }else{
            return response()->json(['errors' => 'The data set ('. $request->month .' '. $request->year .') you are trying to upload already exists! Please check the period and try again.'], 422);
        }
    }



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

Laravel - Dropdown Pluck Data Cannot Get the String Value

I have a dropdown that the value of the dropdown is on another table .. and I plucked it so here it is I am getting 1 to display and not Sample Client 3 value which the dropdown has.. help thanks.

See here my dropdown and its value

enter image description here

See my dropdown, when I choose Sample Client it will insert 0 and NOT the ACTUAL string why is that? please take a look at my code thanks

My Dropdown Input

 

My Controller

On create function here it is

$clients = Client::all()->pluck('client_name');
    return view('admin.movies.create', compact('clients'));

on View Index which I foreach loop here it is

 <td></td>

and my Database Model Relationship

On the CLIENT side

    class Client extends Model
{
     use SoftDeletes;

     protected $dates = ['deleted_at'];
     // Table Name
     protected $table = 'clients';
     // Primary Key
     public $primaryKey = 'id';
     // Timestamps
     public $timestamps = true;

on the MOVIES side

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

    class Movie extends Model
{
    // Table Name
    protected $table = 'movies';
    // Primary Key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;

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



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

Laravel 5 -- Redirect in Controller is not working

Everything works perfectly except:

use Illuminate\Routing\Redirector;

public function my_call() {
 return redirect()->route('page-1');
}

return view('page-1') works without problems. Maybe anybody sees what I am doing wrong?

Thank you.



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

How to return collection instead array from DB Laravel?

If to use basic queries using use Illuminate\Support\Facades\DB; we get result as array instead collection. How to return collection?

$users = DB::select('select * from users where active = ?', [1]);

It returns array of $users (rows).



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

How to retrieve information through table?

I have SQL query that does that I need:

SELECT users.FirstName, users.Id FROM `orders` 
INNER JOIN orderrecipients ON orderrecipients.Orders_Id = orders.Id
INNER JOIN users ON users.Id = orderrecipients.Users_Id;

I try to use Eloquent model to build query above using hasManyThrough:

public function OrderRecipients()
{
 return $this->hasManyThrough('App\OrderRecipient', 'App\Order', 'Id', 'Orders_Id');
}

And using is:

$recipients = OrderModel::with("OrderRecipients")->where("User_Id", $userId)->get();
dd($recipients->OrderRecipients()->count());

How to build this relation and get data through table?



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

Laravel 5.7 - Spark API authentication session issues

Just going to preface this question by saying that I'm diving back into Laravel after a while of not using it, it appears there are a lot of changes, and the current project in question is using A LOT of the baked in "Laravel Ecosystem"... so I could be missing some context here.

The issue : After upgrading from Laravel 5.6 to 5.7, auth-guarded API routes are busting because of session expiry, even immediately after logging in (prompting logout).

The configuration :

/config/auth.php

'guards' => ['api' => ['driver' => 'spark']]

/routes/api.php

Route::group([
    'middleware' => 'auth:api'
], function () {
    // Routes in here are busting
}

/app/Providers/SparkServiceProvider.php

protected $usesApi = true; // yup

Additional info :

  • The site uses the Socialite plugin for managing user authentication
  • There are indeed spark_token's in the request
  • Vue client making the calls, getting status 401 Unauthorized on the next page load after successfully authenticating via login form

Any ideas?



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

Filling fields on input

I am creating a search engine and i want to check the database and fill in the hidden fields in the form if the search field brings back a match in the database. So for example if the user entered London and it had a match in my city table, i would want the hidden id and country_id fields filled with the city id and its related country id so that on the search page i would get a url like. Can this be done?

'search?searchinput=London&City=1&Country=1

I have two tables both connected through the relationship:

City: id, name, country_id

Country: id, country,

HTML form:

<div class="search-homepage-input">
    {!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
    <div class="col-md-9 col-l">
    {!! Form::text('searchinput', null, array('class' => 'form-control ', 'maxlength' =>'50', 'placeholder' => 'Search by city. Eg. London, New York, Milan...')) !!}
    </div>
    {!! Form::hidden('country', null, array('id' => 'country')) !!}
    {!! Form::hidden('city', null, array('id' => 'city')) !!}
    <div class="col-md-3 col-r">
        {!! Form::submit('Find Shops', array('class' => 'btn btn-homepage-search'))  !!}
    </div>
    {!! Form::close() !!}
</div>



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

phpunit --version give me 3.7.21. Which is giving me problem on my laravel 5.6 dump.php file. Checked other related question on stackoverflow

I have installed fresh laravel project 5.6 version. On composer.json I have phpunit version 7. But when i run phpunit, it gives me an error of parse synax error. I have php version 7.2. I have also tried doing phpunit --version on /vendor/bin but it is stil giving me

 phpunit --version
PHPUnit 3.7.21 by Sebastian Bergmann.



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

Long standing while trying to create a PDF in PHP

I am using barryvdh/laravel-dompdf

$pdf = PDF::loadView('myview', $data);                      
//return $pdf->download('pdfview.pdf');                          
return $pdf->stream($nombre_archivo);

I am having a problem while trying to use the stream method $pdf->stream($nombre_archivo); my app keeps loading forever.

If i use the download method $pdf->download('pdfview.pdf'); works fine, but I need to use the stream method.

if you could help me, I will be very grateful.



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

Socket.io Connection Timedout

I am making a simple blog in Laravel and I setup a websocket so I will have a realtime changes. I used Docker to make it work. In my local machine, it's all good and work perfectly. However when I deployed it to my server which is AWS EC2 Instance. Seems like socket didn't work. In browser console is look like this

GET http://myblog.com:6001/socket.io/?EIO=3&transport=polling&t=MTbkzBX net::ERR_CONNECTION_T

I checked my port

bootstrap.js

import Echo from 'laravel-echo'

window.io = require('socket.io-client');

if (typeof io !== 'undefined') {
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001'
    });
} 

I think it's fine here since it worked in my local machine, just in my server won't work. Is anyone encountered the same problem and solved it? Please help me, thanks!

this is what I run to install the websockets

npm install redis socket.io socket.io-client laravel-echo-server laravel-echo



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

how to import excel file in mysql using laravel 5.7 with vue JS

i was creating vue file for inpute Excel or csv file laravel 5.7 i was using Maatwebsite/Laravel-Excel dont know how to route there things it if my first time to make app like laravel with vue JS Don't know what to doo there is Vue file

    <template>
    <div class="container">
        <div class="row mt-5">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Students</h3>

                <div class="card-tools">
                    <button class="btn btn-success" data-toggle="modal" data-target="#exampleModal">Add New <i class="fas fa-user-plus"></i></button>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#importModel">Import <i class="fas fa-file-excel"></i></button>
                    <button class="btn btn-warning" data-toggle="modal" data-target="#export">Export <i class="fas fa-file-excel"></i></button>

                </div>
              </div>

            </div>
            <!-- /.card -->
          </div>
        </div><!-- /.row -->
        <!-- Modal -->
        <div class="modal fade" id="importModel" tabindex="-1" role="dialog" aria-labelledby="importModelLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModelLabel">Import Excel</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST"   enctype="multipart/form-data">
                <div class="modal-body">
                        <div class="form-group">
                            <label>Import</label>
                            <input type="file" name="excel_file"
                                class="form-control" :class="{ 'is-invalid': form.errors.has('excel_file') }">
                        </div>


                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save Student</button>
                </div>
                </form>
            </div>
        </div>
        </div>

        <!--Exit Modal-->
    </div>
</template>

<script>
    export default {
        data(){
            return{
                form: new Form({
                    first_name:'',
                    last_name:'',
                    email:'',
                    password:'',
                    designation:''
                })
            }
        },
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

set a post route to import data in web.php file that will route the things as pr laravelExcel

Route::post('importExcel', 'API/StudentMasterController@import');

in a controller file

public function import()
{
    Excel::import(new StudentImport, request()->file('excel_file'));
      //return redirect('/')->with('success', 'All good!');
}

and in a APP/import/studentmaster.php file

public function model(array $row)
{
    return new Student_master([
        'EnrollmentNo'     => $row[22],
    ]);
}



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

Laravel - Count number of rows table on the other file.blade.php

I have two pages. I want to count the number of data row table on the second page how can I do that?

Here I have

@php echo count($clients); @endphp 

My Two pages have the same variable $clients i have no clue how to count the other page rows table help thanks



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

phpunit: Parse error: unexpected '.', expecting '&' or variable (T_VARIABLE)

I have looked up for parse errors. All of them. None seems to be my problem. I haven't modified any of the test sample cases which laravel 5.7.15 gave me. I was expecting some kind of failed test case. I have checked my php version on IIS too. IIS is running php version 7.2. The complete error message is:

Parse error: syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in C:\code plearning\codeEcom\vendor\symfony\var-dumper\Resources\functions\dump.php

What I have modified is laravel's phpunit.xml file. I have added this line of code so that I will have all my test factories data in a new database.

<env name="DB_DATABASE" value="cart_testing"/>



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

Laravel - Cannot Un Delete and Display Data using Soft Delete

Hello I cannot un delete my data why is it? here is my code

on the Controller

   public function displayArchive()
{
    $clients = Client::withTrashed();
    return view('admin.clients.homeArchive')->with('clients', $clients);
}

one the View

 <table class="table table-bordered" id="dynamic_field">  
           <tr>  
              <th>Client Code</th>
              <th>Client Name</th>
              <th>Address</th>
              <th>Tel No.</th>
              <th>Contact Person</th>
              <th>Mobile No.</th>
              <th>Email Address</th>
              <th>Website</th>
              <th>Status</th>
              <th>Update</th>

           </tr>  
           @foreach ($clients as $client)
           <tr>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
               <td><a href="#" class="btn btn-danger">Inactive</a></td>
               <td><a href="/admin/clients//edit" class="fa fa-edit btn btn-primary"></a></td>

           </tr>      
           @endforeach

        </table>  

on the Web Here you can see how I call my controller and view pages.

Route::get('/admin/clients/homeArchive', 'Admin\ClientsController@displayArchive');



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

I need upload image to API with ajax & Json, but i dont understand ,where me wrong

This My Html

This My JS

please help me !!



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

Unable to connect with database with manual settings in laravel

The project were I'm working needs connect with multiple databases on runtime to this, I'm setting the connection propertie on the fly, I'm doing this as follows:

I create a helpers

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

if(! function_exists('conexionBD')){

    /**
     * Establish a tenant database connection.
     *
     * @param $hostname
     * @param $username
     * @param $password
     * @param $database
     */

    function conexionBD($hostname, $username, $password, $database){
        DB::purge('empresa');

        Config::set('database.connections.empresa.host', $hostname);
        Config::set('database.connections.empresa.database', $database);
        Config::set('database.connections.empresa.username', $username);
        Config::set('database.connections.empresa.password', $password);

        DB::reconnect('empresa');

        Schema::connection('empresa')->getConnection()->reconnect();
    }
}

I created a Middleware called Tenant

public function handle($request, Closure $next) {
        if (($request->session()->get('empresaId')) === null)
            return redirect()->route('inicio')->withErrors(['error' => __('Por favor inicie sesión en alguna empresa antes de intentar esta acción')]);

        $empresa = new empresa();
        $empresa->connect();

        return $next($request);
    }

My model of empresa is like that

class empresa extends Model
{
    protected $fillable = [
        'hostname',
        'username',
        'password',
        'database'
    ];

    public function connect()
    {
        if (! $this->connected()) {
            conexionBD(
                $this->hostname,
                $this->username,
                $this->password,
                $this->database
            );
        }
    }

    private function connected()
    {
            $connection = Config::get('database.connections.empresa');
            return $connection['username'] == $this->username &&
            $connection['password'] == $this->password &&
            $connection['database'] == $this->database;
    }
}

Now, when I run this code, I get "SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO)" error, in my database config I have the database, username, password and host empty. In my database, in the empresas table I have that fields with correct information, but at the moment of change the database, the system tell me that, and I don't understand why if I'm not have a localhost user and my database has a password

Someone knows that my code is missing or that I am doing wrong to make the multi-tenant system work correctly?



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

How to count table column data and display in google bar charts in Laravel?

working with Laravel 5.6 and mysql db. an I have table as vehicles like this?

id  name  type  
1   nhy   car
2   juy   van
3   nhy   car
4   kiu   bus
5   hyu   van
etc

currently I am displaying all vehicles numbers using following controller function,

public function vehiclebarchart()
    {
    $chart = Charts::database(Vehicle::all(), 'bar', 'google')
    ->elementLabel("Total")
    ->GroupByDay();
        return view('summarys.vehiclebarchart',compact('chart'));
    }

but now I need display each vehicles types in bar charts like car,van,bus... with counting then, how can I configure controller sql query like above query

$chart = Charts::database(Vehicle::all(), 'bar', 'google')

for my new requirements?



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

How to change url in pagination?

In my Laravel 5.7 app I have news page

http://mysite/all_news

with pagination implementation as:

$newsList = PageContent
    ::select(\DB::raw(' page_contents.*, users.username'))
    ->getByPageType( 'N' )
    ->getByPublished( true )
    ->orderBy('created_at', 'desc')
    ->join(\DB::raw('users '), \DB::raw('users.id'), '=', \DB::raw('page_contents.creator_id'))
    ->paginate( 4 , null, null, $page)
    ->onEachSide();

and route defined as :

Route::get('all_news', array(
    'as'      => 'all_news',
    'uses'    => 'PageController@all_news'
));

and in view I show pagination :

But rendered links in pagination looks like(and how to render them ?):

http://mysite/all_news?=2

How to make urls look like

http://mysite/all_news/2

?

Thanks!



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

Laravel validation: unique rule to bring duplicated record back

I have not found anywhere a clean way of what I am exactly looking for so thought to give on here a try:

$validator = Validator::make($request->all(), [
            'an_id' => 'unique:users,an_id',
            'another_id' => 'unique:users,another_id',
            'test_id' => 'unique:users,test_id',
        ]);

        if ($validator->fails()) {
            //
        }

So, what I'd like to do is when a duplicate test_id is provided, is to not only fail but show me which user uses the same test_id.

Is this actually possible through Laravel's Validation?



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

Laravel showing image

I am using Laravel 5.7. I have successfully uploaded and stored in a database. Looking in my directory I can see(Windows 10) that it is in the correct place beneath the root:

storage\app\images\continents\icons

If I try to show it even though my line resolves to:

http://localhost:8000/storage/app/images/continents/icons/cc001f7733c9a5ab4941cefa2d50bde1.jpg

I just get a 404 error.

It is most certainly there.



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

Laravel "Creating default object from empty value" yet

Everything is set well no typo error and I don't thing I have wrong connection betweene MVC yet I'm getting an error

"Creating default object from empty value"

For 3 days trying to solve this problem and can't locate the exact reason of it.

The View File:

@extends('layouts.app')

@section('header')
  <h1>@lang('messages.paypalsettings')</h1>
  <hr />
  <div style="clear:both">&nbsp;</div>
@endsection
@section('content')
<form action="" method="POST">
  
  <div class="col-sm-12">
      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="merchant_email">@lang('messages.merchant_email')</label>
            <input type="text" class="form-control" id="merchant_email" name="merchant_email" value="">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="sandbox">@lang('messages.sandbox')</label>
            <select id="sandbox" name="sandbox" class="form-control">
                <option value="1">Yes</option>
                <option value="">No</option>
            </select>
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">  
            <label for="api_username">@lang('messages.api_username')</label>
            <input type="text" class="form-control" id="api_username" name="api_username" value="">
        </div>
      </div>  
  </div>

  <div style="clear:both">&nbsp;</div>

   <div class="col-sm-12">
      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="api_password">@lang('messages.api_password')</label>
            <input type="text" class="form-control" id="api_password" name="api_password" value="">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="api_secret">@lang('messages.api_secret')</label>
            <input type="text" class="form-control" id="api_secret" name="api_secret" value="">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">  
            <label for="currency_code">@lang('messages.currency_code')</label>
            <input type="text" class="form-control" id="currency_code" name="currency_code" value="">
        </div>
      </div>  
  </div>

  <div style="clear:both">&nbsp;</div>

  <div class="form-group float-right">
    <button type="submit" class="btn btn-primary">@lang('messages.save')</button>
  </div>


</form>
@endsection

The controller side

namespace AppExample\Http\Controllers;

use Illuminate\Http\Request;
use AppExample\models\Paypal;
use AppExample\models\PaypalSettings;
use AppExample\User;
use App\Invoice;
use App\Item;
use Auth;
use Lang;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Srmklive\PayPal\Services\ExpressCheckout;
use AppExample\IPNStatus;

class PayPalController extends Controller
{
    /**
     * @var ExpressCheckout
     */
    protected $provider;

    public function __construct()
    {
        $this->middleware('auth');
        //$this->provider = new ExpressCheckout();
    }

    public function paypalsettings(){
       $paypalsettings = PaypalSettings::find(1);
        if(!$paypalsettings){
          $paypalsettings = new PaypalSettings;
          $paypalsettings->sandbox = '';
          $paypalsettings->merchant_email = '';
          $paypalsettings->api_username = '';
          $paypalsettings->api_password = '';
          $paypalsettings->api_secret = '';
          $paypalsettings->currency_code = '';
        }
        return view('paypal.index')->with('paypal', $paypalsettings);
    }

public function save_paypalsettings(Request $request){
    $merchant_email = $request->merchant_email;
    $sandbox = $request->sandbox;
    $api_username = $request->api_username;
    $api_password = $request->api_password;
    $api_secret = $request->api_secret;
    $currency_code = $request->currency_code;
    $paypalsettings = PaypalSettings::find(1);
    $paypalsettings->merchant_email = $request->merchant_email;
    $paypalsettings->sandbox = $sandbox;
    $paypalsettings->api_username = $api_username;
    $paypalsettings->api_password = $api_password;
    $paypalsettings->api_secret = $api_secret;
    $paypalsettings->currency_code = $currency_code;
    $paypalsettings->save();

    // $paypalitems = Paypal::find(1);
    // $paypalitems->item_number = $item_number;
    // $paypalitems->item_name = $item_name;
    // $paypalitems->amount = $amount;
    // $paypalitems->save();        
    return back();
}

    public function paypal_items(){
       $paypal = Paypal::find(1);
        if(!$paypal){
          $paypal = new Paypal;
          $paypal->item_number = '';
          $paypal->item_name = '';
          $paypal->amount = '';
        }
        return view('paypal.index')->with('paypal', $paypal);
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getExpressCheckout(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $cart = $this->getCheckoutData($recurring);

        try {
            $response = $this->provider->setExpressCheckout($cart, $recurring);

            return redirect($response['paypal_link']);
        } catch (\Exception $e) {
            $invoice = $this->createInvoice($cart, 'Invalid');

            session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
        }
    }

    /**
     * Process payment on PayPal.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getExpressCheckoutSuccess(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $token = $request->get('token');
        $PayerID = $request->get('PayerID');

        $cart = $this->getCheckoutData($recurring);

        // Verify Express Checkout Token
        $response = $this->provider->getExpressCheckoutDetails($token);

        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            if ($recurring === true) {
                $response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
                if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
                    $status = 'Processed';
                } else {
                    $status = 'Invalid';
                }
            } else {
                // Perform transaction on PayPal
                $payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
                $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
            }

            $invoice = $this->createInvoice($cart, $status);

            if ($invoice->paid) {
                session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
            } else {
                session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
            }

            return redirect('/');
        }
    }

    /**
     * Parse PayPal IPN.
     *
     * @param \Illuminate\Http\Request $request
     */
    public function notify(Request $request)
    {
        if (!($this->provider instanceof ExpressCheckout)) {
            $this->provider = new ExpressCheckout();
        }

        $post = [
            'cmd' => '_notify-validate'
        ];
        $data = $request->all();
        foreach ($data as $key => $value) {
            $post[$key] = $value;
        }

        $response = (string) $this->provider->verifyIPN($post);

        $ipn = new IPNStatus();
        $ipn->payload = json_encode($post);
        $ipn->status = $response;
        $ipn->save();            
    }

    /**
     * Set cart data for processing payment on PayPal.
     *
     * @param bool $recurring
     *
     * @return array
     */
    protected function getCheckoutData($recurring = false)
    {
        $data = [];

        $order_id = Invoice::all()->count() + 1;

        if ($recurring === true) {
            $data['items'] = [
                [
                    'name'  => 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id,
                    'price' => 0,
                    'qty'   => 1,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success?mode=recurring');
            $data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
        } else {
            $data['items'] = [
                [
                    'name'  => 'Product 1',
                    'price' => 9.99,
                    'qty'   => 1,
                ],
                [
                    'name'  => 'Product 2',
                    'price' => 4.99,
                    'qty'   => 2,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success');
        }

        $data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
        $data['invoice_description'] = "Order #$order_id Invoice";
        $data['cancel_url'] = url('/');

        $total = 0;
        foreach ($data['items'] as $item) {
            $total += $item['price'] * $item['qty'];
        }

        $data['total'] = $total;

        return $data;
    }

    /**
     * Create invoice.
     *
     * @param array  $cart
     * @param string $status
     *
     * @return \App\Invoice
     */
    protected function createInvoice($cart, $status)
    {
        $invoice = new Invoice();
        $invoice->title = $cart['invoice_description'];
        $invoice->price = $cart['total'];
        if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
            $invoice->paid = 1;
        } else {
            $invoice->paid = 0;
        }
        $invoice->save();

        collect($cart['items'])->each(function ($product) use ($invoice) {
            $item = new Item();
            $item->invoice_id = $invoice->id;
            $item->item_name = $product['name'];
            $item->item_price = $product['price'];
            $item->item_qty = $product['qty'];

            $item->save();
        });

        return $invoice;
    }
}

The Model Side

namespace AppExample\models;

use Illuminate\Database\Eloquent\Model;

class Paypal extends Model
{
  protected $table = 'paypal_duration';

    protected $fillable = [
      'id', 'item_number', 'item_name', 'amount'
    ];

    public function teacher(){
      return $this->belongsTo('AppExample\models\Teacher');
    }

    public function subscription(){
      return $this->belongsTo('AppExample\models\Subscription');
    }

    public function get_packages(){
       return $packages = Packages::whereHas('paypal_packages', function($query){
          $query->where('id', '=', $this->id);
        })->get();
    }
    public function has_expired(){
        $now = new Carbon();
        $end = Carbon::parse($this->enddate);
        return $now->gt($end);
    }

}

The Route side

Route::get('admin/paypal/edit', 'PaypalController@paypalsettings')->name('admin.paypal.edit');
Route::post('admin/paypal/save', 'PaypalController@save_paypalsettings')->name('admin.paypal.save');

Maybe I stopped seeing things well should consider to go to the doctor. But am I wrong why I am getting this error while everything is well set I think. Any help much appreciated, thanks in advanced!



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

Why did not delete user in table in Laravel 5.6

I am working with Laravel 5.6 and going delete users fron users table as admin. I have following UserController function to delete table records?

public function delete($id)
    {
       User::where('id', $id)
                ->delete();

        return redirect()->back()->with('info', 'User deleted successfully'); 
    }

and My users data showing in index blade file with concluding delete buttons like this,

<td><a class="button is-outlined" href="" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>

and My delete route is like this,

Route::get('users/{users}/delete', [
    'uses' => '\App\Http\Controllers\UserController@delete',
]);

but now when I click delete button javascript conformation coming and after accept it not deleting records. url is change like this

http://localhost:8000/users?16/delete/     //16 is user id

how can I fix this problem?



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

Error after calculating, the calculation returns a error even if it is mathematically correct

I have a problem making a calculation on laravel this is the calculation:

$inc = round(100*($Incom->total_amount/$TotalRewenue), 2);

I tested if $Incom is 0, $Incom->total_amount is 0 and $TotalRewenue is 0 and neather of theme are 0 and if i putt a dd of $inc i actually get the value of the calculation correct.

this is the full code:

    $TotalIncome = DB::table('actuals_report')->where('companyId',$id)->Where('dataYear',$dataYear)->where('type','LIKE','TotlaIncome%')->first();
    $TotalExpense = DB::table('actuals_report')->where('companyId',$id)->Where('dataYear',$dataYear)->where('type','LIKE','TotlaExpense%')->first();
    $TotalRewenue = $TotalIncome->year - $TotalExpense->year;



    foreach($TopTwentyIncomers as $topIncomer)
    {
        foreach($TopTwentyExpensers as $topExpenser)
        {
            if($topIncomer->name == $topExpenser->name)
            {
                $topTwentyRevenuers[] = (object) array('name' => $topIncomer->name, 'total_amount' => $topIncomer->total_amount - $topExpenser->total_amount);
            }
        }
    }

    foreach($topTwentyRevenuers as $Incom)
    {

        $inc = round(100*($Incom->total_amount/$TotalRewenue), 2);
        //dd($Incom->total_amount);
        $yearlyReportExists = DB::table('yearly_report')
            ->where('company_id', $id)
            ->where('year', $dataYear)
            ->where('client_name', $Incom->name)
            ->Where('type','LIKE','%highestGenerator%')
            ->first();

        if(!empty($yearlyReportExists)){
            DB::table('yearly_report')
                ->where('id', $yearlyReportExists->id)
                ->update(['company_id'=>$id,'year'=>$dataYear,'type'=>"highestGenerator",'client_name'=>$Incom->name,'amount'=>round($Incom->total_amount, 2),'inc'=>$inc]);
        }
        else{
            dd($inc);
            DB::table('yearly_report')->insert(['company_id'=>$id,'year'=>$dataYear,'type'=>"highestGenerator",'client_name'=>$Incom->name,'amount'=>round($Incom->total_amount, 2),'inc'=>$inc]);
        }
    }



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

Page Forbidden even if user is authorized in laravel 5.7

I'm using laravel 5.7 Gate and policies for site authorization. I have done it as follows but Page is forbidden even if user has permission in the roles table. in my system I have 3 main Roles as Super Admin, Admin,Guest. They have different permissions as attached image. Roles and Permissions. Please help me to fix this.

web.php

Route::get('/users', 'UserController@index')->name('users')->middleware('can:view-user');

AuthServiceProvide.php

public function boot()
{
    $this->registerPolicies();
    $this->registerPostPolicies();   
}

public function registerPostPolicies()
{
    Gate::define('view-user', function($user){
        $user->hasAccess(['view-user']);
    });

    Gate::define('activate-user', function($user){
        $user->hasAccess(['activate-user']);
    });
}

Role Model

public function hasAccess(array $permissions)
{
    foreach($permissions as $permission){
        if($this->hasPermission($permission)){
            return true;
            echo("<script>console.log('PHP: ".$permissions."');</script>");
        }
    }
    return false;
}

protected function hasPermission(string $permission){
    $permissions = json_decode($this->permissions,true);
    return $permissions[$permission]??false;

}   

Roles and hasAction function in User Model

public function roles()
{
    return $this->belongsToMany(Role::class, 'roles_users');
}

public function hasAccess(array $permissions)
{
   foreach($this->roles as $role){
        if($role->hasAccess($permissions)){
            return true;
        }
   }
   return false;
}

Role seeder

use Illuminate\Database\Seeder;
Use App\Role;
class rolerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $super_admin = Role::create([
            'name'        => 'Super Admin',
            'slug'        => 'super admin',
            'permissions' => json_encode([
                'create-user' => true,
                'update-user' => true,
                'update-user' => true,
                'activate-user' => true,
                'view-user'  => true,

            ]),
        ]);
        $admin = Role::create([
            'name'        => 'Admin',
            'slug'        => 'admin',
            'permissions' => json_encode([
                'view-user'  => true,
            ]),
        ]);

        $guest = Role::create([
            'name'        => 'Guest',
            'slug'        => 'guest',
            'permissions' => json_encode([
                'view-user'  => true,
            ]),
        ]);
    }
}

And code is written as below tutorial link to tutorial



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

Laravel - Archiving Data, Delete and Insert to another Table

When I click the button delete I want to delete the data and insert it to another table which is the archive how can I do it?

Here is my Destroy Public Function:

public function destroy($id)
{
    $client = Client::find($id);
    $client->delete();

}

My Store Public Function:

$client = new Client;
$client->client_code = $request->input('client_code');
$client->client_name = $request->input('client_name');



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

Cannor login using laravel 5 after run command

$ php artisan optimize $ php artisan route:cache $ php artisan config:cache Reply

i run this command base some articles to optimize the web, But unfortunately after do all this step i cannot login any more .

I dont't know how to recover this , Please help me on this issue ..



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

jeudi 29 novembre 2018

Where I should use "Gates" in Laravel 5?

I store list of permissions in database.

I have a resource controller:

class UserController extends Controller {

   public function store(Request $request) {
       if (Gate::denies('create-user', User::class)) {

       }       

       /**
        when I use controller helper it throws 
        Illuminate\Auth\Access\AuthorizationException

        like this $this->authorize('create-user', User::class); 
       */

       return response()->json(User::create($request->validated()));
   }   

}

In my case more convenient use Gate::allows way because I have a specific list of permissions.

But how can I throw Illuminate\Auth\Access\AuthorizationException? if a user does not have permission to do this action.

I have to use Gate::allows instead of $this->authorize because in my UserPolicy I have to specify the name of a permission like this:

class UserPolicy
{
    use HandlesAuthorization;

     public function create(User $user)
     {
        $has = MyPermissionModel::hasAccess($user, 'create-user');
        return $has;
     }
}

But if I use Gates it seems more clear and correct:

class AuthServiceProvider extends ServiceProvider
{ 
    public function boot()
    { 
      Gate::define('create-user', 'App\Policies\UserPolicy@create');
    }
}

And now I can check access anywhere, not only inside UserController.

So my questions are:

What is a better way to check permissions when I store my permissions dynamically in DB?

How can I throw Illuminate\Auth\Access\AuthorizationException? if I use Gates.



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

Laravel cast datetime to date

Good Day everyone,

I'm doing a whereBetween dates query on eloquent however, I have issue with the date time.

if I select date_from to 2018-11-01 and date_to to 2018-11-29

and If i have a data that was created on 2018-11-29 12:28:45 the data created on this datetime will not be included because of the time. is there a way to cast the created_at to date.

here's my code:

Payable::with('details', 'transaction_type')
                        ->whereBetween('created_at', [$request->date_from, $request->date_to])
                        ->get();

thanks in advance.



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

Save Post Data from External Server To Laravel

I want to save information posted to a callback URL to a Laravel database. I have created a controller and a route in the api.php file but the posted information is not being saved. When I create a PHP file in the public folder, the info is being saved but I want it to go through a controller. Kindly let me know what I need to do to save the info.

Route: Route::post('/receivesms', 'MessageController@stk');

Controller:

namespace App\Http\Controllers;

use App\Message;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    public function stk(Request $req){

        $message = new Message();
        $message->sender = $req->input('from');
        $message->recipient = $req->input('to');
        $message->message = $req->input('message');
        $message->date_sent = $req->input('date');
        $message->message_id = $req->input('id');
        $message->link_id = $req->input('linkId');
        $message->save();

        return view('welcome');
    }
}

The posted info is as explained here. with the posted data being;

 $from = $_POST['from'];
 $to = $_POST['to'];
 $text = $_POST['text'];
 $date = $_POST['date'];
 $id = $_POST['id'];
 $linkId = $_POST['linkId']; 



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

What is difference between relation with ->profiles() and ->profiles in Laravel?

What is difference between relation with->profiles() and ->profiles in Laravel?



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

how to return download file and continue execute another code in only controller laravel

i have a controller like this:

public function export() {
  $this->getTempalte();
  $post=Post::find(1)->get();
  return redirect()->back()->with($post);
}
public function getTempalte(){
  return Storage::download('public\template\note.docx');
}

but when i run this controller, it called getTemplate function but it dont retunt file, and other code in export function still continue



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

Laravel service container bing class constructor with parameter

I have a Closet class, its constructor with 3 parameter.

Class Closet
{
    public function __construct($size, $length, Jeans $Jeans)
    {
        $this->size = $size;
        $this->length = $length;
        $this->Jeans = $Jeans;
    }
}

And I need to use dependency injection on some where.

Class Outfit
{
    public function __construct(Closet $Closet)
    {
        $this->Closet = $Closet;
    }

    public function pants($size, $length)
    {
        $this->Closet($size, $length);
    }
}

so I bind it in Provider

public function register()
{

    $this->app->singleton(Closet::class, function ($app) {
        return new Closet($app->make('Jeans'));
    });

}

What should I do to bind $size, $length into register?



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

Access pivot table value via a model which relates to both pivoted models

Say I have a table of matches for a game where the opponents score is kept per match, and the match can have any number of players, currently the relationship looks like this:

class Match extends Model {
    public function players() {
        return $this->belongsToMany(Player::class)->withPivot(['score']);
    }
}

class Player extends Model {
    public function matches() {
        return $this->belongsToMany(Match::class)->withPivot(['score']);
    }
}

It works nicely, I can get players of a match and get each players score for that match via the pivot table. I assume I'm doing this much right.

Then we introduce a third model, which easily relates to both models and keeps track of which player spectators of the game place bets on:

class Bet extends Model {
    // get the match the bet is for
    public function match() {
        return $this->belongsTo(Match::class);
    }

    // get the player the bet is for
    public function player() {
        return $this->belongsTo(Player::class);
    }
}

But then we decide we want show a list of bets and the final score the player on the match had relating to that bet, e.g. $bet->playerWithMatch->pivot->score. But obviously, Bet isn't related to Player via a pivot, however it shares both the relationships that the pivot exists to bring together, so the information is already all there to attach it to the pivot table directly.

Sure, one could simply get the related match, then iterate through the players of that match, e.g.:

foreach ($bet->match->players as $player) {
    if ($player->id == $bet->player->id) {
        // yay, we got it!
        return $player->pivot->score;
    }
}
// this should never happen... oh but wait, isn't this a sign of bad design patterns or something?
// should we not find a way to more Eloquently represent all of this? hmm...
return null;

But I would prefer a simpler more "inline" way I can do straight in the initial query and have it available in a Blade template for example and I feel like there must be some way to do this that I'm missing? Without doing an excessive number of queries and/or breaking my ability to use Laravel's pagination?



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

Laravel 5.6 orderBy not working in pagination

I got a query below to retrieve all the transactions, I wanted to sort it by the column date, however it still displayed unsorted data.

$transactions = \App\Transaction::latest()->select('transactions.*', 'category_name')->join('categories', 'transactions.category_id', '=', 'categories.id')->
           orderBy('transactions.date','desc')->paginate(8);



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

Laravel 5:7 Determining reasonable setRedrawFrequency for Symfony's Progress Bar to avoid CLI blinking based on a quantity of records to loop

I work on several artisan commands that do something in a loop over a different quantity of items. Sometimes it's 30 items, sometimes it's 800k items, sometimes 20k.

Everything works but sometimes the output blinks. I know why - due to the too frequent refresh.

$progress = $this->output->createProgressBar($this->countSyncRowsCleaned);

I came up with determining the refresh rate somehow dynamically based on the volume of records to loop through. So instead of hardcoding:

$progress->setRedrawFrequency(50);

I do:

$progress->setRedrawFrequency(max(1, floor($this->countSyncRowsCleaned / 1000)));

Sometimes 50 is great, sometimes it's still to frequent.

What would be a good math formula to set reasonable redraw frequency for a huge spread of integers? Sometimes several records, sometimes over a million.

Thanks for any hints.



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

Laravel : Middleware Issue

I have middleware UKM i want if the Auth::id() in the table ukm then can access the next request. But not working, if Auth::id() no in the table user can access.

public function handle($request, Closure $next)
    {
        $query = DB::table('ukm')->where('id_user',Auth::id())->get();
        foreach($query as $key){
            $cek = $key->id_user;
        }
        if ($cek != NULL) {
            return $next($request);
        }

            return redirect('/');
    }  



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

Laravel Passport, two tables for Login API

I am trying to make a user authentication with two tables, a different table to 'users' and the one of 'users' which is the one with default Laravel, use laravel passport. The detail is when I try to login with the second table I can not do the authentication because I do not recognize the users of the second table.

-Tengo el modelo User2 -> protected $guard_name = 'api2'; -Use otra coneccion -> protected $connection = 'mysql2';

**config/auth.php**

'guards' => [
'web' => [
    'driver' => 'session',
    'provider' => 'users',
],

'api' => [
    'driver' => 'passport',
    'provider' => 'users',
],

'api2' => [
    'driver' => 'passport',
    'provider' => 'users2',
  ], 
],

'providers' => [

'users' => [
    'driver' => 'eloquent',
    'model' => App\User::class,
],
'user2' => [
    'driver' => 'eloquent',
    'model' => App\User2::class,
],

],

My controller

public function login(Request $request)
 {
if (Auth::attempt($request->only('email', 'password'))) {
  $email = $request->only('email');
  $token =  $user->createToken('123456')->accessToken;
  $user->withAccessToken($token);
  $email=json_decode(json_encode($email));
  $user = User2::where('email', $email->email )->first()->only('id','name','email','employee_id');

  $user1 = User::find($user['id']);

  if(!$user1->hasAnyRole(Role::all())){
    return response()->json([
      'success' => false,
      'data' => '',
      'msg' => "does not have assigned role"
    ], 403);
  }
  $roles = $user1->getRoleNames()->first();
  $role = Role::findByName($roles,'api');
  $user=json_decode(json_encode($user));

  return response()->json([
    'success' => true,
    'token' => $token,
    'data' => [
      'user_id' => $user->id,
      'name' => $user->name,
      'email' => $user->email,
      'employee_id' => $user->employee_id,
      'role_id' => $role->id,
      'role_name' => $role->name
        ],
    'msg' => "Successfully"
  ], 200);
} else {
  return response()->json(['error' => 'Unauthorised'], 401);
}
}



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

Can't connect my database well in laravel

i have my database created using mySQl and ready to use but i can't tell laravel what is the foreign keys and what they reference i tried using this way

Schema::table('course', function (Blueprint $table) {
        $table->foreign('weeklyHoursId')->references('id')->on('weekly_hours');
        $table->foreign('gradeSystem')->references('id')->on('grade_system');
    });

but it dosen't work for me and i still getting this error message

 SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`credithourssystem`.`#sql-2494_38`, CONSTRAINT `course_weeklyhoursid_foreign` FOREIGN KEY (`weeklyHoursId`) REFERENCES

weekly_hours (id)) (SQL: alter table course add constraint course_weeklyhoursid_foreign foreign key (weeklyHoursId) references weekly_hours (id)) any help, please :)



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

Backpack for Laravel - Permissionmanager: Can't create new user

so I got the following problem. I am using Backpack for Laravel with the PermissionManager Extension. By default, you have to log in via your email address, however, you can change that to log in with a username. Works fine if I (for example) seed the database. But for some strange reason, I can not create new users via the PermissionManager PermissionManager Extension. If I try the following error message is the result:

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value 
(SQL: insert into `users` (`updated_at`, `created_at`) 
values (2018-11-29 22:26:32, 2018-11-29 22:26:32))

Just for testing, I gave the name column a default value but the error message is the same, except the error now is: Field 'username' doesn't have a default value so it just takes the next column in my database.

Of course, I've changed the CRUD-Requests, Form-Requests and so on, to store a username instead of an email. But it looks like the Request doesn't get my form values. It only tries to store the timestamps.

Strange thing: If I reverse all I did in the Controllers and so on and create an email column again, it will just work fine... did I overlook something? How can I solve this error and store users with a username instead of an email?



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

laravel mysql database same page multiple form submission table not updating

i am trying to update database table by using checkboxes ,the code is not giving any error,but the database table is not updating. My blade code where the form is:

<body>
        <h2>Reported Posts </h2>
        <a href="">Back</a> 

        <table>
        @foreach($post_reports as $post_report)
            <tr>
                <td>Report NO:</td>
                <td></td>
                <td></td>
    <form method="post">
        @csrf
                <td><input type="checkbox" name="statusyes[]" value= >report to admin  <input type="checkbox" name="statusno[]" value= >wrong report </td>
            </tr>
        @endforeach
        <td><input type="submit" name="submit" value="Submit" /></td>
    </form>
        </table>

my controller code is :

I am using the status_update_reported_post function

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post_report;
use Illuminate\Support\Facades\DB;


class moderatorController extends Controller
{
    public function index(Request $request){

    return view('moderator.index');
   }

   public function reported_post(Request $request){

    $post_reports=DB::table('Post_reports')
                ->where('status','moderator')->get();

    return view('moderator.reported_post')-> with('post_reports',$post_reports);
   }

   public function status_update_reported_post(Request $request){
   $statusadmin[]=$request['statusyes'];
   $statuswrong[]=$request['statusno'];
   $r='admin';
   $wr='wrong';

   foreach($statusadmin as $report_id){
      DB::table('post_reports')
               ->where('report_id','$report_id')
               ->update(['status' => 'admin']);

   }

   foreach($statuswrong as $report_id){

        DB::table('post_reports')
               ->where('report_id','$report_id')
               ->update(['status' => 'wrong']);

   }
}


}

the code is working fine but there is no update in the table i dont know where the problem is, It all seems fine to me .



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

Laravel - Clear Cache(s) Without Artisan Command

I've moved my project but have run into an issue. I'm discovering that the old settings (which have been changed in my .env to reflect the changed host) are still being used by my project.

I can't access my project through a browser as it returns this error: SQLSTATE[HY000] [1045] Access denied for user 'appReop'@'localhost' (using password: YES) (SQL: select * fromsettingslimit 1)

appReop was an the previous login username. And while I could just create a new user to reflect this, I also run into an issue about the old password being too weak for the current database configuration.

But when I go to run php artisan cache:clear, it returns the same above error. So I was curious if there was a way to manually clear the caches to fix my errors?

Thanks!



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

PHP/Laravel 5.4/Carbon - sustainable way to parse week of year, considering for year to year week number variances

Any thoughts on how to parse week of year and consider for abnormalities like this year's 12/31/18 actually being week 1 of 2019. The reason is someone wrote a scheduler that stores dates like so: 2017-W37-1 (year, the letter W, actual week number and actual day number of the week). The way it was written, it has already stored over three hundred rows as 2018-W53, which does not even exist this year. I'm working with PHP/Laravel 5.4 and I've started a weekOfYear method to filter all incoming dates from the front end. Flow is front end has a date picker, sends a date to the index, store and destroy methods and interacts with the schedules table from there, which has a "date" column in the above format (actually a string obvs and not date). There is no fallback date, so it just pulls all the schedules for a week based on that one string. My method so far:

public function weekOfYear($date)
{
    $date = Carbon::parse($date);
    $formattedDate = $date->year.'-W'.$date->weekOfYear;

    if ($date->format('Y-m-d') === '2018-12-31') {
        $formattedDate = '2019-W01';
    }
    return $formattedDate;
}

The day number gets tagged on in further methods, but I'll probably add that here as well. This works for 2018, but I would rather parse the date in a more flexible way, despite the fact that 2019 is actually more straightforward.



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

Moving Laravel to Production without Serve

I'm trying to understand my issue here, I've looked through a variety of resources and haven't found a solution that worked for me.

I have my Laravel project which I have moved to a new Apache host. At the moment, my project is hosted in the directory /var/www with the default "public" folder of Laravel being relabeled html.

Currently, this is my .htaccess:

<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>

I haven't changed anything else at the moment (besides my tries at fixing the issue and then reverting them), but my issues arises when I go to my base URL. It opens a page and tells me that it can't find a class I have set up. (Simply this error):

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'App\Setting' not found

And just so I know I'm writing it correctly, this is a portion of my file structure:

enter image description here

I'd appreciate any help any one can give. Thanks in advance!



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

Error creating elasticsearch mapping with elasticquent lib

In my Laravel 5.7 app I try to work with elasticsearch with composer.json :

{
    "require": {
        ...
        "elasticquent/elasticquent": "dev-master",
        ...
    },

reading article https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/ I want to start with creting mapping and bulking data. For this in my model app/Vote.php:

namespace App;

use DB; ... use Elasticquent\ElasticquentTrait; ... class Vote extends MyAppModel { use ElasticquentTrait; ...

protected $table = 'votes';
protected $primaryKey = 'id';
public $timestamps = false;

protected $fillable = ['name', 'slug', 'description', 'creator_id', 'vote_category_id', 'is_quiz', 'status', 'image'];
protected $mappingProperties = array(

    'id'               => [
        'type' => 'integer',
        "analyzer" => "standard",
        'include_in_all' => FALSE
    ], //            'user'    => array(  // THERE would be nested data later //                'type' => 'object', //               

'properties' => array( // 'name' => array('type' => 'string', 'include_in_all' => TRUE), //
'fullName' => array('type' => 'string', 'include_in_all' => TRUE, 'boost' => 2) // ), // ), 'name' => [ 'type' => 'string', "analyzer" => "standard", 'include_in_all' => TRUE ], 'slug' => [ 'type' => 'string', "analyzer" => "standard", 'include_in_all' => TRUE ], 'description' => [ 'type' => 'string', "analyzer" => "standard", 'include_in_all' => FALSE ], 'created_at' => [ 'type' => 'date', "analyzer" => "standard", 'include_in_all' => FALSE ],

public function getTableName(): string
{
    return $this->table;
}

public function getPrimaryKey(): string
{
    return $this->primaryKey;
}



public static function setVotesElasticMapping()
{

// Vote::deleteMapping();

    Vote::createIndex(/*$shards = null, $replicas = null*/);

    Vote::putMapping(/*$ignoreConflicts = true*/);

    Vote::addAllToIndex ();
}

}

But calling method setVotesElasticMapping I got error:

{"error":{"root_cause":[{"type":"resource_already_exists_exception","reason":"index [select_vote/IxHrJ300SIWSZ_s12-jAJw] already exists","index_uuid":"IxHrJ300SIWSZ_s12-jAJw","index":"select_vote"}],"type":"resource_already_exists_exception","reason":"index [select_vote/IxHrJ300SIWSZ_s12-jAJw] already exists","index_uuid":"IxHrJ300SIWSZ_s12-jAJw","index":"select_vote"},
"status":400}

That is clear, as I have created the index before and "select_vote" is "default_index" in config/elasticquent.php file. But uncommenting line

Vote::deleteMapping();

I got error :

Elasticsearch \ Common \ Exceptions \ BadRequest400Exception (405)
{"error":"Incorrect HTTP method for uri [/select_vote/votes/_mapping] and method [DELETE], allowed: [PUT, GET, POST]","status":405}

Can you say why error and how to fix it? I think anyway I need this method calling, say if I remade structure of mapping...

Thanks!



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

Mailable components not including panel.blade.php

I am trying to get my head around laravel's mailables and the way it is rendered. I read the docs, but I couldn't find anything about this.

I published the mailable components to be able to customize, the live in resources/views/vendor/mail/html and the markdown folder

I also have resources/views/emails/testing.blade.php

I am using markdown as indicated in the docs it will make use of the default template and it will also render the text version

I am essentially tyring to understand why panel won't render where I have the panel tag

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <style>
        @media only screen and (max-width: 600px) {
            .inner-body {
                width: 100% !important;
            }

            .footer {
                width: 100% !important;
            }
        }

        @media only screen and (max-width: 500px) {
            .button {
                width: 100% !important;
            }
        }
    </style>

    <table class="wrapper" width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td align="center">
                <table class="content" width="100%" cellpadding="0" cellspacing="0">

                    

                     <!-- Why can't I render it here???? -->

                    <!-- Email Body -->
                    <tr>
                        <td class="body" width="100%" cellpadding="0" cellspacing="0">
                            <table class="inner-body" align="center" width="570" cellpadding="0" cellspacing="0">
                                <!-- Body content -->
                                <tr>
                                    <td class="content-cell">

                                        

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

                    
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

and my testing.blade.php

@component('mail::panel')
        Some panel content
@endcomponent

@component('mail::message')
Welcome to the site 

Your registered email is  , Please click on the below link to verify your email account

@component('mail::subcopy')
        super subcopy
@endcomponent

@component('mail::button', ['url' => url('/')])
My Button
@endcomponent

Thanks,<br>


@endcomponent

The only way panel seems to render is if I have it inside @component('mail::message') but even so it won't render where I indicated above?

Anyone? cheers



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

How to combine two collections by matching keys and their values

So, I've been bashing my head against this for a while and I cant get it to just do what I need it to.

I want to be able to store a set of valuse in our database as Json, but no matter what I cant get Laravel or format the object quite right first.

I've got three queries, One gets users usernames and their First name, as an object. Another two use that object to get a count of each users sales, and quotes, from our databsae with count().

Now all I need is the objects to be combined.

array:1 [
  "" => array:3 [
    0 => array:7 [
      0 => array:2 [
        "CallCentreID" => "sdickerson"
        "FirstName" => "Sarah"
      ]
      1 => array:2 [
        "CallCentreID" => "wjones"
        "FirstName" => "Wendy"
      ]
      2 => array:2 [
        "CallCentreID" => "aknox"
        "FirstName" => "Alex"
      ]
      3 => array:2 [
        "CallCentreID" => "mking"
        "FirstName" => "Melissa"
      ]
      4 => array:2 [
        "CallCentreID" => "nrowecc"
        "FirstName" => "Neil"
      ]
      5 => array:2 [
        "CallCentreID" => "ejones"
        "FirstName" => "Emma"
      ]
      6 => array:2 [
        "CallCentreID" => "spurnell2"
        "FirstName" => "Simon"
      ]
    ]
    1 => array:5 [
      0 => array:2 [
        "CallCentreID" => "aknox"
        "Sales" => 1169
      ]
      1 => array:2 [
        "CallCentreID" => "ejones"
        "Sales" => 401
      ]
      2 => array:2 [
        "CallCentreID" => "mking"
        "Sales" => 767
      ]
      3 => array:2 [
        "CallCentreID" => "sdickerson"
        "Sales" => 1067
      ]
      4 => array:2 [
        "CallCentreID" => "wjones"
        "Sales" => 716
      ]
    ]
    2 => array:6 [
      0 => array:2 [
        "CallCentreID" => "aknox"
        "Quotes" => 3587
      ]
      1 => array:2 [
        "CallCentreID" => "ejones"
        "Quotes" => 400
      ]
      2 => array:2 [
        "CallCentreID" => "mking"
        "Quotes" => 6975
      ]
      3 => array:2 [
        "CallCentreID" => "nrowecc"
        "Quotes" => 3
      ]
      4 => array:2 [
        "CallCentreID" => "sdickerson"
        "Quotes" => 2686
      ]
      5 => array:2 [
        "CallCentreID" => "wjones"
        "Quotes" => 2734
      ]
    ]
  ]
]

The above is as close as I can get with the code I have which is;

$Users = User::where('Accesslevel', 'laravelcallcentre')->select('EmailAddress as CallCentreID', 'FirstName')->get(); 

        $Sales = Order::groupBy('CallCentreID')
            // ->whereDate('OrderDate', '=', date('2018-06-21'))
            ->whereIn('CallCentreID', $Users->pluck('CallCentreID'))
            ->where('Status', 'BOOKING')
            ->selectRaw('CallCentreID, count( * ) AS Sales')
            ->get();

        $Quotes = Order::groupBy('CallCentreID')
            // ->whereDate('OrderDate', '=', date('2018-06-21'))
            ->whereIn('CallCentreID', $Users->pluck('CallCentreID'))
            ->where('Status', 'QUOTE')
            ->selectRaw('CallCentreID, count( * ) AS Quotes')
            ->get();

        $collection = collect([$Users, $Sales, $Quotes]);

        $CCData = $collection->groupBy('CallCentreID');

Anyone got any better Ideas? I feel like im doing this completley wrong. I had this written out as a foreach loop but that ended up being four queries for every user, whihc stacked up fast.



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

How to update other columns alongside remember_token when logging out?

I have noticed that when logging out, laravel automatically sets remember_token value in the user table as evidenced from the screenshot from laravel-debugbar.

enter image description here

As you may have noticed from the screenshot is that am also setting the last_login column for the particular user that is logging out.

Problem is that as seen from the screenshot, it is running two update statements, one right after another not just one.

So is there way i can setup my application so i can run just one update statement when logging out so it can set the last_login, remember_token and updated_at in the user table for that particular user.

Thank you



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

Laravel - On Install New Library - Remove / Downgrade Vendor Packages

I have an issue.

I download my live application. There are so many packages are installed into the Vendor Directory. I need to install one more directory there through composer.

My Issues is that when I write command. Like

composer require jeremy-dunn/php-fedex-api-wrapper 

Whats happening, composer removing some packages and downgrading other packages then install the above Library.

I want that, Composer install that directory without removing and downgrading the vendors other packages.

Any Help will be appreciated.

Thanks



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

laravel: Why my transaction and try catch is not working properly in this code?

I haven't used any sort of pattern. I'm thinking to use traits. Sorry for this lump of code but I have nested data. I'm inserting multiple data and in the way of inserting into my tables. I'm not getting the exception error. It gives me success but I have no data on my tables. Sometime it rollbacks but doesn't gives me an error. How can I optimize the code below. Please help me. How to structure this code so database transaction works properly.

public function paymentGetaway(Request $request){
        DB::beginTransaction();
        try{
           $user = User::find(auth()->id())->first();

           //Check email if it already exists then update
           $existing_client = Client::where('email', $request->email)->where('is_deleted', 0)->first();
           if($existing_client){
               $existing_client->fname = $request->fname;
               $existing_client->lname = $request->lname;
               $existing_client->useru_id = auth()->id();
               $existing_client->updated_at = date('Y-m-d H:i:s');
               $result = $existing_client->save();

               /*Address section*/
               if($result){
                   $state = true;
                   $old_addr = Address::where('table', "client")->where('table_id', $existing_client->id)->get();

                   foreach ($old_addr as $key => $value) {
                       //Data exits
                       if($value->addr1 == $request->addr1 
                            && $value->zip == $request->zip 
                            && $value->state == $request->state
                            && $value->country == $request->country
                            && $value->city == $request->city )
                       {

                           $state = false;
                           $addr_id = $value->id;
                       }                   

                   }   

                   if($state){
                       $address = new Address();
                       $address_data = $request->only([
                           'addr1','zip', 'city','state', 'country', 'addr2'
                       ]);
                       $address_data['addr_type'] = "Temporary";
                       $address_data['table'] = "client";
                       $address_data['table_id'] = $existing_client->id;
                       $new_c_address = $address->create($address_data); 
                       $addr_id = $new_c_address->id;
                   }  

               }

               $order = $this->storeOrder($existing_client->id, $addr_id);
               $carts = $this->getCartItems();
               foreach ($carts as $key => $cart) {
                   $discount= $this->getDiscount($cart->product_id);

                   $order_items = new OrderItem();
                   $order_items->order_id = $order->id;
                   $order_items->inventory_id = $cart->inventory_id;

                   if($discount !== null){
                       $order_items->product_discount_id = $discount->id;
                   }

                   $order_items->quantity = $cart->quantity;
                   $order_items->userc_id = auth()->id();
                   $order_items->created_at = date('Y-m-d H:i:s');
                   $order_items->save();
               }                 


              /*Set the cart data to is_deleted = 0 which means inactive cart*/ 
              foreach($carts as $cart){
                   $cart->is_deleted = 1;
                   $cart->save();
              } 

              DB::commit();              

           }else{
               $client = new Client();
               $client_data = $request->only([
                   'fname', 'lname', 'email'
               ]); 
               $client_data['userc_id'] = auth()->id();       
               $new_client = $client->create($client_data);

               //Inserting to HR Customer
               $this->addCustomer($request);

               if($new_client){
                   //Store address
                   $address = new Address();
                   $address_data = $request->only([
                       'addr1','zip', 'city','state', 'country', 'addr2'
                   ]);
                   $address_data['addr_type'] = "Temporary";
                   $address_data['table'] = "client";
                   $address_data['table_id'] = $new_client->id;
                   $new_c_address = $address->create($address_data);            
                   $addr_id = $new_c_address->id;
               } 

               $order = $this->storeOrder($new_client->id, $addr_id);
               $carts = $this->getCartItems();
               $purchaseWithoutDis = 0;
               $purchaseWithDis = 0;
               $productCount = 0;
               $discountAmount = 0;
               // $discount_percent = 0;

               foreach ($carts as $key => $cart) {
                   $discount= $this->getDiscount($cart->product_id);

                   $order_items = new OrderItem();
                   $order_items->order_id = $order->id;
                   $order_items->inventory_id = $cart->inventory_id;

                   if($discount !== null){
                       $order_items->product_discount_id = $discount->id;
                   }

                   $order_items->quantity = $cart->quantity;
                   $order_items->userc_id = auth()->id();
                   $order_items->created_at = date('Y-m-d H:i:s');
                   $order_items->save();

                   $productCount +=$cart->quantity;                

                   //Collect Discount
                   if(!is_null($discount)){
                       if($discount->type == "flat"){
                           //Get the total sales   
                           $inventory = Inventory::find($order_items->inventory_id);
                           $purchaseWithoutDis +=$inventory->price * $cart->quantity;                       

                           $discountAmount += $discount->amount * $cart->quantity;

                           $priceAfterDiscount = $inventory->price - $discount->amount;
                           $purchaseWithDis += $priceAfterDiscount * $cart->quantity;

                       }else{                
                           //Get the total sales   
                           $inventory = Inventory::find($order_items->inventory_id);
                           $purchaseWithoutDis +=$inventory->price * $cart->quantity;

                           $disAmount = ($discount->amount/100) * $inventory->price;
                           $purchaseWithDis += $disAmount * $cart->quantity;

                           $discountAmount += $disAmount * $cart->quantity;                        
                       }
                       dd("here");
                   }else{
                       $inventory = Inventory::find($order_items->inventory_id);
                       $purchaseWithoutDis +=$inventory->price * $cart->quantity;
                       $purchaseWithDis += $inventory->price * $cart->quantity;
                   }
               }   
               if($discountAmount == 0){
                   $discountAmount = null;
               }
               //Create Invoice and Journal 
               $invoice = $this->storeInvoice($request,$purchaseWithoutDis,$order->id, $new_client->id, $discountAmount);
               $productDesc = $request->fname.' '.$request->lname.' Ordered '.$productCount.' items. Order No: '.$invoice->invoice_no;    

               $journal = $this->storeJournal($purchaseWithoutDis,$purchaseWithDis, $productDesc, $discountAmount);
               /*Set the cart data to is_deleted = 0 which means inactive cart*/ 
               foreach($carts as $cart){
                   $cart->is_deleted = 1;
                   $cart->save();
               } 
               DB::commit();            
               return response()->json(["Payment Successful"], 200);
           }  
       }catch(\Exception $e){
            DB::rollback();
            return response(["message"=>$e->getMessage()], 500);
       } 



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

which file need to change for reset password on laravel?

I worked on this file resources/views/auth/passwords/reset.blade.php. but not showing any changes. Where should I need to do?



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

Dompdf LoadView variable passing

i can't load able to pass a parameter to the dompdf function LoadView.

this is my controller:

  public function pst_affluiti(){

    $data=DB::all('Anagrafica')->get();
    $pdf = PDF::loadView('output',['data' => $data]);
  return $pdf->stream('output.pdf');
  }

my output.blade.php

<body>
 <div class="container">
<table class="table table-sm table-bordered" >
  <thead>
    <tr>
      <th scope="col-sm-1 col-6">Data Affl.</th>
      <th scope="col-sm-2">Cron.</th>
      <th scope="col-sm-2">Cognome</th>
      <th scope="col-sm-2">Nome</th>
      <th scope="col-sm-2">Data nac.</th>
    </tr>   
  </thead>
 <tbody>
        @foreach($data as $row)
            <tr>
               <td></td>
               <td></td>
               <td></td>
               <td></td>
            </tr>
           @endforeach 
         </tbody>
</table>
</div>
</body>

if i load a normal view of my query it works well.

Any suggest? Thanks in advance



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