lundi 31 août 2020

customer guard is not accessible in package's routes in laravel?

I have two guards in project default web and customer .both works fine. in project route when I check Auth::guard('customer')->check() it shows me true but at the same time when check it in my package's controller which is present inside vendor directory it shows me false . In the result it doesn't allow user to visit the route.

Strange thing is that when i use one guard at a time it work fines. but i cant use both at a same time. it also work fine when use different route for both guards I dont know why customer guard is not authenticated in package

package's routes

<?php

Route::group(['namespace' => 'Coldxpress\Ticket\Http\Controllers'], function () {
    Route::group(['middleware' => 'web'], function () {
        
        Route::group(['prefix' => 'tickets','middleware'=>['auth','auth:customer']], function () {
            Route::get('/{filter}', 'TicketController@index')->name('tickets.index');
            Route::post('/store', 'TicketController@store')->name('tickets.store');
            Route::post('/update', 'TicketController@updateTicket')->name('tickets.update');
            Route::get('/filtered_tickets/{filter}', 'TicketController@filteredTickets')->name('tickets.filtered');
            Route::get('/get_replies/{ticket_id}', 'TicketController@getReplies')->name('tickets.replies');
            Route::post('/store_reply/{ticket_id}', 'TicketController@storeReply')->name('tickets.store.reply');
            Route::post('/store_replies_image', 'TicketController@uploadReplyImage');
        });
        
    });
   
});

Package's Service Provide

<?php

namespace Coldxpress\Ticket;

use App\Models\Admin\Customer;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class TicketServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     * 
     * @var string
     */
    protected $namespace = 'Coldxpress\Ticket\Http\Controllers';

    public function boot()
    {
        dd(\Auth::guard());
        //dd(asset('ticket/assets/plugins/global/plugins.bundle.css'));
        $this->loadRoutesFrom(__DIR__ . '/routes/web.php');
        // $this->loadRoutesFrom(__DIR__ . '/routes/api.php');
        $this->loadViewsFrom(__DIR__ . '/resources/views', 'ticket');
        $this->loadMigrationsFrom(__DIR__ . '/database/migrations');
        $this->mapApiRoutes();

        //      $this->publishes([__DIR__.'/resources/ticket' => public_path()],
        //        'views');

    }

    public function register()
    {
    }


    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(__DIR__ . '/routes/api.php');
    }
}



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

Laravel 5: errno: 150 "Foreign key constraint is incorrectly formed

I'm trying to add a foreign key constraint to the notifications table migration (Laravel 5.8) I've tried this a few different ways. I separated them as suggested on other posts, but I haven't been able to find the solution to my problem.

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `appealmaker`.`notifications` (errno: 150 "Foreign key constraint is incorrectly formed")")

The migration looks like this:

class CreateNotificationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

        Schema::table('notifications', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('notifications');
    }
}


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

only one guard is working on route at a time in laravel

i have package inside my package i have web.php file . I want to limit these routes for two types of users. But the problem is only one type of user can access these routes. if i want web guard user i have to remove customer guard and vice versa. what could be the issue?

Route::group(['namespace' => 'Coldxpress\Ticket\Http\Controllers'], function () {
    Route::group(['middleware' => 'web'], function () {
        
        Route::group(['prefix' => 'tickets','middleware'=>['auth','auth:customer']], function () {
            Route::get('/{filter}', 'TicketController@index')->name('tickets.index');
            Route::post('/store', 'TicketController@store')->name('tickets.store');
            Route::post('/update', 'TicketController@updateTicket')->name('tickets.update');
            Route::get('/filtered_tickets/{filter}', 'TicketController@filteredTickets')->name('tickets.filtered');
            Route::get('/get_replies/{ticket_id}', 'TicketController@getReplies')->name('tickets.replies');
            Route::post('/store_reply/{ticket_id}', 'TicketController@storeReply')->name('tickets.store.reply');
            Route::post('/store_replies_image', 'TicketController@uploadReplyImage');
        });
       
    });
   
});


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

multiple guards are not working on routes of laravel package?

I have laravel package in its routes. I want to add two guards if any user related to these guard is authenticated it should go on that route but it is not working. if i remove customer route the default guard work if I remove default guard then customer route work don't know what is the problem

routes

Route::group(['namespace' => 'Coldxpress\Ticket\Http\Controllers'], function () {
    Route::group(['middleware' => ['web','auth:customer']], function () {
        Route::group(['prefix' => 'tickets'], function () {
            Route::get('/{filter}', 'TicketController@index')->name('tickets.index');
            Route::post('/store_replies_image', 'TicketController@uploadReplyImage');
        });
    });
});


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

How to sync if model id is hidden field?

I'm trying to sync data to pivot table for my model. But my Recipe model has an hidden id field. Like this;

protected $hidden = ['id', 'content', 'difficulty_id'];

And when I try to sync relationships to pivot table, recipe_id becomes zero. If I remove id from $hidden above, it sync id without any problem. I also tried to call makeVisible("id") for the model but didn't help.

$changedMeals = $record->meals()->sync($meals);

How can I sync id when keeping it in $hidden?

Thank you very much...



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

How to check table names in different databases in laravel

I have two databases . one for project and one for telescope. I want to check the tables name in each database how i can to this?

if i have one database i can do this

$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames()

but Dont know what to do for multiple databases



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

Laravel 5.6 querying related tables to filter results based on multiple columns from both the tables

Hello guys I am working on a project build using laravel 5.6, I want to filter results in search, based on conditions that applies to different columns from both the tables.

I have two tables one is Adverts and other is Vehicle_Specifications

Adverts has columns:

[id, user_id, category_id, status_id, promotion_id,title, description, state, city, cost, slug]

Adverts table is also related to Ad_Images table which holds all the images of the adverts according to their ids.

Vehicle_Specifications has columns:

[id, advert_id, brand, model, year, body_type, doors, color, milage, fuel_type]

Scenario: Now I want to filter data from adverts table based on status_id, state, city then get those adverts which has filters matching in vehicle_specifications table like brand = honda, model = civic etc. and also paginate the result.

Query that I have tried:

$filtered_vehicles = Ad::with('vehiclespecification')->where([['state', $state]])->whereHas('vehiclespecification', function ($query) {
                $query->where('brand', 'like',$_GET['make'].'%');
            })->paginate(50);

the above query does give me some results but it is not perfect. Any help would be much appreciated.

Thank you



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

Laravel 7 | how can i clone eloquent object and add entry in table with all relationship

I want to clone one product with all its relationship like price, attributes, images etc.

also, price and attribute have another relationship (nested relationships)

is there any easy way I can clone all this with few line of code?



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

Natural sort issue with laravel eloquent [closed]

hi i have problem with the natural sort using eloquent values are as in column and i want result as in can any one please help me with this issue example [11,A111,A1A1,P1,P11,P2] Result ASC : [11,A111,A1A1,P1,P2,P11]



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

Change() on database column not working in laravel migration?

about three monthe ago I write a migration to change column type from string to integer which was working fine at that time now it is giving this error

 public function up()
    {
        Schema::table('delivery_zones', function (Blueprint $table) {
            $table->Integer('income_rate_zone')->nullable()->change();
            $table->Integer('expense_rate_zone')->nullable()->change();
            // DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');

        });
    }

I can use raw db query but i want to avoid that because i have used this method at many places. i have 2.10 version of doctrine/dbal

Error

  Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, CHANGE expen...' at line 1 (SQL: ALTER TABLE delivery_zones CHANGE income_rate_zone income_rate_zone INT CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, CHANGE expense_rate_zone expense_rate_zone INT CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`)

  at C:\Projects\temp-xdock\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, CHANGE expen...' at line 1")


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

how to authenticate web login page by api in laravel

I created an API for login in laravel. In postman it is working properly. Now I want to use that api in my web form. I have an login form and fill email and password then click on button then my login api should be run and should be redirect on dashboard.

API route is (in, routes/api.php):

Route::post('login', 'apifolder\AuthController@login');

controller for api is:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string',
        'remember_me' => 'boolean'
    ]);

    $credentials = request(['email', 'password']);
    if(!Auth::attempt($credentials))
        return response()->json([
            'message' => 'Unauthorized',
            'status' => '401',
        ], 401);

    $user = $request->user();
    
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    if ($request->remember_me)
        $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();
    return response()->json([
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateTimeString(),
            'status' => '200',
    ]);
}

Above API is working properly in postman.

Now I want to use it from my web form.

routes are(in, routes/web.php):

Route::get('/','loginController@index')->name('login');
Route::POST('/login','loginController@login_submit')->name('login.submit');
Route::get('/dashboard','loginController@dashboard')->name('dashboard');

controller is:

public function login_submit(Request $request)
{
   $data1 = [
       'email' => $request->email, 
       'password' => $request->password,
   ];

   $curl = curl_init();

   curl_setopt_array($curl, array(
       CURLOPT_URL => "http://localhost/interview_assign/public/api/auth/login",
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_ENCODING => "",
       CURLOPT_MAXREDIRS => 10,
       CURLOPT_TIMEOUT => 30000,
       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
       CURLOPT_CUSTOMREQUEST => "POST",
       CURLOPT_POSTFIELDS => json_encode($data1),
       CURLOPT_HTTPHEADER => array(
           "accept: */*",
           "accept-language: en-US,en;q=0.8",
           "content-type: application/json",
            "X-Requested-With: XMLHttpRequest"
       ),
   ));

   $response = curl_exec($curl);
   $err = curl_error($curl);

   curl_close($curl);

   if ($err) {
       echo "cURL Error #:" . $err;
   } else {
   $response = json_decode($response);
   
        if($response->status == '200')
        {
            return redirect()->route('dashboard');
        }
        else
        {
            return view('login',compact('response'));
        }
   }

}    

public function dashboard()
{
    return view('dashboard');
}

login blade is:

 <form action="" method="post">
    @csrf
    <div class="input-group mb-3">
      <input type="email" class="form-control" name="email" placeholder="Email">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-envelope"></span>
        </div>
      </div>
    </div>
    <div class="input-group mb-3">
      <input type="password" class="form-control" name="password" placeholder="Password">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-lock"></span>
        </div>
      </div>
    </div>
    <div class="row">
      <!-- /.col -->
      <div class="col-4">
        <button type="submit" class="btn btn-primary btn-block">Sign In</button>
      </div>
      <!-- /.col -->
    </div>
  </form>

When I login, then I got correct response. and also redirect on dashboard. But how to use response api token to authenticate my dashboard. Means, if I am not logged in then dashboard should not be access. Dashboard should be access only when I am logged in.

In postman after login, i got token then I copy token and paste in key in dashboard api and get the dashboard data. But how to authenticate in my web login and dashboard?



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

dimanche 30 août 2020

Export data with parameter year and month Laravel + Mysql

I got stack when i want to implement export data with parameters, this is the code from controller

public function export_byMonth(Request $request)
{
    return Excel::download(new ProjectMSelected($request->m , $request->y), 'ProjectMonthly_'.$request->m.'_'.$request->y.'.xlsx');
}

Note M is Month and Y = is Year

and this is the code for export using maatwebsite/excel.

namespace App\Exports;

use App\table2;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ProjectMSelected implements FromView, WithHeadings
{
    use Exportable;

  public function __construct($m , $y)
  {
      $this->m = $m;
      $this->y = $y;
  }
  public function headings(): array
  {
   return [
      'Code Project' ,
      'Name',
      'Directorates',
      'Division', 
      'Scope',
      'Priority',
      'Progress',
      '%',
      'Remarks',
      'Plan',
      'pdate',
      'PM',
      'CO PM',
  ];
}
public function view(): View
{
    return view('report.excel.report_monthly_per_project', [
        'project_array' => table2::whereRaw('YEAR(tgl_masuk) = ',$this->y ,'And Month(tgl_masuk) =', $this->m)->get()
    ]);
}
}

it's still parsing the error message like this, how to solve the error ?

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 (SQL: select * from `projectmonthlyview2` where Month(tgl_masuk) = YEAR(tgl_masuk) =)


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

Way of passing API data to the view asynchronously?

I'm super new to Laravel and I was wondering what the best optimization for the following issue would be.

Right now I have a call to an external API to a project management application that retrieves a list of tasks. This call occurs in my controller and the data is then passed to a dashboard view to be rendered with Vue. I'd normally just have this API call happen entirely on the front-end, but the project management application uses OAuth 2, so I'm authenticating and calling the endpoint on the server-side.

This technically works fine, but sometimes loading my app's dashboard takes a little longer to load than I'd like. I believe the culprit is the fact that the page makes the API call on each reload.

My question is this: is there a way to pass the API response data to the view asynchronously? In my ideal scenario the view would load with just a loading icon and then show the tasks once they were received from the project management server. Like I said: I'd know how to do this using AJAX and the like, but there's an access token and OAuth involved.

Hopefully that makes sense and isn't a totally silly question, but any suggestions at this time would be helpful. Thanks!



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

Laravel | Unable to get array of strings searched from the database

What is the ultimate use-case ?

My mobile App is going to send a query for https://example.com/public/api/classifiedsearch?search=name%3Aorange+apples+grapes+onions

& I'd expect the results to include data from the products table with name containing the term in the search strings above. The problem that I'm facing is that, i don't get any results matched at all. I have confirmed by printing that $terms (referred below) is indeed able to capture the values from search as an array & the for loop is working the number of times equalent to the number of words in search string. But no results returned. Any hint/suggestions to why isn't it mapping ????

Here's what i have done in my APIcontroller for classifiedsearch

public function index(Request $request)
{
    try{
       $queryString = $request->input('search',null);
         $terms = explode(" ",$queryString);
    
    // print_r($terms);
              
      if ( !empty( $request->query('search')))
      {
                   
        $products = Product::whereHas('store', function ($query) use ($terms) 
               {
                    foreach ($terms as $term) 
                    {
                     //    print_r("CHECKING FOR $term");
                    $query->where('name', 'like', '%' . $term . '%');
                    
                    }
               })->get();
          
      }
            
      else 
      {       
           $products = $this->productRepository->all(); 
      }
           
    } catch (RepositoryException $e) {
        return $this->sendError($e->getMessage());
    }

    return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
}

Output :

{"success":true,"data":[],"message":"Products retrieved successfully"}

Can someone please help ??



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

samedi 29 août 2020

checked for multiple checkbox in update form

This is my blade file for the update form. So how I should I retrieve those data in the form by checked the checkbox.

 <div class="form-group row">
                <label class="col-md-3 col-form-label form-control-label" for="input-description">Hobbies</label>
                <div class="col-md-9">
                    <input type="checkbox" name="hobbies[]" class="form-control-label" value="football" > Football
                    &nbsp; <input type="checkbox" name="hobbies[]" class="form-control-label" value="basketball"> Basketball
                     <input type="checkbox" name="hobbies[]" class="form-control-label" value="table_tennis"> Table Tennis
                     <input type="checkbox" name="hobbies[]" class="form-control-label" value="hockey"> Hockey
                     <input type="checkbox" name="hobbies[]" class="form-control-label" value="others"> Others
                </div>
            </div>
 </div>

This is my Controller

public function edit($id)
{
    $student=Student::find($id);
    return view('students.edit', compact('student'));
}

In the database, .hobbies are stored in hobbies column like this

["basketball","football",'table_tennis']


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

i have this problem and i have tryed more once but didn't work [duplicate]

have searched about the problem and have found (php artisan cache: clear and php artisan migrate: install) but dose not work give me the same errors



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

How to bind or inject variables from service providers to model class laravel

I have this class called Book and I want to have one global variable sort of thing in that class which consist of a exchange rate (For whole data / model) I am trying to use service containers to inject the variable in it but I am sort of loss here

I tried this code in my AppServiceProvider.php in register()

$variable = 'something';
$this->app->bind('App\Models\FrontEnd\Book', function ($app) {
    return new $variable;
});

But it does not work .



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

Insert an Array of Checkbox Values with Laravel, Vue,js, and Axios

I am making a simple Workorder Form. I have two tables: workorders and units. Workorder model has many Unit and Unit model belongs to Workorder. I need to insert each array value (id only) into the units table. I will have multiple records to insert per query. What I have below is clearly not working.

The View

              <table>
                    <thead>
                    <tr>
                        <td>MFG</td>
                        <td>Build</td>
                        <td>SN</td>
                        <td>Type</td>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="hp in hps">
                        <td>
                            <input type="checkbox" :value="hp.id" v-model="checkedhps"><span class="checkbox-label"> </span>
                        </td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    </tbody>
                </table>

                <form @submit.prevent="onSubmit">
                   <div>
                     <input type="hidden" autocomplete='off'>
                   </div>
                   <div>
                     <button type="submit">Create</button>
                   </div>
                </form>

The Script

    export default {
    data: function() {
                return {
                    checkedhps:[],
                }
            },
            methods: {
                onSubmit(){
                    axios.post('/checkedHps', this.$data)
                    .then((response) => {
                        if(response.status===200) {
                           this.$router.push('/customer/'+this.customer.id)
                        }
                    })
                }
             }
         }

The Controller

public function store(Request $request){
    $hps = $request->input('checkedhps');
    foreach($hps as $hp){
        hp_wo::create($hp);
        }
    }


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

Saving Dynamic Select Values in database - Laravel

I am working an multiple select Boxes in a form which are rendered dynamically.

Here in the below scenario I am mapping the selecttion to the parent title.

The example result is { "1": [ 2 ], "2": [ 1, 3 ] }

        <table class="table">
          <thead>
            <tr>
              <td>Variation Name</td>
              <td>Variation Values</td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Size</td>
              <td>
                <select multiple="multiple">
                  <option value="2">Medium</option>
                </select>
              </td>
            </tr>
            <tr>
              <td>Color</td>
              <td>
                <select multiple="multiple">
                  <option value="1">White</option>
                  <option value="3">Blue</option>
                  <option value="4">Black</option>
                </select>
              </td>
            </tr>
          </tbody>
        </table>

I am passing the result to the Laravel Controller so that I could save the response..

I am not sure how do I save the data to the database..

public function itemsStore(Request $request)
    {
        $items_arrays = array($request['itemsArray'], true);
        dd(items_arrays);
    }

The dd result is

array:2 [
  0 => "{"1":[2],"2":[1,3]}"
  1 => true
]

How do I save the values to database in the respective format

item_id | item_value_id
   1             2
   2             1
   2             3


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

Role-Permission using Entrust Package for Project

Can anyone give Simple example for creating role based authentication of entrust package for Laravel as backend & Angular as FrontEnd



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

Laravel | Unable to get the search results filtered for *multiple keywords* | Returns all from the table now

Code(Controller):

    public function index(Request $request)
    { 
      
     
        try{
            $this->productRepository->pushCriteria(new RequestCriteria($request));
            $this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
            $this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
            if($request->get('trending',null) == 'week'){
                $this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
            }
            else{
                $this->productRepository->pushCriteria(new NearCriteria($request));
            }

          $queryString = $request->query;
  
        if ($queryString = $request->query('search')) {
       //     [$column, $term] = explode(':', $queryString);

       $terms = explode(" ", request('q'));

$products = Product::query()
    ->whereHas('store', function ($query) use ($terms) {
        foreach ($terms as $term) {
            // Loop over the terms and do a search for each.
            $query->where('name', 'like', '%' . $term . '%');
        }
    })
  
    ->get();
  

else
        
           $products = $this->productRepository->all(); 
    
       
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
    }

I'm getting the complete set of data within the product table as of now. My intension is to be able to filter the results with matching keywords as in $terms . Can someone please help figure out what's missing in filtering above ?



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

vendredi 28 août 2020

Laravel 6.0 input::value"old(' ')"

i am using this code but i am not working old function i have used both using this <?php echo old('title'); ?> AND Both Are Not workin please Help

 <form action="<?php echo route('post.create') ?>" method="GET">
 @csrf
        <input type="text" name="title" value="<?php echo old('title');  ?>"></br>
        <textarea name="contant" id="" cols="30" rows="10"><?php echo old('contant'); ?></textarea>


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

Laravel | Unable to get multiple keywords mapped to return combined results | Class 'App\Http\Controllers\API\Post' not found

Issue :

I'm trying to get multiple keywords searched in a single query, but for some reason I'm getting this error always :

[2020-08-29 03:50:02] development.ERROR: Class 'App\Http\Controllers\API\Post' not found {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Class 'App\\Http\\Controllers\\API\\Post' not found at /home2/examplehat/public_html/shopper/app/Http/Controllers/API/ClassifiedSearchAPIController.php:78)
[stacktrace]

Here's my controller's index function :

    public function index(Request $request)
    { 
      
     
        try{
            $this->productRepository->pushCriteria(new RequestCriteria($request));
            $this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
            $this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
            if($request->get('trending',null) == 'week'){
                $this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
            }
            else{
                $this->productRepository->pushCriteria(new NearCriteria($request));
            }

//            $this->productRepository->orderBy('closed');
//            $this->productRepository->orderBy('area');
        
          $queryString = $request->query;
          $terms = explode(" ", request('q'));
        if ($queryString = $request->query('search')) {
           //  [$column, $term] = explode(':', $queryString);

            $products = Post::query()              //----PROBLEM HERE
    ->whereHas('name', function ($query) use ($terms) {
        foreach ($terms as $term) {
            // Loop over the terms and do a search for each.
            $query->where('name', 'like', '%' . $term . '%');
        }
    })->get();
  
    //    $products = Product::where('name', 'like', '%' . $term . '%')->get();
}

else
        
           $products = $this->productRepository->all(); 
           
        //  $products = Product::where('name', 'like', '%' . 'chilli' . '%')->get();
    
       
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
    }

Can someone please help me understand what needs to be done to fix the error stated ? I tried use App\Post; but it didn't help.



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

Laravel | Unable to get results of matching substrings

Question :

I have a table called product with some bunch of columns. One of which is name. The problem is :

Sample entries:

  1. name: Salt Powder.
  2. name: Chilli powdeR

The problem

When i do a query for https://example.com/public/api/products?search=name%3Apowder I get 0 results .

Expectation is to return

Salt Powder & Chilli powdeR since the term "powder" is common in both.

Now when i do a query for https://example.com/public/api/products?search=name%3Asalt+powder , i get Salt powder as the result.

Here's my controller & what i have been trying to implement in the index :

    public function index(Request $request)
    {
     
     if (Query::has('search')) {              ------>>> I know that something is terribly wrong here.
        $queryString = Query::get('search');
        $products = Products::where('name', 'LIKE', "%$queryString%")->orderBy('name')->paginate(5);
    }   
        try{
            $this->productRepository->pushCriteria(new RequestCriteria($request));
            $this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
            $this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
            if($request->get('trending',null) == 'week'){
                $this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
            }
            else{
                $this->productRepository->pushCriteria(new NearCriteria($request));
            }

            $products = $this->productRepository->all();

        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
    }

My productRepository.php:

<?php

namespace App\Repositories;

use App\Models\Product;
use InfyOm\Generator\Common\BaseRepository;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;

    class ProductRepository extends BaseRepository implements CacheableInterface
    {
    
        use CacheableRepository;
        /**
         * @var array
         */
        protected $fieldSearchable = [
            'name',
            'seokeywords',
            'price',
            'discount_price',
            'description',
            'capacity',
            'package_items_count',
            'unit',
            'itemsAvailable',
            'featured',
            'store_id',
            'category_id',
            'brand_id'
        ];
    
        /**
         * Configure the Model
         **/
        public function model()
        {
            return Product::class;
        }
    
        /**
         * get my products
         **/
        public function myProducts()
        {
            return Product::join("user_stores", "user_stores.store_id", "=", "products.store_id")
                ->where('user_stores.user_id', auth()->id())->get();
        }
    }

Can someone please help to understand what or which statement should i modify ? I've tried changes but most attempts ended in errors. Any help is much appreciated. I can share any files that you guys may be interested to peak into



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

Laravel This page isn’t working HTTP ERROR 500 [closed]

I just deleted an image from the images folder of my website in cpanel, and then when i refresh my website it gave me an error page as this

enter image description here

i don't know what actually happened, someone please help me to fix this issue, i did find the .htaccess file in the project directory, later i had to upload the one from my local machine,

Here's my .htaccess file

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
<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} (.+)/pubic$
    RewriteRule ^ %1 [L,R=301]

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

    # Disable index view
    Options -Indexes

    # Hide a specific file
    <Files .env>
        Order allow,deny
        Deny from all
    </Files>
</IfModule>



<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On 
    # Default directive
    ExpiresDefault "access plus 1 month"
    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"
    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    # CSS
    ExpiresByType text/css "access plus 1 month"
    # Javascript 
    ExpiresByType application/javascript "access plus 1 year"
</IfModule>

# BEGIN cPanel-generated php ini directives, do not edit
# Manual editing of this file may result in unexpected behavior.
# To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
# For more information, read our documentation (https://go.cpanel.net/EA4ModifyINI)
<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 300
   php_value max_input_time 600
   php_value max_input_vars 1000
   php_value memory_limit 32000M
   php_value post_max_size 80M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php74"
   php_value upload_max_filesize 2M
   php_flag zlib.output_compression Off
</IfModule>
<IfModule lsapi_module>
   php_flag display_errors Off
   php_value max_execution_time 300
   php_value max_input_time 600
   php_value max_input_vars 1000
   php_value memory_limit 32000M
   php_value post_max_size 80M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php74"
   php_value upload_max_filesize 2M
   php_flag zlib.output_compression Off
</IfModule>
# END cPanel-generated php ini directives, do not edit

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php73” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

my error_log

[28-Aug-2020 12:41:01 UTC] PHP Fatal error:  Uncaught ErrorException: include(/home/chatigra/public_html/goworkas/vendor/composer/../../app/Exceptions/Handler.php): failed to open stream: No such file or directory in /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php:444
Stack trace:
#0 /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php(444): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'include(/home/c...', '/home/chatigra/...', 444, Array)
#1 /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php(444): include()
#2 /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/home/chatigra/...')
#3 [internal function]: Composer\Autoload\ClassLoader->loadClass('App\\Exceptions\\...')
#4 [internal function]: spl_autoload_call('App\\Exceptions\\...')
#5 /home/chatigra/public_html/goworkas/vendor/laravel/framework/src/Illuminate/Container/Container.php(779): ReflectionClass->__construct('App\\Exceptions\\...')
#6 /home/chatigra/public_html/gowork in /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php on line 444
[28-Aug-2020 12:41:02 UTC] PHP Fatal error:  Uncaught ErrorException: include(/home/chatigra/public_html/goworkas/vendor/composer/../../app/Exceptions/Handler.php): failed to open stream: No such file or directory in /home/chatigra/public_html/goworkas/vendor/composer/ClassLoader.php:444
Stack trace:


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

"composer update" Laravel packages problem can´t update

I just updated my laravel v5.6 to v5.7. While doing so, i had the following problem with my package and i don`t understand what is the actual problem and with that the solution, i only have a guess that it is about illuminate/support https://github.com/kemalevren/geth-php#readme

Error:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install kemalevren/geth-php v1.1.6
    - Conclusion: don't install kemalevren/geth-php v1.1.5
    - Conclusion: don't install kemalevren/geth-php v1.1.4
    - Conclusion: don't install kemalevren/geth-php v1.1.3
    - Conclusion: don't install kemalevren/geth-php v1.1.2
    - Conclusion: don't install kemalevren/geth-php v1.1.1
    - Conclusion: remove laravel/framework v5.7.29
    - Conclusion: don't install laravel/framework v5.7.29
    - Conclusion: don't install laravel/framework v5.7.28
    - Conclusion: don't install laravel/framework v5.7.27
    - Conclusion: don't install laravel/framework v5.7.26
    - Conclusion: don't install laravel/framework v5.7.25
    - Conclusion: don't install laravel/framework v5.7.24
    - Conclusion: don't install laravel/framework v5.7.23
    - Conclusion: don't install laravel/framework v5.7.22
    - Conclusion: don't install laravel/framework v5.7.21
    - Conclusion: don't install laravel/framework v5.7.20
    - Conclusion: don't install laravel/framework v5.7.19
    - Conclusion: don't install laravel/framework v5.7.18
    - Conclusion: don't install laravel/framework v5.7.17
    - Conclusion: don't install laravel/framework v5.7.16
    - Conclusion: don't install laravel/framework v5.7.15
    - Conclusion: don't install laravel/framework v5.7.14
    - Conclusion: don't install laravel/framework v5.7.13
    - Conclusion: don't install laravel/framework v5.7.12
    - Conclusion: don't install laravel/framework v5.7.11
    - Conclusion: don't install laravel/framework v5.7.10
    - Conclusion: don't install laravel/framework v5.7.9
    - Conclusion: don't install laravel/framework v5.7.8
    - Conclusion: don't install laravel/framework v5.7.7
    - Conclusion: don't install laravel/framework v5.7.6
    - Conclusion: don't install laravel/framework v5.7.5
    - Conclusion: don't install laravel/framework v5.7.4
    - Conclusion: don't install laravel/framework v5.7.3
    - Conclusion: don't install laravel/framework v5.7.2
    - Conclusion: don't install laravel/framework v5.7.1
    - Installation request for kemalevren/geth-php ^1.1 -> satisfiable by kemalevren/geth-php[v1.1.0, v1.1.1, v1.1.2, v1.1.3, v1.1.4, v1.1.5, v1.1.6].
    - Conclusion: don't install laravel/framework v5.7.0
    - kemalevren/geth-php v1.1.0 requires illuminate/support 5.1.*|5.2.*|5.3.*|5.4.*|5.5.* -> satisfiable by laravel/framework[5.2.x-dev, 5.3.x-dev, 5.4.x-dev, 5.5.x-dev], illuminate/support[5.1.x-dev, 5.2.x-dev, 5.3.x-dev, 5.4.x-dev, 5.5.x-dev, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.13, v5.4.17, v5.4.19, v5.4.27, v5.4.36, v5.4.9, v5.5.0, v5.5.16, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44].
    - Can only install one of: laravel/framework[5.7.x-dev, 5.2.x-dev].
    - Can only install one of: laravel/framework[5.7.x-dev, 5.3.x-dev].
    - Can only install one of: laravel/framework[5.7.x-dev, 5.4.x-dev].
    - Can only install one of: laravel/framework[5.7.x-dev, 5.5.x-dev].
    - don't install illuminate/support 5.5.x-dev|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.0|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.16|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.17|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.2|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.28|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.33|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.34|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.35|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.36|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.37|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.39|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.40|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.41|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.43|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.5.44|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support 5.1.x-dev|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support 5.2.x-dev|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support 5.3.x-dev|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support 5.4.x-dev|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.1|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.13|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.16|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.2|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.20|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.22|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.25|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.28|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.30|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.31|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.41|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.6|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.1.8|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.0|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.19|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.21|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.24|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.25|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.26|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.27|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.28|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.31|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.32|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.37|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.43|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.45|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.6|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.2.7|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.3.0|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.3.16|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.3.23|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.3.4|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.0|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.13|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.17|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.19|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.27|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.36|don't install laravel/framework 5.7.x-dev
    - don't install illuminate/support v5.4.9|don't install laravel/framework 5.7.x-dev
    - Installation request for laravel/framework 5.7.* -> satisfiable by laravel/framework[5.7.x-dev, v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.12, v5.7.13, v5.7.14, v5.7.15, v5.7.16, v5.7.17, v5.7.18, v5.7.19, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.23, v5.7.24, v5.7.25, v5.7.26, v5.7.27, v5.7.28, v5.7.29, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].

My composer.json includes ""kemalevren/geth-php": "^1.1"," and i added the following to my composer.lock

{
            "name": "kemalevren/geth-php",
            "description": "A PHP wrapper to the geth JSON-RPC API.",
            "keywords": [
                "geth",
                "php",
                "eth"
            ],
            "license": "MIT",
            "authors": [
                {
                    "name": "Kemal Evren",
                    "email": "hi@kemalevren.com"
                }
            ],
            "type": "project",
            "require": {
                "php": ">=7.0",
                "guzzlehttp/guzzle": "~6.3",
                "illuminate/support": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*|5.5.*|5.6.*|5.8.*"
            },
            "require-dev": {
                "phpunit/phpunit": "6.5.*"
            },
            "autoload": {
                "psr-4": {
                    "kemalevren\\Geth\\": "src/"
                }
            },
            "extra": {
                "laravel": {
                    "providers": [
                        "kemalevren\\Geth\\Laravel5\\GethPhpServiceProvider"
                    ],
                    "aliases": {
                        "JsonRpc": "kemalevren\\Geth\\Laravel5\\Facades\\JsonRpc"
                    }
                }
            }
        },


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

how to get sum with whereIn/whereBetween using laravel query builder?

I have getting wrong value from query. can anyone help me to correct my query in laravel project. mysql code :

select SUM(amount) as total from `sales` 
where `bankid` = 1 
and `month` = 8 
and `year` = 2020
and userid in (select userid from user where bank_id=2 AND (usertype=1 OR usertype=2))

Laravel code :

function test($bank_id,$usertype,$month=NULL,$year=NULL){
    $query = Sales::query();
    if(is_numeric($bank_id)){
        $query->where('bankid',$bank_id);
    }
    if($month)
    $query = $query->where('month', $month);
    
    if($year)
    $query = $query->where('year', $year);

    $query = $query->select(DB::raw("SUM(amount) as total"));
    if(is_numeric($usertype)){
        $query->whereIn('userid',function ($query) use($bank_id,$usertype) {
            $query->select(DB::raw('userid'))
            ->from('user');            
            if(is_numeric($bank_id)){
                $query->where('bank_id',$bank_id);
            }                 
            if($usertype==1){
               // $query->whereBetween('usertype', [1, 2]);
                $query->where('usertype', 1);
                $query->orWhere('usertype', 2);
            } else {
                $query->where('usertype',$usertype);
            }
        });
    } 
    return $query->get()->toarray()[0]['total'];
}

When i used querylog and got the query:

DB::connection()->enableQueryLog(); 
dd($query->toSql(), $query->getBindings());

select SUM(amount) as total from `slaes` 
where `bankid` = 1 
and `month` = 8 
and `year` = 2020 
and `userid` in (select userid from `user` where `bank_id` = 1 and `usertype` =1 OR `usertype` = 2)

I need to make it from and userid in (select userid from user where bank_id = 1 and usertype =1 OR usertype = 2) to and userid in (select userid from user where bank_id = 1 and (usertype =1 OR usertype = 2))

And can anyone suggest to minimize loading issue while running this query. i have almost 1M records in my database.
Thank you.



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

Laravel - Routes & Middleware - Location change from version 5.2 to 5.3

I'm currently upgrading a Laravel application from 5.2 to a current version (7.x). Actually I'm doing the the upgrade from Laravel 5.4 to 5.5. Now I recognized, that in 5.3 the location of routes.php (former app\Http) changed to routes\web.php and routes\api.php. I'm having trouble, to transfer the different routes into the specific files.

I've copied the files of the routes folder into the project and changed the RouteServiceProvider accordingly to the github code from 5.5 (https://github.com/laravel/laravel/blob/5.5/app/Providers/RouteServiceProvider.php):

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * The path to the "home" route for your application.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }
}

My former routes.php looked like this:

<?php

Route::group(['middleware' => 'web'], function () {
// all web routes without authorization go here:
...

    Route::group(['middleware' => 'auth'], function () {
    // all routes which need authorization go here:
    ...

    });
});

Now I've put all routes without authorization into web.php and all routes which need authorization into the api.php file.

But this configuration does not work. It does not show the pages. The crazy thing is, that also no error logs are produced, so laravel.log is empty.

What is wrong in the RouteServiceProvider or what do I have to change that my routes are working again.

I appriciate any help or hint! Many thanks in advance!



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

Laravel: route for static file name issue

I want to make kind of api for static files with versioning in such way:

public/js

public/js
  ├ script-1.1.js
  ├ script-1.2.js
  ├ ...
  └ script-2.1.js

routes/web.php


Route::get('/js/{version}/script.js', function ($version) {
    return File::get(public_path() . '/js/script-'.$version.'.js');
})->where('version', '^\d+(\.\d+)*$');

The problem is that Laravel ignores this route anyway and trying to find static file.

I.e. this will return 404 page:

Route::get('/js/test/script.js', function() {
    return response('Echo', 200)
           ->header('Content-Type', 'text/plain');
});

But this will return 'Echo':

Route::get('/js/test', function() {
    return response('Echo', 200)
           ->header('Content-Type', 'text/plain');
});

How to perform routing on URL which has filename in the end? I can't find similar issues still or any examples.



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

Redirecting issues in laravel

I'm working on laravel which is hosted on server, It is hosted on sub directory when i open project link which is hosted on sub domain such as

https://mymaindomain/subdirectory/

it redirects me to

https://mymaindomain/subdirectory/server.php

I want to remove server.php from url.



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

jeudi 27 août 2020

Laravel Middleware not executing functions

I have this Locale middleware which sets language based from settings on DB

    public function handle($request, Closure $next)
    {
        $HQ = Branch::where('is_hq', 1)->where('is_active', 1)->first();

        $Company = GlobalVariable()->branch($HQ)->all()->whereIn('group', array(1, 3, 9))->keyBy('key');
        $locale = strtolower($Company['bi__language']->value);

        if ($locale === 'eng') {
            \App::setlocale('en');
        } else {
            \App::setlocale($locale);
        }

        return $next($request);
    }

but i need to get the branch where the current user is so i need to get the Auth::id() first so i changed my code to this to access Auth.

     public function handle($request, Closure $next)
     {
        $response = $next($request);

        $HQ = Branch::where('is_hq', 1)->where('is_active', 1)->where('user_id', \Auth::id())->first();

        $Company = GlobalVariable()->branch($HQ)->all()->whereIn('group', array(1, 3, 9))->keyBy('key');
        $locale = strtolower($Company['bi__language']->value);

        if ($locale === 'eng') {
            \App::setlocale('en');
        } else {
            \App::setlocale($locale);
        }

        return $response;
    }

Now i am getting the current user logged in but the problem is it is not executing this block of code

if ($locale === 'eng') {
   \App::setlocale('en');
} else {
    \App::setlocale($locale);
}

Note: the code wihout Auth is executing this block of code but the second isn't

Am i missing something here?



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

Laravel Passport Oauth Customize page / auto redirect

Hi I would like to ask about laravel passport oauth confirmation page

enter image description here

This is the page when we are asked for authorization, I would like to customize this page, or even possible to skip this page to always authorize anyway since the requestor will be just an internal application

I tried to google this but no luck. Is that possible? if so please tell me how to, or any link will be greatly appreciated



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

When i write a join query in laravel, it get 'Allowed memory exhausted'

I wrote join query in laravel project. there are 1M records in the database. when i load the page it is showing 'Allowed memory exhausted' message. can anyone help me to solve this issue? My code:

function test($bank_id=NULL,$month=NULL,$year=NULL,$userType=NULL){
    $query = Sales::query();
    if($bank_id){
        $query = $query->where('bankid', $bank_id);
    }
    
    if($month)
    $query = $query->where('month', $month);
    
    if($year)
    $query = $query->where('year', $year);
    
    $query = $query->select(DB::raw("SUM(amount) as total"));
    if($userType!="all"){   
        $query->join('user', function($join)
        {
            $join->on('user.userid', '=', 'sales.userid');
            $join->on('user.bank_id', '=', 'sales.bankid');
        });
        if($userType==1){
            $query->where('usertype','=', 1)->orWhere('usertype','=', 2);
        } else {
            $query->where('usertype', '=', $userType);
        }
    }
    return $query->get()->toarray()[0]['total'];
}

mysql Query

SELECT SUM(sales.amount) as total FROM `sales`  INNER JOIN user
ON sales.userid = user.userid 
And sales.bankid = user.bank_id

WHERE sales.bankid=1
user.bank_id=1
AND sales.month=8
AND sales.year= 2020
And user.usertype=6

Another query(2) i have try, i did not get 'Allowed memory exhausted' issue here. it is working fine but when i try to get usertype 1 and usertype 2 records. i am getting wrong value.

function test($bank_id=NULL,$month=NULL,$year=NULL,$userType=NULL){
    $query = Sales::query();
    if($bank_id){
        $query = $query->where('bankid', $bank_id);
    }
    
    if($month)
    $query = $query->where('month', $month);
    
    if($year)
    $query = $query->where('year', $year);
    
     $query = $query->select(DB::raw("SUM(amount) as total"));
    if($userType!="all"){   
        $query->whereIn('userid', function ($query1) use ($userType,$bank_id) {
            $query1->select('userid')
                ->from('user');
                if($bank_id!="all"){
                    $query1 = $query1->where('bank_id', $bank_id);
                }
                if($userType==1){
                    $query1->where('usertype', 1)->orWhere('agentType', 2);
                } else {
                    $query1->where('usertype', $userType);
                }
        });
    }
    return $query->get()->toarray()[0]['total'];
}

mysql query

$query=DB::select("SELECT SUM(sales.amount) as total 
FROM `sales`
WHERE month=8
AND year= 2020
AND bank=2
AND `userid` IN (select userid from user where bank_id=2 AND(usertype=1 OR usertype=2))");

Thank you.



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

How to decrement product quantity after checkout in Laravel (With Session)

Can you help me how to decrement after doing a checkout. So far this is the only idea I have but it shows an error called "Object of class Illuminate\Database\Eloquent\Collection could not be converted to number ". Thank you for the reply. Also I am using the one with session. enter image description here enter image description here

Note. I edit and put another image for more clearer explanation and here is the code

public function postCheckout(Request $request){
        $books = Product::all();
        if (!Session::has('cart')){
             return view('shop.shoppingcart');

        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        $order = new Order();
        $order->cart = serialize($cart);
        $order->address = $request->input('address');
        $order->name = $request->input('name');
        
        Auth::user()->orders()->save($order);
        
        $q=$cart->totalQty;
        $r=$books-$q;
      Product::table('books')
      ->where('id',$id) 
    
      ->update(array('quantity' => $r));
        Session::forget('cart');

        return redirect("home");
    }

And the error is "Object of class Illuminate\Database\Eloquent\Collection could not be converted to number"



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

Group By Date And Order By Title

Simple Question - How can i group by date and order Alphabetically ;

$data = Images::where('status','active')->groupBy('date')->orderBy('thumbnail','DESC')->paginate($settings->result_request)->onEachSide(1);

January 1st : A B C January 2nd : A B C

The code is only ordering the files alphabetically.



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

Why Laravel form not reaching the URL, redirecting back with empty message

I'm developing a website in Laravel 5.8, its login & others forms were working fine earlier but suddenly stopped working. Whenever i'm hitting the form, its not reaching to the URL and redirecting back without any message.

https://transformbadminton.com/web/login

Please help i'm trying to solve this since 3 hour but still no success.



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

Video upload and stream (video save in Laravel storage folder)

I have successfully upload video but unable to stream video from Laravel storage/app folder.

My Vue Js Code

 <video width="120" height="240" controls>
   <source :src="videoFullPath" type="video/mp4">
      Your browser does not support the video tag.
</video>

The videoFullPath state value is http://127.0.0.1:8000/storage/app/candidate_video/7/6514082.mp4.



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

How can i get unique collection to load from database in blade file

I want to load all unique subjects like in the database. and Each Subject contains multiple questions and each question contains multiple answers. I do not whether this process is correct or not but with the process, .i got only one subject with multiple questions and answers. I hope you understand my problem. There are exams_answers database where I want to view the result of all subject -> questions ->answers by the same user_id and exam_id.

This is my Database

This is my database of ExamAnswer

This is my Controller File where I want to get the result in a blade file like this: There are two subject_id 1 & 2. I want to get two subjects and each subject contain questions and each question contain the answers.

public function result($id)
{
   $results = ExamAnswer::where('exam_id', $id)->with('subject')->get();
     foreach ($results as $result){
            $subjects[] = $result->subject;
            $object = collect($subjects);
            $uniqueSubject = $object->unique();
            $uniqueSubject->values()->all();
        }
        $allSubject = $uniqueSubject->all();
    return view('frontend.mock.result',compact('results','allSubject));
}

This is my ExamAnswer Model

                    public function subject()
                        {
                          return $this->belongsTo(Subject::class, 'subject_id');
                        }

This is Subject Model

                  public function results(){
                          return $this->belongsTo('App\Result','subject_id');
                      }

This is my blade file. I want to load all unique subjects like in the database there are two ids 1 and 2. and Each Subject contains multiple questions and each question contains multiple answers.

         <div>
              @foreach($allSubject as $index => $subject) 
                 @php $result=\App\ExamAnswer::where('exam_id', $exam->id)- 
                   >where('subject_id',$subject->id)->with('question')->with('question.answers')- 
                  >get();
              @endphp
               @foreach($result as $index=> $result)
                      <span>) {!! $result->question->question_body !!}  </span>
                          @foreach($result->question->answers as $index => $answer)
                          ) {!! $answer->answer_body !!}  
                          @endforeach
               @endforeach
        </div> 


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

Sort by Last Title Word

Simple question - how do I order 'id' descending by last word.

The relevant part of my controller looks like this:

$images   = Images::where('status', 'active')
                ->where('categories_id',$category->id)
                ->orderBy('id','DESC')
                ->paginate($settings->result_request)
                ->onEachSide(1);

For Example :

  1. John AA
  2. Kane AAA
  3. Matt AC
  4. Caesey AAB
  5. Morris AB

It should be like ;

  1. John AA
  2. Morris AB
  3. Matt AC
  4. Kane AAA
  5. Caesey AAB


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

Failed to download orchid/platform from dist: Operation timed out after 10005 milliseconds with 0 out of 0 bytes received

Am trying to update my composer but I keep get the above error. I also delete my vendor file and composer.lock and try it I still getting the error I don't know what am missing there.

Thanks for your help!



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

Get difference number of two dates and subtract it from table laravel HR

So I'm trying to figure out how to make this work I have a Leave Application(which is currently just a form that stores the data) which is supposed to remove the "Days Granted" like Annual Leaves or Sick Leaves based on the dates from them for example "from 27/08/2020" and "to 30/08/2020" which is 3 days I want to get those numbers from between the dates and in the user table on the leave_days_granted field(which always has default value 20) to remove it from there so leave_days_granted - 3 = 17 something like this so I can display it on the view how many that user has left

I have added this in the user model

class User
{
    public function leaveBalance()
    {
        $daysUsed = $this->leaves->map->numberOfDays()->sum();
        return $this->leave_days_granted - $daysUsed;
    }

    // You can also add a helper to make your controller more readable.
    public function hasAvailableLeave()
    {
        return $this->leaveBalance() > 0;
    }

    public function leaves()
    {
        return $this->hasMany(\App\Leave::class);
    }

}

And this is added in the Leave Model

class Leave
{
    protected $dates = ['from', 'to'];

    public function numberOfDays()
    {
        return $this->from->diffInDays($to);
    }
}

So here I don't get why this isn't working it's not changing anything in the database when I request a leave and I'm not sure now if I'm supposed to add something more on the Leave controller to call this or the View of the Leave

This is how I get the dates on the view

<div class="card-body">
                    <form method="POST" action="">
                        @csrf

                        <div class="form-group">
                            <label>From Date</label>
                            <div class="col-md-6">
                                <input class="datepicker" type="text" class="form-control @error('from') is-invalid @enderror" name="from" required="">

                                @error('from')
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group">
                            <label>To Date</label>
                            <div class="col-md-6">
                                <input class="datepicker1" type="text" class="form-control @error('to') is-invalid @enderror" name="to" required="">

This is the form link This is the users table link This is the leaves table link



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

Does Laravel 5.2 support PHP 7.2

I have project developed in Laravel 5.2 version. But now I want to upgrade only PHP version to 7.3 So can anyone let me know that if Laravel 5.2 works with PHP latest versions.

I want laravel version to be unchanged but with latest PHP version that is PHP 7.2+



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

mercredi 26 août 2020

Laravel error when using composer to setup

I am a php beginner. I got some problem when using composer to initially extend the project. Your kindness would be highly appreciate.

Hereby is the trace infomation and composer.jason.

Stack trace: #0 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(809): ReflectionClass->__construct() #1 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(691): Illuminate\Container\Container->build() #2 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(796): Illuminate\Container\Container->resolve() #3 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(269): Illuminate\Foundation\Application->resolve() #4 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(805): Illuminate\Container\Container->Illuminate\Container{closure}() #5 C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php(691): Illuminate\Container\Container- in C:\Users\jim\git\laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 811 Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255


{ "name": "laravel/laravel", "type": "project", "description": "The Laravel Framework.", "keywords": [ "framework", "laravel" ], "license": "MIT", "require": { "php": "^7.2.5", "fideloper/proxy": "^4.2", "fruitcake/laravel-cors": "^2.0", "guzzlehttp/guzzle": "^6.3", "laravel/framework": "^7.24", "laravel/tinker": "^2.0" }, "require-dev": { "facade/ignition": "^2.0", "fzaninotto/faker": "^1.9.1", "mockery/mockery": "^1.3.1", "nunomaduro/collision": "^4.1", "phpunit/phpunit": "^8.5" }, "config": { "optimize-autoloader": true, "preferred-install": "dist", "sort-packages": true }, "extra": { "laravel": { "dont-discover": [] } }, "autoload": { "psr-4": { "App\\": "app/" }, "classmap": [ "database/seeds", "database/factories" ] }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } }, "minimum-stability": "dev", "prefer-stable": true, "scripts": { "post-autoload-dump": [ "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", "@php artisan package:discover --ansi" ], "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "@php artisan key:generate --ansi" ] } }


I try to track the exception and found error indicator in app.php



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

issue laravel version 6.0 not able to call compact function

writing this code for routing

Route::get('/welcome', 'WelcomeController@welcome');

after that i have called to a new controller

<?php
    namespace  App\Http\Controllers;
    
    class WelcomeController extends Controller{
        
        public function welcome () {
            $data = ['name'=>'Test'];
            return view('welcome', compact(data));
        }
    }

after that i am calling this $data variable in welcome.blade.php

using this method $data['name'];

server not sending any responce



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

Query fails when trying to get candidates from API with two words value separated by space

Both queries are not returning candidates with status:Returned Candidate. First query never fails but not returning candidates with status: Returned Candidate. Second query fails with error "Trying to get property of non-object". Please can you advise how this query should be built and how correctly request a status with two words value separated by space.

    $query = '&query=isDeleted:0 AND (status:Registered OR status:Returned Candidate OR status:Offer OR status:Placed OR status:Unavailable)';
    $query = '&query=isDeleted:0 AND (status:"Returned Candidate" OR status:"Offer" OR status:"Placed" OR status:"Unavailable")';



    $query = str_replace(" ", "%20", $query);
    $fields = 'id';
    $method='search/Candidate?BhRestToken='.Session::get('BH.restToken').$query.'&fields='.$fields.'&count='.$count.'&start='.$start.'&sort=-customDate1';

    $response = $bh->makeHttpRequest(Session::get('BH.restURL'), $method);


    if(isset($response->errorMessage)){

        if(BH_DEV === true) echo "<pre>".print_r($response,2)."</pre>";

        $response = array();
    }

    return $response;


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

Laravel Increase Upload file Size Heroku

It looks like I cannot upload more than 2mb file with heroku.

I can upload 3mb file on my local but I can't upload the same file after pushing to heroku. (Using storage S3)

I updated the htaccess file and I have added

ini_set('upload_max_filesize', '64M');

to my controller but it doesn't work.

Is there a way we can change the php.ini setting on heroku?



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

Laravel Socialite + Ionic / Angular ( Sign up with Facebook or Google)

My website already has login with Fb or Google function and it's working fine, now I want to connect it to my ionic app. I wrote the code, and in Ionic it's connecting to Fb API successfully but not posting a request to my server (Laravel), there's no change in the DB. Can anyone figure out what is the issue? Here's my code:

Laravel - Api Social Controller:

     public function mobileProviderLogin($provider)
    {
        try{
            $userinfo = Socialite::driver($provider)->user();
        }catch (\Exception $e){
           return response()->json(array("status" => false,  "message" => "Login failed!"));        }

        Log::debug($userinfo->getId());
        $socialProvider = SocialProvider::where('provider_id',$userinfo->getId())->first();
        if(!$socialProvider){

           
                Log::debug('CONTINUE 1.1');
                $user = User::firstOrCreate(
                    ['name'=>$userinfo->getName(), 'display_name' => $userinfo->getName()] //Create With including email
                );
                
                Log::debug('CONTINUE 1.2');
                $user->socialProvider()->create([
                    'provider_id' =>$userinfo->getId(),
                    'provider' => $provider
                ]);
           
        }
        else
        {
            Log::debug('CONTINUE 2.1');
            $user=$socialProvider->user;
            Log::debug('CONTINUE 2.2');
        }
        
        if ($user != null)
        {
            Log::debug('CONTINUE 3.1');
            auth()->login($user);
        }
   
return response()->json(array("status" => true,  "message" => "Login success!"));  } 

Ionic - service.ts:

  mobileProviderLogin(res: any) {

    return this.http.post(this.env.API_URL + 'auth/mobileProviderLogin', {res:res}
    )
  }

Ionic - Login.ts:

fbLogin() 
 {
  this.fb.login(['public_profile', 'email'])
    .then(res => {
      if (res.status === 'connected') {
        this.isLoggedIn = true;
        this.getUserDetail(res.authResponse.userID);
        this.authService.mobileProviderLogin(res);
        this.route.navigate(['/home']); 
      } else {
        this.isLoggedIn = false;
      }
    }),  (error: any) => {
      console.log(error);
         }
}


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

Is there a way to take the number between two dates and subtract with it in Laravel

So I've been trying to find a way to get/take the number in between two dates in fields "from" and "to"(leave table) then take that number(ex. it's 7) and subtract it with another number from the user table a from a field called leaveBalance it has a default number of 20 so I want that ( 20 -7) and the result to be saved in that specific user who requested the leave, in that leaveBalance field after that is changed, also would it be possible to add an if statement to check if the number between dates is bigger than the number allowed that we have on the leaveBalance to just return an error message

This is the leave table

  1. id
  2. user_id
  3. from
  4. to
  5. type
  6. description
  7. status
  8. message

The user table has the leaveBalance field and the two tables don't have a foreign key relation the user_id on the leave only stores the id of that authenticated user when a leave is created and then it only displays the leaves of that id created on the user's view

This is the Leave Controller

public function create()
     {
        $leaves = Leave::latest()->where('user_id',auth()->user()->id)->paginate(5);
        return view('leave.create',compact('leaves'));
    }
public function store(Request $request)
    {
        $this->validate($request,[
            'from'=>'required',
            'to'=>'required',
            'description'=>'required', 
            'type'=>'required'
            ]);
            $data=$request->all();
            $data['user_id']=auth()->user()->id;
            $data['message']='';
            $data['status']=0;
            $leave =Leave::create($data);
            
            $admins = Admin::all();
            $users = User::where('role_id', 2)->get();

            foreach ($admins as $admins) {
                foreach($users as $users){
                $admins->notify(new LeaveSent($leave));
                $users->notify((new LeaveSent($leave)));
            }
        }
        return redirect()->back()->with('message','Leave Created');

    }

This is the Leave Model:

{
    use Notifiable;

    protected $guarded=[];
    
    public function user(){
        return $this->belongsTo(User::class,'user_id','id');   
     }
}

This is the view of the Leave

<div class="card-body">
                    <form method="POST" action="">
                        @csrf

                        <div class="form-group">
                            <label>From Date</label>
                            <div class="col-md-6">
                                <input class="datepicker" type="text" class="form-control @error('from') is-invalid @enderror" name="from" required="">

                                @error('from')
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group">
                            <label>To Date</label>
                            <div class="col-md-6">
                                <input class="datepicker1" type="text" class="form-control @error('to') is-invalid @enderror" name="to" required="">

I'm open to using carbon in this I don't really know much on carbon but I am aware that it's used for dates and such but since I use date picker is that possible?



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

Unable to encrypt uploaded file on S3 using FileVault in Laravel 5.8?

I am using Laravel 5.8.

I am uploading a file on s3 which is successfully uploaded. But I am unable to encrypt using FileVault api.

enter image description here

Below are my configurations:

'kyc-documents' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'root' => 'app/kyc',
        ],

My controller code

$file_url = Storage::disk('kyc-documents')->putFileAs('/'.Auth::user()->id,$file,$filename);

            Log::info($file_url); // here it logs as 4/hitbtc_api_key.png


            FileVault::disk('kyc-documents')->encrypt($file_url); // Here it gives error as mentioned below

The error I am getting is as follows

fopen(app/kyc/4/hitbtc_api_key.png.enc): failed to open stream: No such file or directory {"userId":4,"exception":"[object] (ErrorException(code: 0): fopen(app/kyc/4/hitbtc_api_key.png.enc): failed to open stream: No such file or directory at /var/www/html/buy_sell/vendor/soarecostin/file-vault/src/FileEncrypter.php:170)

PS: While I am using local disk it is uploaded with .enc file extension which is correct way it should be. Only issue using s3 configurations in my fileSystem disk.

Please do help



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

SSL Certificate has expired error in Laravel API with Guzzle and can't generate new license using lets encrypt

I have an laravel project configure with docker setup. I notice that my SSL is expired, but I cannot renew my SSL so that I want to have a free SSL license using letsencrypt but I have some issues regarding on my domain name.

enter image description here

When I tried using Lets encrypt I encountered this error: enter image description here

Guide followed: linode.

I don't know why letsencrypt is not accepting my domain name?

Thanks!



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

mardi 25 août 2020

Upload Bulk Images Alphabetically

I am trying to upload bulk images alphabetically but finding it difficult. please help with same and i have tried many times didn;t got any success. Given below is the code to upload images as well as code to upload bulk images is included itself in between after //bulk upload section. Please help. Whenever i upload images it uploads like :

1.A 2.C 3.B

I like to upload the images alphabetically.

1.A 2.B 3.C

<?php

namespace App\Http\Controllers\Traits;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\AdminSettings;
use App\Models\User;
use App\Models\Stock;
use App\Models\Images;
use App\Helper;
use League\ColorExtractor\Color;
use League\ColorExtractor\ColorExtractor;
use League\ColorExtractor\Palette;
use Illuminate\Support\Facades\Validator;
use Image;

trait Upload {

  public function __construct(AdminSettings $settings, Request $request) {
   $this->settings = $settings::first();
   $this->request = $request;
 }

 protected function validator(array $data, $type)
 {
    Validator::extend('ascii_only', function($attribute, $value, $parameters){
      return !preg_match('/[^x00-x7F\-]/i', $value);
  });

  $sizeAllowed = $this->settings->file_size_allowed * 1024;

  $dimensions = explode('x',$this->settings->min_width_height_image);

  if ($this->settings->currency_position == 'right') {
    $currencyPosition =  2;
  } else {
    $currencyPosition =  null;
  }

  if ($type == 'bulk') {
    $max_lenght_title = 255;
  } else {
    $max_lenght_title = $this->settings->title_length;
  }

  $messages = array (
  'photo.required' => trans('misc.please_select_image'),
  "photo.max"   => trans('misc.max_size').' '.Helper::formatBytes( $sizeAllowed, 1 ),
  "price.required_if" => trans('misc.price_required'),
  'price.min' => trans('misc.price_minimum_sale'.$currencyPosition, ['symbol' => $this->settings->currency_symbol, 'code' => $this->settings->currency_code]),
  'price.max' => trans('misc.price_maximum_sale'.$currencyPosition, ['symbol' => $this->settings->currency_symbol, 'code' => $this->settings->currency_code]),

);

  // Create Rules
  return Validator::make($data, [
   'photo'       => 'required|mimes:jpg,gif,png,jpe,jpeg|dimensions:min_width='.$dimensions[0].',min_height='.$dimensions[1].'|max:'.$this->settings->file_size_allowed.'',
      'title'       => 'required|min:3|max:'.$max_lenght_title.'',
      'description' => 'min:2|max:'.$this->settings->description_length.'',
      'tags'        => 'required',
      'price' => 'required_if:item_for_sale,==,sale|integer|min:'.$this->settings->min_sale_amount.'|max:'.$this->settings->max_sale_amount.'',
      'file' => 'max:'.$this->settings->file_size_allowed_vector.'',
    ], $messages);
  }

// Store Image
 public function upload($type)
 {

   if ($this->settings->who_can_upload == 'admin' && Auth::user()->role != 'admin') {
     return response()->json([
         'success' => false,
         'errors' => ['error' => trans('misc.error_upload')],
     ]);
   }

   //======= EXIF DATA
   $exif_data  = @exif_read_data($this->request->file('photo'), 0, true);
   if (isset($exif_data['COMPUTED']['ApertureFNumber'])) : $ApertureFNumber = $exif_data['COMPUTED']['ApertureFNumber']; else: $ApertureFNumber = ''; endif;

   if (isset($exif_data['EXIF']['ISOSpeedRatings'][0]))
     : $ISO = 'ISO '.$exif_data['EXIF']['ISOSpeedRatings'][0];
     elseif(!isset($exif_data['EXIF']['ISOSpeedRatings'][0]) && isset($exif_data['EXIF']['ISOSpeedRatings']))
     : $ISO = 'ISO '.$exif_data['EXIF']['ISOSpeedRatings'];
   else: $ISO = '';
 endif;

   if (isset($exif_data['EXIF']['ExposureTime'])) : $ExposureTime = $exif_data['EXIF']['ExposureTime']; else: $ExposureTime = ''; endif;
   if (isset($exif_data['EXIF']['FocalLength'])) : $FocalLength = $exif_data['EXIF']['FocalLength']; else: $FocalLength = ''; endif;
   if (isset($exif_data['IFD0']['Model'])) : $camera = $exif_data['IFD0']['Model']; else: $camera = ''; endif;
   $exif = $FocalLength.' '.$ApertureFNumber.' '.$ExposureTime. ' '.$ISO;
   //dd($exif_data);

   $pathFiles      = config('path.files');
   $pathLarge      = config('path.large');
   $pathPreview    = config('path.preview');
   $pathMedium     = config('path.medium');
   $pathSmall      = config('path.small');
   $pathThumbnail  = config('path.thumbnail');
   $watermarkSource = url('public/img', $this->settings->watermark);

   $input = $this->request->all();

   if (! $this->request->price) {
     $price = 0;
   } else {
     $price = $input['price'];
   }

   // Bulk Upload
   if ($type == 'bulk') {

     $_type = true;
     $replace = ['+','-','_','.','*'];
     $input['title']  = str_replace($replace, ' ', Helper::fileNameOriginal($this->request->file('photo')->getClientOriginalName()));

     $tags = explode(' ', $input['title']);

     if ($this->request->tags == '') {
               $input['tags'] = $tags[0];
         }

     // Set price min
     if ($this->request->item_for_sale == 'sale'
          && $this->request->price == ''
          || $this->request->item_for_sale == 'sale'
          && $this->request->price < $this->settings->min_sale_amount
        ) {
               $price = $this->settings->min_sale_amount;
         $input['price'] = $this->settings->min_sale_amount;
         } else if($this->request->item_for_sale == 'sale'
      && $this->request->price == ''
      || $this->request->item_for_sale == 'sale'
      && $this->request->price > $this->settings->max_sale_amount) {
       $price = $this->settings->max_sale_amount;
       $input['price'] = $this->settings->max_sale_amount;
     }

     // Description
     if (! empty($this->request->description)) {
        $description = Helper::checkTextDb($this->request->description);
      } else {
        $description = '';
      }
                         
   }

   $input['tags'] = Helper::cleanStr($input['tags']);
   $tags = $input['tags'];

   if (strlen($tags) == 1) {
     return response()->json([
         'success' => false,
         'errors' => ['error' => trans('validation.required', ['attribute' => trans('misc.tags')])],
     ]);
   }

   $validator = $this->validator($input, $type);

   if ($validator->fails()) {
     return response()->json([
         'success' => false,
         'errors' => $validator->getMessageBag()->toArray(),
     ]);
 } //<-- Validator

    $vectorFile = '';

    // File Vector
    if ($this->request->hasFile('file')) {

      $file           = $this->request->file('file');
      $extensionVector = strtolower($file->getClientOriginalExtension());
      $fileVector      = strtolower(Auth::user()->id.time().str_random(40).'.'.$extensionVector);
      $sizeFileVector  = Helper::formatBytes($file->getSize(), 1);

    $valid_formats = ['ai', 'psd', 'eps', 'svg'];

    if (! in_array($extensionVector, $valid_formats)) {
        return response()->json([
            'success' => false,
            'errors' => ['error_file' => trans('misc.file_validation', ['values' => 'AI, EPS, PSD, SVG'])],
        ]);
    }

    if ($extensionVector == 'ai') {
      $mime = ['application/illustrator', 'application/postscript', 'application/vnd.adobe.illustrator', 'application/pdf'];

    } elseif ($extensionVector == 'eps') {
      $mime = ['application/postscript', 'image/x-eps', 'application/pdf', 'application/octet-stream'];

    } elseif ($extensionVector == 'psd') {
      $mime = ['application/photoshop', 'application/x-photoshop', 'image/photoshop', 'image/psd', 'image/vnd.adobe.photoshop', 'image/x-photoshop', 'image/x-psd'];

    } elseif ($extensionVector == 'svg') {
      $mime = ['image/svg+xml'];
    }

    if (! in_array($file->getMimeType(), $mime)) {
        return response()->json([
            'success' => false,
            'errors' => ['error_file' => trans('misc.file_validation', ['values' => 'AI, EPS, PSD, SVG'])],
        ]);
    }

    $vectorFile = 'yes';

  }

   $photo          = $this->request->file('photo');
   $fileSizeLarge  = Helper::formatBytes($photo->getSize(), 1);
   $extension      = $photo->getClientOriginalExtension();
   $originalName   = Helper::fileNameOriginal($photo->getClientOriginalName());
   $widthHeight    = getimagesize($photo);
   $large          = strtolower(Auth::user()->id.time().str_random(100).'.'.$extension );
   $medium         = strtolower(Auth::user()->id.time().str_random(100).'.'.$extension );
   $small          = strtolower(Auth::user()->id.time().str_random(100).'.'.$extension );
   $preview        = strtolower(str_slug($input['title'], '-').'-'.Auth::user()->id.time().str_random(10).'.'.$extension );
   $thumbnail      = strtolower(str_slug($input['title'], '-').'-'.Auth::user()->id.time().str_random(10).'.'.$extension );

   $watermark   = Image::make($watermarkSource);
   $x = 0;
   ini_set('memory_limit', '512M');

        $width    = $widthHeight[0];
        $height   = $widthHeight[1];

       if ($width > $height) {

         if ($width > 1280) : $_scale = 1280; else: $_scale = 900; endif;
             $previewWidth = 850 / $width;
             $mediumWidth = $_scale / $width;
             $smallWidth = 640 / $width;
             $thumbnailWidth = 280 / $width;
       } else {

         if ($width > 1280) : $_scale = 960; else: $_scale = 800; endif;
             $previewWidth = 480 / $width;
             $mediumWidth = $_scale / $width;
             $smallWidth = 480 / $width;
             $thumbnailWidth = 190 / $width;
       }

         //======== PREVIEW
         $scale    = $previewWidth;
         $widthPreview = ceil($width * $scale);

         $imgPreview  = Image::make($photo)->resize($widthPreview, null, function ($constraint) {
           $constraint->aspectRatio();
           $constraint->upsize();
         })->encode($extension);

         //======== Medium
         $scaleM  = $mediumWidth;
         $widthMedium = ceil($width * $scaleM);

         $imgMedium  = Image::make($photo)->resize($widthMedium, null, function ($constraint) {
           $constraint->aspectRatio();
           $constraint->upsize();
         })->encode($extension);

         //======== Small
         $scaleSmall  = $smallWidth;
         $widthSmall = ceil($width * $scaleSmall);

         $imgSmall  = Image::make($photo)->resize($widthSmall, null, function ($constraint) {
           $constraint->aspectRatio();
           $constraint->upsize();
         })->encode($extension);

         //======== Thumbnail
         $scaleThumbnail  = $thumbnailWidth;
         $widthThumbnail = ceil($width * $scaleThumbnail);

         $imgThumbnail  = Image::make($photo)->resize($widthThumbnail, null, function ($constraint) {
           $constraint->aspectRatio();
           $constraint->upsize();
         })->encode($extension);


   //======== Large Image
   $photo->storePubliclyAs($pathLarge, $large);

   //========  Preview Image
   Storage::put($pathPreview.$preview, $imgPreview, 'public');
   $url = Storage::url($pathPreview.$preview);

   //======== Medium Image
   Storage::put($pathMedium.$medium, $imgMedium, 'public');
   $urlMedium = Storage::url($pathMedium.$medium);

   //======== Small Image
   Storage::put($pathSmall.$small, $imgSmall, 'public');
   $urlSmall = Storage::url($pathSmall.$small);

   //======== Thumbnail Image
   Storage::put($pathThumbnail.$thumbnail, $imgThumbnail, 'public');

   //=========== Colors
   $palette   = Palette::fromFilename($urlSmall);
   $extractor = new ColorExtractor($palette);

   // it defines an extract method which return the most “representative” colors
   $colors = $extractor->extract(5);

   // $palette is an iterator on colors sorted by pixel count
   foreach ($colors as $color) {

     $_color[] = trim(Color::fromIntToHex($color), '#') ;
   }

   $colors_image = implode( ',', $_color);

   if (! empty($this->request->description)) {
        $description = Helper::checkTextDb($this->request->description);
      } else {
        $description = '';
      }

   if ($this->settings->auto_approve_images == 'on') {
     $status = 'active';
   } else {
     $status = 'pending';
   }

   $token_id = str_random(200);

   $sql = new Images;
   $sql->thumbnail            = $thumbnail;
   $sql->preview              = $preview;
   $sql->title                = trim($input['title']);
   $sql->description          = trim($description);
   $sql->categories_id        = $this->request->categories_id;
   $sql->user_id              = Auth::user()->id;
   $sql->status               = $status;
   $sql->token_id             = $token_id;
   $sql->tags                 = mb_strtolower($tags);
   $sql->extension            = strtolower($extension);
   $sql->colors               = $colors_image;
   $sql->exif                 = trim($exif);
   $sql->camera               = $camera;
   $sql->how_use_image        = $this->request->how_use_image;
   $sql->attribution_required = $this->request->attribution_required;
   $sql->original_name        = $originalName;
   $sql->price                = $price;
   $sql->item_for_sale        = $this->request->item_for_sale ? $this->request->item_for_sale : 'free';
   $sql->vector               = $vectorFile;
   $sql->save();

   // ID INSERT
   $imageID = $sql->id;

   // Save Vector DB
   if($this->request->hasFile('file')) {

       $file->storePubliclyAs($pathFiles, $fileVector);

       $stockVector             = new Stock;
       $stockVector->images_id  = $imageID;
       $stockVector->name       = $fileVector;
       $stockVector->type       = 'vector';
       $stockVector->extension  = $extensionVector;
       $stockVector->resolution = '';
       $stockVector->size       = $sizeFileVector;
       $stockVector->token      = $token_id;
       $stockVector->save();
   }

   // INSERT STOCK IMAGES
   $lResolution = list($w, $h) = $widthHeight;
   $lSize       = $fileSizeLarge;

   $mResolution = list($_w, $_h) = getimagesize($urlMedium);
   $mSize      = Helper::getFileSize($urlMedium);

   $smallResolution = list($__w, $__h) = getimagesize($urlSmall);
   $smallSize       = Helper::getFileSize($urlSmall);

 $stockImages = [
     ['name' => $large, 'type' => 'large', 'resolution' => $w.'x'.$h, 'size' => $lSize ],
     ['name' => $medium, 'type' => 'medium', 'resolution' => $_w.'x'.$_h, 'size' => $mSize ],
     ['name' => $small, 'type' => 'small', 'resolution' => $__w.'x'.$__h, 'size' => $smallSize ],
   ];

   foreach ($stockImages as $key) {
     $stock             = new Stock;
     $stock->images_id  = $imageID;
     $stock->name       = $key['name'];
     $stock->type       = $key['type'];
     $stock->extension  = $extension;
     $stock->resolution = $key['resolution'];
     $stock->size       = $key['size'];
     $stock->token      = $token_id;
     $stock->save();

   }

   if ($type == 'normal') {
     return response()->json([
                    'success' => true,
                    'target' => url('photo', $imageID),
                ]);
   } else {
     return 'success';
   }
  }
}


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