mercredi 31 juillet 2019

How can I change the default message of invalid credentials on OAuthServerException in Laravel Passport?

I am developing an API using Laravel Passport for authentication and my problem is that I cannot change the default message when the login fail due to invalid credentials.

LoginController.php

public function login(Request $request) {
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required'
    ]);

    return $this->issueToken($request, 'password');
}

IssueTokenTrait.php

public function issueToken(Request $request, $grantType, $scope = "") {
    $params = [
        'grant_type' => $grantType,
        'client_id' => $this->client->id,
        'client_secret' => $this->client->secret,
        'scope' => $scope
    ];

    if($grantType !== 'social'){
        $params['username'] = $request->username ?: $request->email;
    }

    $request->request->add($params);
    $proxy = Request::create('oauth/token', 'POST');

    return Route::dispatch($proxy);
}

When I put invalid credentials, it returns:

{
    "error": "invalid_credentials",
    "error_description": "The user credentials were incorrect.",
    "message": "The user credentials were incorrect."
}

I want to change this message because I want the message to depend on the language.



via Chebli Mohamed

Passing variables from Pre-Process to Post-Process scripts

In a DreamFactory/Bitnami instance I managed to get an Event's Pre-Process script and Post-Process script running. However, there are variables that are generated during the Pre-Process event script that need to be passed to Post-Process script for further processing.

How should I tackle this problem?

I tried to use Payload within Request object, but it is not retained between the scripts. Also after further reading I understand that Payload is not used for this purpose.



via Chebli Mohamed

When would

I am trying to figure out when and how .queued in DreamFactory is fired.

From DreamFactory article,

https://blog.dreamfactory.com/queueing-with-dreamfactory-scripting/

there are 3 events that can be fired after running GET to resource, e.g.:

api/v2/db/_table/<table_name>.get

I understand when Pre-Process event and Post-Process event are fired. But I just can't figure out when .Queued is fired.

As DF is using Laravel in the framework, may be someone can share some idea about how this works.



via Chebli Mohamed

Display total days between two dates if status is completed

I am trying to count the number of days between two dates the carbon::now and $start_date and when the status == complete the counting of days stops then get the total number of days.

if ($this->status === 'COMPLETED') {
    $now = Carbon::now();
    $start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);
    $this->start_date_to_current_date = $start_date->diffInDays($now, true);
}

But the problem is, the days still continues to count even the status is completed like for example the total days is 3 then in the next day it becomes 4. Why is that ? :/



via Chebli Mohamed

laravel blade page doesn't load completely

sometimes when i'm submitting a form or loading a page the html doesn't load completely. also the page have some animated part when loading. it happens randomly. i tried testing it by multi-clicking and normal clicking, any advice or idea might be helpful.



via Chebli Mohamed

Vuejs and Laravel app not updating app.js in production

I've got a laravel vuejs app in which the app.js file isn't being updated with the latest code changes. I thought it was the browser cache but I've tried different browsers, removing the cache, cmd+shift+r, clearing local storage, etc. I'm running a docker container on an EC2 instance. I think the server is serving an old cached version of the file but I can't figure out where or how. I'm new to Vue so there may be a setting somewhere that i don't know about. My mix-manifest points to /js/app.js?id=f731d89afd217e59e8f4

Any ideas on what to do or where to start?



via Chebli Mohamed

Syntax form create

I want to remove this syntax for my form

<div class="form-group ">
            
            
            <br>
            {!! $errors->first('name', '<span class="help-block">:message</span>') !!}
        </div>

        <div class="form-group ">

            
            
            <br>
            {!! $errors->first('firstname', '<span class="help-block">:message</span>') !!}

            
            
        </div>

And put that syntax:

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


     <fieldset class="form-group ">
       <label for="form-group-input-1">Name</label>
       <input type="text" name="name" id="name" class="form-control" required="required" value=""/>
       {!! $errors->first('name', '<span class="help-block">:message</span>') !!}
       </fieldset>

       <fieldset class="form-group ">
        <label for="form-group-input-1">Firstname</label>
        <input type="text" name="firstname" id="firstname" class="form-control" required="required" value=""/>
        {!! $errors->first('firstname', '<span class="help-block">:message</span>') !!}
       </fieldset>

Is it a version problem? I am currently with version 5.4.13.

I have to update my version is that right?



via Chebli Mohamed

How to specify a specific connection (or the database name) for Datatables in Laravel 5

I'm using Laravel 5 with Jajra/Datatables

The project use 3 databases, one is MySQL and 2 are commercial SQL databases.

The SQL databases have the tables with exactly same names.

If I want to display a table from MySql database I use in controller:

return  Datatables::of(DB::table('coeficientVR_VanzariNoi')
        ->get(['id','marca','model','capacitate','combustibil', 'caroserie', 'altaClasaSchimb', 'coeficient',
              ]))->make(true);

and it's working great!

How to specify a table from one of the the SQL databases?

I have models associated to them, and models have the connection specified.

Example for one of table which is named "version":

class version_Jato extends Model
{
    //
    protected $connection = 'sqlJato';
    protected $table = 'version';
    protected $primaryKey = 'vehicle_id';

....

So I need to specify the SQL database but I don't know how.

Thank you for your time!



via Chebli Mohamed

When polymorphic relation shouldn't be used?

Is it okay to use polymorphic relation when there are lets say 6 common columns and 2 columns with different names?

I need to track car maintenance and refueling.

maintenances - table

-date

-km_driven

-info (refers to maintenance info )

refuelings - table

-date

-km_driven

-amount (refers to amount in liters)

So, should i use polymorphic relationship or not? Is it ok if there are more different columns per model?



via Chebli Mohamed

How to use Eloquent to retrieve data from two different tables

I'm setting up a system to check if the user has sent a message to another user.

MessagesController.php

use App\Message;
use App\User;

class MessagesController extends Controller
{
    public function index()
    {
        return view('admin.messages')->with('messages', Message::all())
                                     ->with('users', User::all());

    }

The message migration has following data:

Schema::create('messages', function (Blueprint $table) {
    $table->increments('id');
            $table->integer('from');
            $table->integer('to');
            $table->mediumText('text');
            $table->integer('status');
            $table->timestamps();
});


And the web.php

Route::get('/admin/messages', [
        'uses' => 'MessagesController@index',
        'as' => 'messages'
    ]);


So the idea is to present a panel with the data of messages, showing:

<tbody>
    <tr>
        @foreach ($messages as $message)

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

        @endforeach
    </tr>
</tbody>


This loads correctly all the information on the Message table. However, it will display the 'from' and 'to' as and ID, as it should.

I expect to have the table populated with not the ID of the user, but the Name of the user, via a relationship between the Message table and the Users table.

What am I missing?



via Chebli Mohamed

LARAVEL phone begins with 05 or 06 "preg_match(): No ending delimiter '/' found"

I'm using LARAVEL 5.5, I want to test the regex to my phone number weather the number begins with 05 or 06 and number length should be 9.

per example, if the number is 068852123 or 0522321485.

there is my code below :

'telephone_1' => 'required|regex:/(05)|(06)[0-9]{8}/',

what's wrong with this code?



via Chebli Mohamed

How can I create a fake image file in laravel?

I am using laravel-medialibrary. I want to test store media. For that I write a function. The piece of that function is:

$file = UploadedFile::fake()->image($fileName);
$media = $this->owner->addMedia($file->path())
      ->usingName($fileName)
      ->usingFileName(str_uniq_file_name('png', str_slug($this->owner->name)))
      ->toMediaCollection($this->collection, $this->disk);

But this code has a several issue. The UploadedFile facade doesn't have much benefit method for me. How can I create a fake image by another way?



via Chebli Mohamed

Vuetify Treeview - Error Loading Children Asynchronously

I am using a client created with Vue Cli which fetches the data in the API made with Laravel 5.

I tried to load child items on a Treeview Vuetify, but it is not working as expected.

Vuetify Treeview

<v-treeview
    v-model="selected"
    :active.sync="active"
    :open.sync="open"
    :items="items"
    :load-children="getChilds"
    open-on-click
/>

Computed "items".

computed: {          
    items() {
        const leafs = [];
        this.items.forEach(item => leafs.push({id: item.id, item.name: name, children:[]}))
        return leafs
    },          
},

Method that returns the children.

getChilds(item) {              
    return new Promise((resolve, reject) => {
        axios.get("/callgetchilds/" + item.id)
            .then(response => {
                item.children.push(...response.data)
                resolve(response)
            })
            .catch(error => {                
                reject(error)
            });
        })
},

But I get the error below:

TypeError: Cannot set property 'vnode' of undefined
    at a.register (VTreeview.js:257)
    at a.created (VTreeviewNode.js:132)
    at nt (vue.runtime.esm.js:1854)
    at Fn (vue.runtime.esm.js:4213)
    at a.e._init (vue.runtime.esm.js:5002)
    at new a (vue.runtime.esm.js:5148)
    at rn (vue.runtime.esm.js:3283)
    at init (vue.runtime.esm.js:3114)
    at p (vue.runtime.esm.js:5972)
    at m (vue.runtime.esm.js:5919)

Someone who has been through this could help me or show me what I am doing wrong.

Thank you



via Chebli Mohamed

Routing to controllers in a different directory for each Role in Laravel

I have multiple user types in my API (admin/agent/user). These roles should do similar thing but with some different conditions. To do this I created a directory for each role and putted it's controllers inside that folder. Now I need to route them based on loggin in user type.

I found this solution but it's not changing the route:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;

class RoleRouting
{
    /**
     * @var Container
     */
    private $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }



    private static $ROLES = [
        'admin' => [
            'namespace' => 'Admin',
        ],
        'agent' => [
            'namespace' => 'Agent',
        ]
    ];

    public function handle(Request $request, Closure $next)
    {
        $action = $request->route()->getAction();
        $role = static::$ROLES[$request->user()->role()];

        $namespace = $action['namespace'] . '\\' . $role['namespace'];

        $action['uses'] = str_replace($action['namespace'], $namespace, $action['uses']);
        $action['controller'] = str_replace($action['namespace'], $namespace, $action['controller']);
        $action['namespace'] = $namespace;

        $request->route()->setAction($action);

        return next($request);
    }
}

And this is the route:

Route::middleware(['auth:api','RoleRouting'])->group(function (){
    Route::apiResources([
        'user' => 'UserController',
        'user_group' => 'UserGroupController'
    ]);
});



via Chebli Mohamed

How to deploy laravel project on a server that uses plesk pannel shared hosting

Please i need help, i am new to laravel. i have this laravel project that i worked on and now i want to deploy it to a shared hosting that uses plesk panel and this is my first time. In this hosting there is already existing PHP project inside htdocs.

i have bought domain example.com which will carry the laravel project and i have shared hosting plan already with existing core php project in its htdocs the server i am using is nakroteck.net server and they uses plesk panel. thanks in advance



via Chebli Mohamed

Laravel Migration in PHP Project

TL;DR

is there a way to use Laravel - Database migration in a PHP Project without using Laravel???

Long version

Laravel Provides Database migrations which work very well when you want to maintain the history of Database Changes and it takes out the hassle of Database migration and makes it simple to set up the database and get started with application development.

I am working on a very simple PHP application with minimal requirements which does not require a framework like Laravel or Lumen.

I got the necessary components like Request, Response, and Blade Templating but database migration is still a challenge and I am willing to use Database Migrations of Laravel.

So I was just thinking, is there a way to use Laravel - Database migration in a PHP Project without using Laravel.



via Chebli Mohamed

Laravel: Session expires while registration form is open

I have have a web app which is waiting for users on a laptop in kiosk mode. Sometimes, registration fails and users get an error screen - I think it's 419 Session Expired.

So I assume two hours after the login screen loads, the session expires (I kept the default of 120 minutes in config/session.php) and Laravel does not accept any request from that page.

How should I deal with this? I know how to make a page reload every 110 minutes or so using JS, but then I'd have to check the registration form is being filled out at this moment. This does not feel like a clean solution to me.

Is there any alternative, such as a mechanism to make Laravel less strict when a request comes from the register or login pages?



via Chebli Mohamed

How can i decrypt cake php Security encrypted value from laravel

I have some values encrypted in cake (Security). But i want to decrypt it from laravel. is it possible ?



via Chebli Mohamed

How to keep same image during update in laravel without choosing image once again?

I want to update some records. Though I didnot want update image and click on update buuton, It shows me error- "Call to a member function getClientOriginalName() on null"

Here is my controller public function update(Request $request) { $participants = new participants;

     $file = $request->file("select_file");

      if($request->hasfile("select_file"))
      {
        $file->move("public/images/",$file->getClientOriginalName());
      }

        $id                   = $request->id;
        $First_name          =  $request->First_name;
        $Last_name           =  $request->Last_name;
        $Date_of_Birth       =  $request->Date_of_Birth;
        $GST_no             =  $request->GST_no;
        $email              =  $request->email;
        $Mobile_No           =  $request->Mobile_No;
        $Company_name        =  $request->Company_name;
        $Address             =  $request->Address;
        $State              =  $request->State;
        $City               =  $request->City;
        $Pincode             =  $request->Pincode;
        $Country             =  $request->Country;
        $Amount              =  $request->Amount;
        // $Image                = $request->Image;
        $Image                = $file->getClientOriginalName();


DB::table('participants')
 ->where('id',$id )
->update(['First_name'=>$First_name,'Last_name'=>$Last_name,'Date_of_Birth'=>$Date_of_Birth,'GST_no'=>$GST_no,'email'=>$email,'Mobile_No'=>$Mobile_No,'Company_name'=>$Company_name,'Address'=>$Address,'State'=>$State,'City'=>$City,'Pincode'=>$Pincode,'Country'=>$Country,'Amount'=>$Amount,'Image'=>$Image]);


$participants->update();



session()->flash('success','Data Updated successfully!');
return redirect()->back();
//return back()->with('error','Update Data successfully!');
}

view page

Image}}"> Image}}" alt="Image not Found" style="width:100px; height:100px;" />

I want the data to be updated with previous image(since I donot want to update image).



via Chebli Mohamed

How to replace custom tags or expression with value from database in Dynamic Email Template

Hi I am getting an email template from frontend. This Email Templates looks like:

Hi ,
We have created an account for you. Here are your details:
Email:
Password:

and I am saving this email template in database. Later while any new user signs up I want to send above email template replacing the USER with username, with email of user and with password of user

I am struck at how can I find this tags or expression from above template and replace it with any dynamic values from db. Let say this values are USER:Test Email: test@test.com and Password: 123456



via Chebli Mohamed

ShellProcessFailed Error for Backup Manager - Laravel

I receive the error 'ShellProcessFailed in ShellProcessor.php line 35:' on creating database backup by using Laravel Backup Manager

Using XAMPP mysql and laravel 5 framework on Windows 10

public function store(Request $request)
{
    $this->validate($request, [
        'file_name' => 'max:30|regex:/^[\w._-]+$/'
    ]);

    try {
        $manager = app()->make(Manager::class);
        $fileName = $request->get('file_name') ?: date('Y-m-d_Hi');

        $manager->makeBackup()->run('mysql', [
                new Destination('local', 'backup/db/' . $fileName)
            ], 'gzip');

        return redirect()->route('backups.index');
    } catch (FileExistsException $e) {
        return redirect()->route('backups.index');
    }
}

Actual result(error): ShellProcessFailed in ShellProcessor.php line 35: Expected result: Successful backup process



via Chebli Mohamed

Laravel How to join table and set a 'LIKE' query on Eloquent?

ENV:

Laravel 5.7.28

Database mysql

CentOS 7.2

I have 3 table like as below, I need join this 3 table and merge columns (customer.first_name,customer.last_name,customer.address,job.name,job.address,job.date) to set 'like' query.

For example, when $text = 'MS'; set 'like' '%'.$text.'%' can return blow (merge customer.first_name and customer.last_name)

customer.first_name = TOM

customer.last_name = SMITH

customer.address = Cecilia Chapman

job.name = ABC.Ltd

job.address = Iris Watson

job.date = 2019-01-10

  1. id table (relation belongs To table customer and job)
    • id
    • customer_id
    • job_id
  2. customer table
    • id
    • first_name
    • last_name
    • address
  3. job id
    • id
    • name
    • address
    • job_date


via Chebli Mohamed

Problem with form option selected where parameters in the url

Hi I have problem with my multiple select search form.

The parameters are in the url urlhomepage.../search?cars=1&cars=2&cars=4

I do not know how to get parameters url in form option as selected

<select multiple="multiple" name="cars[]" id="select2" placeholder="">
  @foreach($names as $name)
  <option value=""></option>
  @endforeach
</select>

I want to get the effect so that the form options are marked on the basis of a url query



via Chebli Mohamed

mardi 30 juillet 2019

Laravel Nova get the value of selected item in Select field

I have a select field in my resource that looks like this:

Select::make('Category', 'category')->options([
    'local' => 'Local',
    'ftp' => 'FTP',
]),

Now I want to display an other field based on the value a user selects in the Category field.

This is my goal:

NovaJsonSchemaField::make('Properties', $this->schema($category))
            ->listClass('list-reset'),

private function schema($category): array
{
    $allSchemas = [
                    'ftp' => [
                        'type' => 'object',
                        'required' => [
                            'foo',
                            'bar',
                        ],
                        'properties' => [
                            'foo' => [
                                'type' => 'string',
                            ],
                            'bar' => [
                                'type' => 'string',
                            ],
                        ],
                    ],
                ];

    return $allSchemas[$category];
}

But I don't know how I can fill up my $category variable with the selected category.

I don't find any information on this in the Nova documentation.



via Chebli Mohamed

How to add related aggregate data in Laravel Eloquent?

One Metric model has many Measurements.

I've set up the relationship so I can do things like:

$metrics = Metric::with('measurements' => function($query) {
   return $query->where('timestamp', '>=', '20190731');
});

This works to fetch all the measurements from 31 July 2019 for the metrics.

But what I want to achieve now is to fetch aggregated measurement data, i.e.

SELECT metrics.*, stats.*
  FROM metrics
 LEFT JOIN (
            SELECT DATE_FORMAT(m.timestamp, '%Y%M') as period,
                   MIN(value) AS min, MAX(value) AS max
            FROM measurements m
            WHERE m.metric_id = metrics.id
            GROUP BY DATE_FORMAT(m.timestamp, '%Y%m')
      ) AS stats

Is there a way to achieve that in Eloquent/Laravel query builder? (Laravel 5.8)



via Chebli Mohamed

Multiple Auto-Incrementing Columns For Laravel

I am trying to create a second auto-incrementing column called order for my table called posts. I am creating this auto-incrementing column because I am using jQuery sortable, and you can change the order of posts. But unfortunately, I get this error.

1075 Incorrect table definition; there can be only one auto column and it must be defined as a key

I have tried $table->increments('order')->unique(); but that's what gave me the error. I also tried creating a foreign key constraint in which the order column would reference the 'id' column in the same table. I have also tried making the order parameter fillable in my model.

Here are my migrations.

Posts Migration

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

2nd Posts Migration

Schema::table('posts', function (Blueprint $table) {
    $table->increments('order')->unique();
});

The expected result is that when the migration is migrated, it'll create a new column called order in the posts table. This new column should be auto-incrementing. If you need more information please don't be afraid to ask.

Thanks in advance for your help.



via Chebli Mohamed

logout function not invalidating session

Basically problem is logout. But after spending whole day on it I came to know that session is working late. What i mean to say is that when I login and then try logout on first attempt it work fine. But on second attempt it is not working fine during this time request is not coming in controller but when I delete browser history it work perfect.On the other hand if difference between two attempts is 10 minutes then it work fine.

I don't know if it is server issue or laravel issue. But I tried all the things including composer commands.

I want to logout quickly on every attempt.



via Chebli Mohamed

Changes in Controller not reflecting showing previous return value

O make change in Controller but it is not effecting it is returning previous changed value not new.

I make many different kind but it is showing same first value which was returned.

I want to return new value from controller



via Chebli Mohamed

There are no commands defined in the "notifications" namespace

I'm trying to run php artisan notifications:table , but I receive the following error : There are no commands defined in the "notifications" namespace.

I'm on laravel version 5.2.36



via Chebli Mohamed

Changing default queue to other Broadcasting event

I'm trying to change default queue to another queue of broadcasting event but not work.

I'm tried following instruction from here. Add public $broadcastQueue = 'exports'; but its still running on default queue.

I'm using laravel 5.8. Here is my code.

My controller:

$paramRequest = $request->input();
dispatch(new ProcessExportExcel($paramRequest))->onQueue('exports');
return response()->json('job dispatched to default queue');

My job:

class ProcessExportExcel implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $request;

    public $tries = 3;

    public function __construct($request)
    {
        $this->request = $request;
    }

    public function handle()
    {
        $condition = $this->request;
        // export excel process...
        event(new ExportNotificationEvent($responeData));
    }
}

My event:

class ExportNotificationEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data;

    public $broadcastQueue = 'exports';

    public function broadcastQueue()
    {
        return 'exports';
    }

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function broadcastOn()
    {
        return new Channel('excel-channel.' . $this->data['userId']);
    }

    public function broadcastAs()
    {
        return 'excel-event';
    }
}



via Chebli Mohamed

how to create model controller and database table using cmd laravel can any one give list of comand?

Hello everyone can you please give me how to crate model database table controller with basic function using cmd command



via Chebli Mohamed

Laravel Job fail issue

I need queue job to re-run if it failed. I set $tries = 3 but I need to know if in job I catch exception is this will be considered as filed job and will be re-run?



via Chebli Mohamed

How to add data in queue(RabbitMQ) in Laravel?

I gonna use RabbitMQ as broker message in Laravel. Documentation says to use default queues, just configure type of broker (Database, RabbitMQ .etc).

To use queues in Laravel I should implement interface ShouldQueue:

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;

    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    public function handle(AudioProcessor $processor)
    {
        // Process uploaded podcast...
    }
}

Then to send message like:

  ProcessPodcast::dispatch($podcast);

Could I leave method public function handle() as empty?

Because I want just to add message. There is another service, that listens RabbitMQ queue.

My question is, how to add a new message in RabbitMQ under Laravel to specific exchange and queue?



via Chebli Mohamed

Can we use same route for authenticated and non-authenticated users in laravel with same controller and same view?

// route which should be used by authenticated and unauthenticated user 
Route::get('user/send-parcel', 'User\SenderController@sendParcerl');

I have tried to add this route in web (outside this auth middleware). It works fine but in my controller i have to add user id if the user is logged in if the user is not logged in the user_id field should contain the value of NULL.

$user = Auth::user();
$parcel->user_id = isset($user) ? $user->id : NULL;

The main problem is if i put the route outside of Auth middleware than it will not get the Auth in my controller. so the code works fine with unauthenticated user but for authenticated user it also put NULL in user_id field



via Chebli Mohamed

laravel Session::flush not deleting session files inside storage/framework/sessions

My laravel website session is still stored in /storage/framework/sessions. after logout.

I try to use Session::flush but its not working

how I can delete these sessions.



via Chebli Mohamed

Problems on testing middleware in Laravel with Clousure $next

I have this middleware on my app that checks the user role for a route:

public function handle($request, Closure $next, ...$roles)
{
   if (in_array($request->user()->rol, $roles)) {
        return $next($request);
   } else {
        return redirect()->action('SecurityController@noAutorizado');
   }
}

And I'm triying to make a test for this middleware (phpUnit):

    public function testUsuarioLogadoPuedeAccederAPantallaUsuarios()
{

    $user = UsuariosTestFixtures::unAsignador();
    $this->actingAs($user);
    $request = Request::create('/usuarios', 'GET');

    $middleware = new CheckRole();
    $response = $middleware->handle($request,Closure $next,$user->getRole(), function () {});
    $this->assertEquals($response, true);

}

But i'm retreiving this error: Argument 2 passed to App\Http\Middleware\CheckRole::handle() must be an instance of Closure, null given

I don't know how I have to pass the "Closure $next" on the $middleware->handle

I've tryed this:

public function testUsuarioLogadoPuedeAccederAPantallaUsuarios(Closure $next){...}

But It returns an error: Too few arguments to function UsuarioControllerTest::testUsuarioLogadoPuedeAccederAPantallaUsuarios(), 0 passed in C:\www\APPS\catsa\vendor\phpunit\phpunit\src\Framework\TestCase.php

What's the solution?

Thanks a lot!



via Chebli Mohamed

Change data values in instance variable when component loading in vue

I use Vue router for loading components in Laravel.I want to change 'show' value in instance variable when I click router-link.How can I do do this?

<router-link to="/login">Login</router-link>

Instance Variable:

const app = new Vue({
    el: '#app',
    data: function() {
        return {
            show: true
        }
    },
    router
});

Login Component :

<template>
  <div>Login component</div>
</template>



via Chebli Mohamed

Laravel website is storing too much of cache or cookies

I have Laravel website. When i make changes in laravel file it doesn't get implemented until I remove all the history including cache and cookies.

it seems like website is storing too much of cache or cookies.

But how i can find it and remove it.



via Chebli Mohamed

SQLSTATE[08006] [7] could not connect to server::Why isn’t this working?”

i'm trying to run my laravel project on postgresql,But i getting the following error to conect to the database:: SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?



via Chebli Mohamed

How to group by with union in laravel

I have two table that I want to union and after I union them I want to groupBy the one column that I used in union

Here is what I tried:

$issuance = DB::table('issuance as i')
            ->select('i.issue_to as stud_id', 'i.created_on');

$stud= DB::table('transfer as t')
            ->select('t.transfer_to as stud_id', 't.created_on')
            ->union($issuance)
            ->select('stud_id', 'created_on', DB::raw('COUNT(*) as total_asset'))
            ->groupBy('stud_id')
            ->orderBy('created_on', 'DESC')->get();

This is the MySQL query in what I tried

"(select `stud_id`, `created_on`, COUNT(*) as total_asset from `transfer` as 
`t` group by `stud_id`) union (select `i`.`issued_to` as `stud_id`, `i`.`created_on` from 
`issuance` as `i`) order by `created_on` desc"

What I really want in MySQL is like this:

select stud_id, count(*) from ((select `t`.`transfered_to` as `stud_id`, 
`t`.`created_on` from `transfer` as `t`) union (select `i`.`issued_to` as 
`stud_id`, `i`.`created_on`, COUNT(*) as asset from `issuance` as `i`)) as t 
group by stud_id order by `created_on` desc

Thank you for the help



via Chebli Mohamed

Eloquent Relationship without Pivot Model

I have 3 tables:

  1. customer: fields: id, name
  2. item: fields: id, name
  3. customer_items: fields: customer_id, item_id, qty

Customer and Item have their separate Models as we would expect.

Question: How would I relate these two(Customer and Item) without having a pivot model.

I want to directly get customer items using $customer->items instead of doing $customer->customerItem->items which I find unnecessary since I don't want to track customerItems & customer by item.

Also, I cannot directly use customer_items table for Item model as I might need to retrieve all items in its controller.



via Chebli Mohamed

Shows previous user as login when switch account

I have laravel app. On this app only one kind of user but when user try to switch account it shows previous user's information like name,picture until user refresh the page.

I tried to see logout and login functions but they are perfect.

User should see his own dashboard after login.



via Chebli Mohamed

lundi 29 juillet 2019

Website doesn't work after changing folder name in public_html cpanel

I have a website running. I put all the files of my laravel5.2 project in public_html of the cpanel, say A. Everything is working fine with url:
www.mydomain.com/A

I need to update something, so I had another folder inside public_html say B, and B is for testing purpose, and I access it through www.mydomain.com/B

I completed my testing, everything is working fine on testing. Testing has separate database.

Now I want to make it real live website so, I changed the name of my testing B to A.
This is what changes I made. 1. updated .env files copied all the content from A to B because I want to use live one's database.
One thing I doubt about APP KEY, tell me If I need to generate new one.

After doing all this, I have a strange problem now.

When I change my testing B to live A, it doesnt' work properly. I am able to login, but see nothing, means I don't see actual data coming from database just templates text, on admin panel.
But If I change folder B to anything else everything works well.

Please help me, what am I missing?



via Chebli Mohamed

Display data as cross tab in laravel

I have this join

$degreesPdfs = DB::select("SELECT student_tbs.student_id,student_tbs.regno,student_tbs.stdName,student_tbs.stdfName,student_tbs.department_id,student_tbs.degree_id,roll_no_tbs.rollno,roll_no_com_dets.subcode,subject_tbs.Na,subject_tbs.semester_id,college_tbs.name FROM student_tbs INNER JOIN roll_no_tbs ON roll_no_tbs.regno = student_tbs.regno INNER JOIN roll_no_com_dets ON roll_no_com_dets.rollno = roll_no_tbs.rollno INNER JOIN college_tbs ON college_tbs.college_id = student_tbs.department_id LEFT JOIN subject_tbs ON subject_tbs.code =roll_no_com_dets.subcode WHERE student_tbs.department_id = $degAdmin_department AND student_tbs.degree_id = $degree");

I want to display data like this Please click on the in order to view the image.I have search alot but could not find any proper solution

https://drive.google.com/open?id=1dSOCRd8TLOdx-E8z3qNpaTNBuEvciOH5

I will be very thankful to you



via Chebli Mohamed

How to let Laravel pivot table use only created_at?

When dealing with belongsToMany relation, you use a pivot table to record the relation.

For many pivot tables, the relations are just created and then deleted. They won't have their own property, so you never update them.

I know I can do this to auto-set both updated_at and created_at.

class Foo extends Model
{
    public function bars() {
        $this->belongsToMany(Bar::class)->withTimestamps();
    }
}

But how to use only created_at? I have no idea.



via Chebli Mohamed

Tôi có một hàm post gửi gmail cho khách hàng, nhưng lại gửi cho chính tôi

Tôi có một hàm gửi gmail đến khách hàng, nhưng lại gửi cho chính tôi

nhưng lại gửi cho chính tôi

public function postSubmit(Request $request) { $order = new Order; $order->name = $request->name; $order->email = $request->email; $order->phone = $request->phone; $order->address = $request->address; $order->content = $request->content; $order->amount = $request->amount; $order->save(); $data = [ 'name' => $request->name, 'email' => $request->email, 'phone' => $request->phone, 'address' => $request->address, 'content' => $request->content, 'amount' => $request->amount, ]; Mail::send('admin.order.send', $data, function ($email) { $email->from('my_email@gmail.com', 'admin'); $email->to()->subject('Submit'); }); return redirect()->back()->with('message', 'thank'); }



via Chebli Mohamed

Laravel 5 array: Cannot use object of type stdClass as array

I'm trying to take items from my database and put them into the format required by the "laravel-paypal" package:

$data['items'] = [
    [
        'name' => 'Product 1',
        'price' => 9.99,
        'desc'  => 'Description for product 1'
        'qty' => 1
    ],
    [
        'name' => 'Product 2',
        'price' => 4.99,
        'desc'  => 'Description for product 2',
        'qty' => 2
    ]
];

So I have a sweet query:

$order_items = DB::table('order_items')
                        ->where('order_id', $order['id'])
                        ->join('products', 'order_items.product_id', '=', 'products.id')
                        ->selectRaw('products.name, order_items.price + order_items.tax as price, order_items.quantity as qty')
                        ->get()
                        ->toArray();

Which yields:

array:2 [▼
  0 => {#296 ▼
    +"name": "fugit"
    +"price": 727.82
    +"qty": 1
  }
  1 => {#298 ▼
    +"name": "MEMBERSHIP"
    +"price": 35.0
    +"qty": 1
  }
]

But when I try to put it into the required array:

$data = [];
$data['items'] = $order_items;

I get the error message:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Cannot use object of type stdClass as array

With details of:

 protected function setCartItems($items)
    {
        return (new Collection($items))->map(function ($item, $num) {
            return [
                'L_PAYMENTREQUEST_0_NAME'.$num  => $item['name'],
                'L_PAYMENTREQUEST_0_AMT'.$num   => $item['price'],
                'L_PAYMENTREQUEST_0_DESC'.$num  => isset($item['desc']) ? $item['desc'] : null,
                'L_PAYMENTREQUEST_0_QTY'.$num   => isset($item['qty']) ? $item['qty'] : 1,
            ];
        })->flatMap(function ($value) {
            return $value;
        });

I've read all the solutions for this error message, and they all say that what I have is an array of objects, not an array of arrays, which is why I'm getting this message. I get it. They all say that I have to access the data with $order_items->price. I get it.

But I need the data in that array of arrays format and since it's a nested array, I can't even figure out how I would do it with a foreach loop.

Any help would be appreciated.



via Chebli Mohamed

Elegant way to pass objects to Laravel's create method

Is there a more elegant way to do the following in Lavarel 5?

MyModel::create([
    'my_other_model_id' => $my_other_model->id,
    'my_other_other_model_id' => $my_other_other_model->id,
]);

I'd like to pass $my_other_model and $my_other_other_model in directly without all that tedious mucking about with ids.



via Chebli Mohamed

Count days and stop count if status is completed

I am trying to count the number of days between two dates and when the status == complete the count of days stops.

if ($this->status == 'COMPLETED') {
    $now = Carbon::now();
    $start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);
    $this->start_date_to_current_date = $start_date->diffInDays($now, true);
}

But the problem is, the days still continues to count and increment. how can I can make the counting stop ?



via Chebli Mohamed

How do I do a callback function in Laravel after a transaction processes

What I'm trying to do here is to implement a callback function in a Laravel 5.4 controller. This uses Authorize.net to process a credit card transaction, then inserts a bunch of stuff into the database, sends some messages, makes an invoice and airbill, and so on.

What I WANT to happen is: 1) Hit the "Submit" button, sends AJAX request 2) Processes the Authorize.net transaction 3) If good, then call a callback function to do all the gruntwork but return a transaction response. 4) Notify the user

The reason I wanna do it this way is that I want the user to wait the minimum amount of time to see the result of their payment processing without having to wait another 5 seconds or so staring at a spinning wheel waiting to go to the order complete page.

Can a callback function help me do this?

Thanks

My current implementation results in a 500 error, and I'm not quite sure what I should do from here...

[ route in web.config ]

// AJAX call to process the transaction, insert the new order, inform the user of success/failure
Route::post('/shop/processtransaction', 'OrderCheckoutController@processTransaction');

[ function processTransaction in OrderCheckoutController.php ]

    public function processTransaction(Request $request) {
        return self::processPaymentAndOrderInsertion($request, 'createOrder');
    }

[ function processPaymentAndOrderInsertion in OrderCheckoutController.php ]

    public function processPaymentAndOrderInsertion(Request $request, callable $createOrderCallback = null) {
        $order_proc = new OrderProcessingTools;
        $transaction_response = $order_proc->processTransaction($request);

        if($transaction_response['success'] === true) {
            self::$createOrderCallback($request, $transaction_response);
        }
        return json_encode($transaction_response);
    }

[ my callback function ]


    public function createOrder(Request $request, $transaction_response) {
        $order_proc = new OrderProcessingTools;
        $new_order = $order_proc->insertNewOrder($request);
        $new_order->payment_status_id = $transaction_response['response_data']['order_payment_status_id'];
        $new_order->save();

        // record the payment transaction
        $order_proc->insertOrderPaymentData($new_order, $transaction_response);

        // insert the travelers for this order
        $travelers = $order_proc->insertOrderTravelers($new_order);

        // insert order inbound shipment record
        $order_proc->insertInboundOrderShipping($new_order->id);

        // generate inbound shipping airbill
        $order_proc->generateInboundShippingAirbill($new_order->id);

        /// generate the invoive
        $order_proc->generateInvoice($new_order);

        // send new order notification to the user
        $order_proc->sendNewOrderNotificationToUser($new_order);

        // send new order notification to admin
        $order_proc->sendNewOrderNotificationToAdmin($new_order);

        // finally kill the session variable
        $_SESSION['travelers'] = [];        
    }

[ my previous non-asynchronous implementation looks like this...]


    public function processTransaction(Request $request) {
        // :: POST 
        // Process the Authorize.net transaction, insert the order, generate invoices 
        // and airbills, send notifications

        $order_proc = new OrderProcessingTools;
        $transaction_response = $order_proc->processTransaction($request);

        if($transaction_response['success'] === true) {
            // insert a new order
            $new_order = $order_proc->insertNewOrder($request);
            $new_order->payment_status_id = $transaction_response['response_data']['order_payment_status_id'];
            $new_order->save();

            // record the payment transaction
            $order_proc->insertOrderPaymentData($new_order, $transaction_response);

            // insert the travelers for this order
            $travelers = $order_proc->insertOrderTravelers($new_order);

            // insert order inbound shipment record
            $order_proc->insertInboundOrderShipping($new_order->id);

            // generate inbound shipping airbill
            $order_proc->generateInboundShippingAirbill($new_order->id);

            /// generate the invoive
            $order_proc->generateInvoice($new_order);

            // send new order notification to the user
            $order_proc->sendNewOrderNotificationToUser($new_order);

            // send new order notification to admin
            $order_proc->sendNewOrderNotificationToAdmin($new_order);

            // finally kill the session variable
            $_SESSION['travelers'] = [];
        }

        // either good news or bad news at this point.. 
        return json_encode($transaction_response);
    }

When I try it this way, this is the error that is returned...

xception: "Symfony\Component\Debug\Exception\FatalThrowableError" file: "F:\wamp64\www\uspassports\public_html\app\Http\Controllers\OrderCheckoutController.php" line: 105 message: "Argument 2 passed to App\Http\Controllers\OrderCheckoutController::processPaymentAndOrderInsertion() must be callable or null, string given



via Chebli Mohamed

Having issues with groupBy with a join

I am doing these query to get all records with specific gender from different tables:

$q = DB::table('bondings')
            ->join('businesses', 'bondings.business_id', '=', 'businesses.id')
            ->select('bondings.*', 'businesses.solicitante_sexo')
            ->whereIn('businesses.solicitante_sexo', ['Masculino','Femenino','Otro'])
            ->groupBy('bondings.business_id');

The query works with out the groupBy, but give all records repeting business_id, and i need to goup them so i will have only one record by business_id

I am getting this error from laravel 5.7:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'ovimipymes.bondings.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select `bondings`.*, `businesses`.`solicitante_sexo` from `bondings` inner join `businesses` on `bondings`.`business_id` = `businesses`.`id` where `businesses`.`solicitante_sexo` in (Masculino, Femenino, Otro) group by `bondings`.`business_id`)



via Chebli Mohamed

Block the access to a page students.index()

In my navbar I have 2 pages which are Student Add and Student Index.

enter image description here

When I click on Student Add, I have an error message Access Denied. Great, no problem...

enter image description here

Now, I would like to make the even thing with the page Students Index and display the items, I have a problem.

I have access to the content...

enter image description here

In my Controller Student I have this:

class StudentController extends Controller
{   

    public function __construct()
    {
        $this->middleware(['auth', 'clearance'])
            ->except('index', 'show');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $students = Student::orderby('id', 'desc')->paginate(5);
        return view('students.index', compact('students'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('students.create');
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
            'firstname' =>'required',
            ]);

        $name = $request['name'];
        $firstname = $request['firstname'];

        $student = Student::create($request->only('name', 'firstname'));

        return redirect()->route('students.index')
            ->with('flash_message', 'Article,
             '. $student->name.' created');
    }

Then, in my Class ClearanceMiddleware I have this:

public function handle($request, Closure $next) {        
        if (Auth::user()->hasPermissionTo('Administer roles & permissions')) {
            return $next($request);
        }

        if ($request->is('students/create')) {
            if (!Auth::user()->hasPermissionTo('Create Student')) {
                abort('401');
            } else {
                return $next($request);
            }
        }

        if ($request->is('students/index')) {
            if (!Auth::user()->hasPermissionTo('Index Student')) {
                abort('401');
            } else {
                return $next($request);
            }
        }

I don't see the missed step. I have to block the access please.



via Chebli Mohamed

Undefined property: stdClass::$user AND Call to a member function diffForHumans() on string

When i run my webpage it's can run normally but i can't search. I need to search for data by those data from different table and when i search data it show error

Undefined property: stdClass::$user (View: C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)

and created_at->diffForHumans() too it show error:

Call to a member function diffForHumans() on string (View: C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)

$group is in table groups no problem.

$group->user->name is about table users has problem:

Undefined property: stdClass::$user

and $group->created_at->diffForHumans() has problem:

Call to a member function diffForHumans() on string

view group\index.blade.php

<div class="container">
  <div class="row">

    <div class="col-md-12">
      <form action="/search" method="get">
        <div>
          <button type="submit" class="btn btn-primary" style="float:right;">Search</button>
          <a style="float:right;">
            <input type="search" name="search" class="form-control" >
          </a>
        </div>
      </form>
    </div>
    <br><br>
    <div class="col-md-12">
      <div class="panel panel-default">
        <div class="panel-heading" style="font-size: 18px;">Home</div>
        <div class="panel-body">
          <table class="table table-striped table-linkable table-hover">

            <thead>
              <tr>
                <th class="text-center">Group</th>
                <th class="text-center">Posted By</th>
                <th class="text-center">Posted At</th>

              </tr>
            </thead>

            <tbody>
              @foreach($groups as $group)
                <tr onclick="document.location.href = ''">
                  <td></td>
                  <td class="text-center"></td>                     <!--error for search-->
                  <td class="text-center"></td>    <!--error for search-->
                </tr>
              @endforeach
            </tbody>

          </table>
          <div class="text-center"> {!! $groups->links(); !!} </div>
        </div>
      </div>
    </div>

  </div>
</div>


Controller GroupController.php

class GroupController extends Controller
{
   public function search(Request $request)
   {
     $search = $request->get('search');
     $groups = DB::table('groups')->where('title', 'like', '%'.$search.'%')->paginate(5);
     //$users = DB::table('users')->where('name', 'like', '%'.$search.'%')->paginate(5);

     return view('group.index', ['groups' => $groups] );
   }
}


Route

Route::get('/search','GroupController@search');

How should I fix it ??



via Chebli Mohamed

Uploading images to digital ocean spaces in Laravel

I'm trying to upload multiple images to digital ocean but I'm getting this error Error executing "PutObject" on "https://images.images.fra1.digitaloceanspaces.com/EunqNIu6mFjPTzJK4yksT5elaFqNQyfRMo9xzjG3.jpeg/EunqNIu6mFjPTzJK4yksT5elaFqNQyfR . How can I upload multiple images to digital ocean spaces?

I have set up everything in digital ocean.

   foreach ($request->photos as $photo) {
        $filename = $photo->hashName();
          Storage::disk('spaces')->putFile( $filename, $photo);

        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
     }



via Chebli Mohamed

Laravel 5 get URI causing NotFoundHttpException

If I am catching a NotFoundHttpException in the Exceptions/Handler.php file in Laravel 5, how can I log the URI causing the exception?

I have seen all kinds of answers about setting up the routes file correctly (did that) but I can't seem to see how I can log the offending URI.

Any ideas?



via Chebli Mohamed

database data retrieving with line break database mysql

i add the data with html special tags like
but when i retrieve data from database this show ( Welcome to this
Website ). it does not break the line .

<h1></h1>

how can i do this help me



via Chebli Mohamed

how to inserting and update image Summernote in laravel 5

I use summernote as a wysiwyg on my web, but I get a problem that I can't find in google(not solve my problem), which is how to input images in my text-area using summernote and display them in view I have used various methods as below but still produce errors, i hope i can get the answer in this amazing stackoverflow.

i tried this code first :

$detail=$request->input('konten');
      $dom = new \DomDocument();
      libxml_use_internal_errors(true);
      $dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
      $images = $dom->getElementsByTagName('img');
      foreach($images as $k => $img){

          $data = $img->getAttribute('src');
          list($type, $data) = explode(';', $data);
          list(, $data)      = explode(',', $data);
          $data = base64_decode($data);
          $image_name= "/img/blog" . time().$k. '.png';
          $path = public_path() . $image_name;
          file_put_contents($path, $data);
          $img->removeAttribute('src');
          $img->setAttribute('src', $image_name);
      }
      $detail = $dom->saveHTML();

and i save it to database, this work no error overall but the problem is, in my laravel directory the "laravel-5" environment not a default, i make folder name "main" for the "laravel" and that folder "main" become one directory in public, the problem is, $path = "public_path() . $image_name" not upload to the right directory on public name "img/blog" but make new directory on MAIN folder, so when i show on view that image not show up because wrong directory the result on img src is img/blog/namefile.png, that must be https://somedomain.com/img/blog/namefile.png to show the image.

and i tried some library name "Intervention\Image\ImageManagerStatic" and this the code :

$detail=$request->input('konten');
      $dom = new \DomDocument();
      $dom->loadHtml( mb_convert_encoding($detail, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
      $images = $dom->getElementsByTagName('img');
        foreach($images as $img){
            $src = $img->getAttribute('src');
            if(preg_match('/data:image/', $src)){
                // get the mimetype
                preg_match('/data:image\/(?<mime>.*?)\;/', $src, $groups);
                $mimetype = $groups['mime'];

                $filename = uniqid();
                $filepath = "/img/blog/$filename.$mimetype"; 

                $image = Image::make($src)
                  ->encode($mimetype, 50)  
                  ->save($filepath);

                $new_src = asset($filepath);
                $img->removeAttribute('src');
                $img->setAttribute('src', $new_src);
            }
        }
      $detail = $dom->saveHTML();

but the result is the image can't be write to the directory, i don't know why, i tried the first one delete the public_path() and change to the URL, and have same error.

//first trial

$detail=$request->input('konten');
      $dom = new \DomDocument();
      libxml_use_internal_errors(true);
      $dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
      $images = $dom->getElementsByTagName('img');
      foreach($images as $k => $img){

          $data = $img->getAttribute('src');
          list($type, $data) = explode(';', $data);
          list(, $data)      = explode(',', $data);
          $data = base64_decode($data);
          $image_name= "/img/blog" . time().$k. '.png';
          $path = public_path() . $image_name;
          file_put_contents($path, $data);
          $img->removeAttribute('src');
          $img->setAttribute('src', $image_name);
      }
      $detail = $dom->saveHTML();

//second trial

$detail=$request->input('konten');
      $dom = new \DomDocument();
      $dom->loadHtml( mb_convert_encoding($detail, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
      $images = $dom->getElementsByTagName('img');
        foreach($images as $img){
            $src = $img->getAttribute('src');
            if(preg_match('/data:image/', $src)){
                // get the mimetype
                preg_match('/data:image\/(?<mime>.*?)\;/', $src, $groups);
                $mimetype = $groups['mime'];

                $filename = uniqid();
                $filepath = "/img/blog/$filename.$mimetype"; 

                $image = Image::make($src)
                  ->encode($mimetype, 50)  
                  ->save($filepath);

                $new_src = asset($filepath);
                $img->removeAttribute('src');
                $img->setAttribute('src', $new_src);
            }
        }
      $detail = $dom->saveHTML();

i expect the image uploaded to the right directory and can be show on the view



via Chebli Mohamed

Laravel form validation issue

enter image description hereLaravel Form Check Validation, I tried to check form validation numerous time but showing this same problem in localhost.

Ist of all, I created a check validation function that inside have one parameter and array function in StudentController. Later, I created a post form for checking the required validation.

public function store(Request $request) {

//Insert data into Student Table
$student = new Student;
$student->name = $request->name;
$student->registration_id = $request->registration_id;
$student->department_name = $request->department_name;
$student->info = $request->info;
$student->save();

return redirect()->route('index');

}



via Chebli Mohamed

how to use Laravel package in my own package?

I'm developing a Role-Permission package in Laravel and i want to use this package;

https://github.com/spatie/laravel-permission

Problem is I can not use some functions in the main project when I install this package in my own package. eg "HasRoles"

My packages composer.json file

 "require": {
        "spatie/laravel-permission": "dev-master"
    },
    "autoload": {
        "psr-4": {
            "Modul\\Permission\\": "src"
        }
    },
    "extra": {
        "laravel": {
            "providers": [
                "Spatie\\Permission\\PermissionServiceProvider"
            ]
        }
    }

when i serve its show this error message

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN) Trait 'Spatie\Permission\Traits\HasRoles' not found

What am I doing wrong here?



via Chebli Mohamed

ReflectionClass error. in Upgrading laravel 5.1 to 5.8

I am following https://medium.com/@info.subashthapa/upgrading-laravel-5-0-to-5-8-1bfec5c8a0e2

to upgrade laravel 5.1 to laravel 5.8 now I have stuck in that error

PHP Fatal error:  Uncaught ReflectionException: Class App\Console\Kernel does not exist in D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php:741
Stack trace:
#0 D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php(741): ReflectionClass->__construct('App\\Console\\Ker...')
#1 D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php(631): Illuminate\Container\Container->build('App\\Console\\Ker...', Array)
#2 D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(674): Illuminate\Container\Container->make('App\\Console\\Ker...', Array)
#3 D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php(220): Illuminate\Foundation\Application->make('App\\Console\\Ker...', Array)
#4 D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php(738): Illuminate\Container\Container->Illuminate\Container\{closure}(Object(Illuminat in D:\xampp\htdocs\cloud\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 741

I have found out ReflectionClass; in fresh laravel 5.8 but I didn't get.

I download composer.json from server I surprised its file got invalid json. I don't know how it happens.

I tried copy composer.json to replace old composer.json still I got error ReflectionClass error.

Please Suggest me.



via Chebli Mohamed

Having problem with retriving json data in laravel

I'm working on a laravel project and i'm getting JSON error. I've try few options to solve the issue but did not come up with any solutions.

In this project I've to send multiple data into database onder one "ID". In that ID there are at list 10 data need to insert. So I used JSON format. It saves ok but getting error when I try to pull data.

Here is my code

Controller :

public function newExpenses(Request $request){

        $Jexpenses = new Jexpenses;

        $json = array(
            'des' => $request->description,
            'valu' => $request->expenses
        );

        $Jexpenses->voucher = $request->voucher_no;
        $Jexpenses->date = $request->date;
        $Jexpenses->description = json_encode($json);
        $Jexpenses->expenses = $request->total;
        $Jexpenses->remarks = $request->remark;

        if($Jexpenses->save()){
            $notification = array(
                'message' => 'Expenses Saved',
                'alert-type' => 'success'
            );
        }

        return redirect()->back()->with($notification);
    }

result :

{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}

Return Controller:

public function expenses(){
        $data = array(
            'title' => 'Expenses',
            'expenses' => Jexpenses::all()
        );

        return view('expenses.expenses')->with($data);
    }

html :

@foreach ($expenses as $key => $getData)


    


    <tr>
        <td> </td>
        <td> </td>
        <td> </td>
        @foreach ($array->description as $k => $v)
           <td></td>
            <td></td>
         @endforeach
        <td></td>
        <td></td>
    </tr>
 @endforeach

it should be work fine but getting error

error:

syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php

Need some help. Thanks.



via Chebli Mohamed

How to check if IPv6 is in between Two range of 2 (min and max) IPv6 addresses

I have this function that works of IPv4 addresses:

 # We need to be able to check if an ip_address in a particular range
protected function ipInRange($lower_range_ip_address, $upper_range_ip_address, $needle_ip_address)
{
    # Get the numeric reprisentation of the IP Address with IP2long
    $min    = ip2long($lower_range_ip_address);
    $max    = ip2long($upper_range_ip_address);
    $needle = ip2long($needle_ip_address);

    # Then it's as simple as checking whether the needle falls between the lower and upper ranges
    return (($needle >= $min) AND ($needle <= $max));
}   

How can I convert into work also with IPv6 addresses? Thanks



via Chebli Mohamed

How to GroupBy in Relationship?

I have post table

| ID | TITLE | SLUG | CONTENT | COMMENTS_COUNT | 

and i have post_reactions table

| ID | USER_ID | TYPE | POST_ID | 

I want to make a relationship that what reactions that post have



via Chebli Mohamed

laravel select certian column of table with query on relation table

user can send a parameter for search , it can be city name or hotel's name. i want to search that in hotel table and city table then and i want to send back only hotel name and city name in any result in response. with my query it only return name of hotel but city's data is null, why? hot can i handle this?

hotel and city have relation

in Hotel Model i have:

  public function city()
    {
        return $this->belongsTo(City::class);
    }

in city model:

  public function hotel()
    {
        return $this->hasMany(Hotel::class);
    }

my query in related controller:

$hotels = Hotel::with('city')->select('name')->where('name', 'like', '%' . $request->target . '%')
                ->orWhereHas('city', function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->target . '%');
                })
                ->orderBy('id')
                ->take(10)->get();
return response()->json(['result' => $hotels]);

and response is :

{"result":[{"name":"venus","city":null}]}



via Chebli Mohamed

Trying to get property 'parameter' of non-object

Hello i have an api in Laravel i'm trying to get a value from a table column Json response it already in the table json response but when i get it its says Trying to get property 'parameter' of non-object

i'm so new on laravel so i'm really lost with this

The Function i use when i call the api it go to

    $parameter = $value->parameter;

And then stop and say in PriceDetailHolder Trying to get property 'parameter' of non-object

I showed 2 functions because i don't really know where is the problem exactly

public static function PriceDetailHolder($booking_prices, $booking_id = null, $currency = null): array
    {
        if (!empty($booking_id) && $booking_id !== null) {
            /**
             * @var $booking Booking
             */
            $booking = Booking::query()->find($booking_id);
            $currency = $booking->CountryArea->Country->isoCode;
        }
        $holder[] = [
            'highlighted_text' => trans('admin.message665'),
            'highlighted_text_color' => '333333',
            'highlighted_style' => 'BOLD',
            'highlighted_visibility' => true,
            'small_text' => 'eee',
            'small_text_color' => '333333',
            'small_text_style' => '',
            'small_text_visibility' => false,
            'value_text' => trans('admin.message665'),
            'value_text_color' => '333333',
            'value_text_style' => '',
            'value_textvisibility' => false
        ];
        foreach ($booking_prices as $key => $value) {
            $code = '';
            if (!empty($value->code)) {
                $code = "({$value->code})";
            }
            $parameter = $value->parameter;
            /**
             * @var $parameterDetails PricingParameter
             */
            $parameterDetails = PricingParameter::query()->find($parameter);
            if ($parameterDetails === null) {
                $prameterName = $parameter;
            } else {
                if ((int)$parameterDetails->parameterType === 13) {
                    $applicable = (int)$parameterDetails->applicable === 1 ? trans('api.message174') : trans('api.message175');
                    /**
                     * @var $priceCardValue PriceCardValue
                     */
                    $priceCardValue = PriceCardValue::query()->where([['price_card_id', '=', $value->price_card_id], ['pricing_parameter_id', '=', $parameter]])->first();
                    $code = "($priceCardValue->parameter_price %)\n" . $applicable;
                }
                $prameterName = $parameterDetails->ParameterApplication . $code;
            }
            $holder[] = [
                'highlighted_text' => $prameterName,
                'highlighted_text_color' => '333333',
                'highlighted_style' => 'NORMAL',
                'highlighted_visibility' => true,
                'small_text' => 'eee',
                'small_texot_clor' => '333333',
                'small_text_style' => '',
                'small_text_visibility' => false,
                'value_text' => $currency . ' ' . $value->amount,
                'value_text_color' => '333333',
                'value_text_style' => '',
                'value_textvisibility' => true
            ];

        }
        return $holder;
    }





public function End(EndTripRequest $request)
    {
        $merchant_id = $request->user('api-driver')->merchant_id;
        $validator = Validator::make($request->all(), [
            'booking_id' => [
                'required',
                'integer',
                Rule::exists('bookings', 'id')->where(static function ($query) {
                    $query->where('booking_status', TripStatus::STARTED);
                }),
            ],
            'latitude' => 'required',
            'longitude' => 'required',
            'tip_amount' => 'nullable|numeric',
        ]);
        if ($validator->fails()) {
            $errors = $validator->messages()->all();
            return response()->json(['result' => '0', 'message' => $errors[0], 'data' => []]);
        }
        /**
         * @var $configuration BookingConfiguration
         */
        $configuration = BookingConfiguration::query()->where('merchant_id', $merchant_id)->first();
        $booking_id = $request->booking_id;
        /**
         * @var $booking Booking
         */
        $booking = Booking::with('PriceCard')->find($booking_id);
        /**
         * @var $bookingDetails BookingDetail
         */
        $bookingDetails = BookingDetail::booking($booking_id)->first();
        $service_type_id = (int)$booking->service_type_id;
        if (!in_array($service_type_id, [1, 5], false)) {
            $start_meter_value = $bookingDetails->start_meter_value;
            $customMessages = [
                'gt' => trans_choice('api.endmeter', 3, ['value' => $start_meter_value]),
            ];
            $validator = Validator::make($request->all(), [
                'send_meter_image' => 'required',
                'send_meter_value' => 'required|integer|gt:' . $start_meter_value,
            ], $customMessages);
            if ($validator->fails()) {
                $errors = $validator->messages()->all();
                return response()->json(['result' => '0', 'message' => $errors[0], 'data' => []]);
            }
        }
        $request->user('api-driver')->free_busy = 2;
        $request->user('api-driver')->total_trips += 1;
        $request->user('api-driver')->save();
        /**
         * @var $user \App\User
         */
        $user = $booking->User;
        ++$user->total_trips;
        $user->save();
        if ($request->hasFile('send_meter_image')) {
            $bookingDetails->end_meter_value = $request->send_meter_value;
            $request->file('send_meter_image');
            $send_meter_image = $request->send_meter_image->store('service');
            $bookingDetails->end_meter_image = $send_meter_image;
        }
        $pricing_type = $booking->PriceCard->pricing_type;
        $price_card_id = $booking->price_card_id;
        $key = $configuration->google_key;
        $endAddress = GoogleController::GoogleLocation($request->latitude, $request->longitude, $key);
        $endAddress = $endAddress ?: 'Address Not found';
        $endTimeStamp = time();
        $bookingDetails->end_timestamp = $endTimeStamp;
        $bookingDetails->end_latitude = $request->latitude;
        $bookingDetails->end_longitude = $request->longitude;
        $bookingDetails->end_location = $endAddress;
        $bookingDetails->accuracy_at_end = $request->accuracy;
        $bookingDetails->save();
        $start_timestamp = $bookingDetails->start_timestamp;
        $seconds = $endTimeStamp - $start_timestamp;
        $hours = floor($seconds / 3600);
        $mins = floor($seconds / 60 % 60);
        //$secs = floor($seconds % 60);
        $timeFormat = sprintf('%02d H %02d M', $hours, $mins);
        $rideTime = round(abs($endTimeStamp - $start_timestamp) / 60, 2);
        $from = $bookingDetails->start_latitude . ',' . $bookingDetails->start_longitude;
        $to = $request->latitude . ',' . $request->longitude;
        $coordinates = '';
        $bookingData = new BookingDataController();
        $bookingData->ActivateRefer($booking->id);

        /**
         * Calculate the distance based on service type.
         */
        switch ($service_type_id) {
            case '1':
                $bookingcoordinates = BookingCoordinate::query()->where('booking_id', $request->booking_id)->first();
                $pick = $booking->pickup_latitude . ',' . $booking->pickup_longitude;
                $drop = $booking->drop_latitude . ',' . $booking->drop_longitude;
                $distanceCalculation = new DistanceCalculation();
                $distance = $distanceCalculation->distance($from, $to, $pick, $drop, $bookingcoordinates['coordinates'], $merchant_id, $key);
                $distance = round($distance);
                $coordinates = $bookingcoordinates['coordinates'];
                break;
            case '5':
                $distance = GoogleController::GoogleShortestPathDistance($from, $to, $key);
                $distance = round($distance);
                break;
            default:
                $distance = $bookingDetails->end_meter_value - $bookingDetails->start_meter_value;
                $distance *= 1000;
        }

        /**
         * Calculate Trip Amount based on Pricing Type
         */
        switch ($pricing_type) {
            case '1':
            case '2':

                $newArray = PriceController::CalculateBill($price_card_id, $distance, $rideTime, $booking_id, $bookingDetails->wait_time, (double)$bookingDetails->dead_milage_distance, (double)$booking->User->outstanding_amount);

                /**
                 * Check if trip went through a toll gate
                 */
                if (!empty($configuration->toll_api)) {
                    $newTool = new Toll();
                    $toolPrice = $newTool->checkToll($configuration->toll_api, $from, $to, $coordinates, $configuration->toll_key);
                    if (is_array($toolPrice) && array_key_exists('cost', $toolPrice) && $toolPrice['cost'] > 0) {
                        $parameter[] = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'TollCharges', 'amount' => sprintf('%0.2f', $toolPrice['cost']), 'type' => 'CREDIT', 'code' => ''];
                        $newArray[] = $parameter;
                    }
                }
                $newExtraCharge = new ExtraCharges();
                $carditnewArray = array_filter($newArray, static function ($e) {
                    return ($e['type'] === 'CREDIT');
                });
                $amount = array_sum(Arr::pluck($carditnewArray, 'amount'));
                if ($booking->number_of_rider > 1) {
                    $amount += $booking->PriceCard->extra_sheet_charge;
                }
                $booking_time = (int)$booking->booking_type === BookingType::RIDE_NOW ? $booking->created_at->toTimeString() : $booking->later_booking_time;
                $timeCharge = $newExtraCharge->NightChargeEstimate($price_card_id, $booking_id, $amount, $booking_time);
                if (!empty($timeCharge)) {
                    $charge = array_sum(Arr::pluck($timeCharge, 'amount'));
                    $amount += $charge;
                    $newArray = array_merge($newArray, $timeCharge);
                }

                /**
                 * Check and calculate surge price
                 */
                if ((int)$booking->PriceCard->sub_charge_status === 1) {
                    $surge = (int)$booking->PriceCard->sub_charge_type === 1 ? $booking->PriceCard->sub_charge_value : bcdiv($amount, $booking->PriceCard->sub_charge_value, 2);
                    $amount += $surge;
                    $parameter = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'Surge-Charge', 'amount' => sprintf('%0.2f', $surge), 'type' => 'CREDIT', 'code' => ''];
                    $newArray[] = $parameter;
                }
                $discoutArray = array_filter($newArray, static function ($e) {
                    return ($e['type'] === 'DEBIT');
                });

                /**
                 * Check if there's a promo code applied to this booking
                 */
                if (!empty($discoutArray)) {
                    $promoDiscount = sprintf('%0.2f', array_sum(Arr::pluck($discoutArray, 'amount')));
                    $bookingDetails->promo_discount = $promoDiscount;
                    $amount = $amount > $promoDiscount ? $amount - $promoDiscount : '0.00';
                } else {
                    $bookingDetails->promo_discount = '0.00';
                }

                /**
                 * Check if a driver or user is referee
                 */
                $referDiscount = $bookingData->Refer($booking->user_id);
                if ($referDiscount !== NULL) {
                    switch ($referDiscount->offer_type) {
                        case '1':
                            $referAmount = $amount;
                            $amount = 0;
                            break;
                        case '2':
                            $referAmount = ($amount * $referDiscount->referral_offer_value) / 100;
                            $amount -= $referAmount;
                            break;
                        case '3':
                            $referAmount = $referDiscount->referral_offer_value;
                            $amount = $amount < $referAmount ? 0 : $amount - $referAmount;
                            break;
                        default:
                            $referAmount = 0;
                            break;
                    }
                    $parameter[] = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'Promotion', 'amount' => sprintf('%0.2f', $referAmount), 'type' => 'DEBIT', 'code' => ''];
                    array_push($newArray, $parameter);
                }
                $billDetails = json_encode($newArray);
                $bookingDetails->total_amount = sprintf('%0.2f', $amount);
                $payment = new Payment();
                if ($amount > 0) {
                    $payment->MakePayment($booking->id, $booking->payment_method_id, $amount, $booking->user_id, $booking->card_id);
                } else {
                    $payment->UpdateStatus($booking->id);
                }
                $bookingDetails->bill_details = $billDetails;
                $bookingDetails->save();
                \App\Http\Controllers\Helper\CommonController::Commission($booking_id, $amount);
                if ($booking->User->outstanding_amount) {
                    User::query()->where('id', $booking->user_id)->update(['outstanding_amount' => NULL]);
                }
                break;
            case '3':
                $amount = '';
                break;
            default:
                $amount = '';
                break;
        }
        if ($service_type_id === 5) {
            $poolRide = new PoolController();
            $poolRide->DropPool($booking, $request);
        }
        $distance = round($distance / 1000, 2) . ' Km';
        $booking->booking_status = TripStatus::COMPLETED;
        $booking->travel_distance = $distance;
        $booking->travel_time = $timeFormat;
        $booking->travel_time_min = $rideTime;
        $booking->final_amount_paid = sprintf('%0.2f', $amount);
        $booking->save();
        $user_id = $booking->user_id;
        $message = 'Driver End Ride';
        $userdevices = UserDevice::getLastDevice($booking->user_id);
        $playerids = [$userdevices->player_id];
        $data = $bookingData->BookingNotification($booking);
        Onesignal::UserPushMessage($playerids, $data, $message, 1, $booking->merchant_id);
        return response()->json(['result' => '1', 'message' => trans('api.message15'), 'data' => $booking]);
    }



via Chebli Mohamed

Laravel Eloquent Repository - Query giving unexpected result?

I'm using laravel eloquent queries to get the result of all students belonging to a department. The relationship is like this: Each department has classes. Each class has students.

If we are writing this on MySQL, we can have two versions: Let's say we want students belonging to department 5.

  1. select * from class inner join student on class.id = student.class_id where class.department_id = 5;

Equivalent Laravel Eloquent Query:

return $classRepo->where(['department_id'=>5])
            ->select(['id','department_id'])
            ->with(['students'])
            ->get();

  1. select * from student inner join class on class.id = student.class_id where class.department_id = 5;

Equivalent Laravel Eloquent Query:

return $studentRepo
        ->with(['class' => function($query){
            $query->select(['id', 'department_id'])
                ->where(['department_id' => 5]);
        }])
        ->get();

Unexpectedly, the result from the first version is this:

[
    {
        "id": 3,
        "department_id" : 5,
        "students": [
            {
                "id": 61060,
                "name" : "Mark"
            },
            {
                "id": 61061,
                "name" : "Tony"
            }
           ]
    }
]

and from second version is this:

[
    {
        "id": 61057,
        "name" : "Smith",
        "class": null
    },
    {
        "id": 61058,
        "name" : "Jason",
        "class": null
    },
    {
        "id": 61060,
        "name" : "Mark",
        "class": {
            "id": 3,
            "department_id": 5
        }
    },
    {
        "id": 61061,
        "name" : "Tony",
        "class": {
            "id": 3,
            "department_id": 5
        }
    }
]

Can anyone explain me the difference in the results between the two versions? Why I am having nulls in the second version against the class key? How laravel eloquent is actually processing the queries?

classRepo is an object of 'Classes' class

class Classes extends Model{

    public function students()
    {
        return $this->hasMany('App\repoModels\Student','class_id','id');
    }

}


studentRepo is an object of 'Student' class

class Student extends Model{

   public function class()
    {
        return $this->hasOne('App\repoModels\Classes', 'id', 'class_id');
    }

}



via Chebli Mohamed

dimanche 28 juillet 2019

Laravel programming

[enter image description here][1]``` public function store(Request $request) {

//Insert data into Student Table
$student = new Student;
$student->name = $request->name;
$student->registration_id = $request->registration_id;
$student->department_name = $request->department_name;
$student->info = $request->info;
$student->save();

return redirect()->route('index');   

}

public function update(Request $request, $id) { $student = Student::find($id);

$student->name = $request->name;
$student->registration_id = $request->registration_id;
$student->department_name = $request->department_name;
$student->info = $request->info;
$student->save();

return redirect()->route('index');

}



  [1]: https://i.stack.imgur.com/DWtQr.png



via Chebli Mohamed

Laravel 5: Add new value in my column migration

I have existing table and columns. One of my column named status the datatype is enum('0','1') with the default value of 0. And right now I want to add more values in my status column. Will look like this enum('0','1','2','3') with also default value of 0.

My Migration

public function up()
    {
        //
         DB::statement("ALTER TABLE purchase_requisitions CHANGE status ENUM('0', '1', '2','3','4','5')")->default('0')->comment('0 = Unproccessed 1 = Processed');
    }

When I migrate this there's an error

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error i
  n your SQL syntax; check the manual that corresponds to your MySQL server v
  ersion for the right syntax to use near '('0', '1', '2','3','4','5')' at li
  ne 1

Question: How can I implement this using the migration?



via Chebli Mohamed

Where can I find what options that Route::resource supports?

In my web.php I have the following:

    Route::resource('transactions/debit', 'TransactionController', [
        'except' => ['show', 'destroy'],
        'names' => [
            'index' => 'transactions.debit.index',
            'create' => 'transactions.debit.create',
            'store' => 'transactions.debit.store',
            'edit' => 'transactions.debit.edit',
            'update' => 'transactions.debit.update',
        ],
    ]);

I tried the Laravel reference, but the only thing it says is that $options is an array.

Where can I find what are all the $options that the resource method and others support?



via Chebli Mohamed

Getting error whens installing Laravolt Avatar package

Please help. I am getting this errors when installing this package. https://github.com/laravolt/avatar#integration-with-other-php-project.

PS C:\xampp\htdocs\ya> composer require laravolt/avatar Using version ^2.2 for laravolt/avatar ./composer.json has been updated 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 - The requested package florianv/laravel-swap (locked at 1.3.0, required as ^2.0) is satisfiable by florianv/laravel-swap[1.3.0] but these conflict with your requirements or minimum-stability. Problem 2 - The requested package laravel/socialite (locked at v3.3.0, required as ^4.0) is satisfiable by laravel/socialite[v3.3.0] but these conflict with your requirements or minimum-stability. Problem 3 - Conclusion: remove florianv/laravel-swap 2.0.0 - Conclusion: don't install florianv/laravel-swap 2.0.0 - Installation request for florianv/laravel-swap ^2.0 -> satisfiable by florianv/laravel-swap[2.0.0, 2.0.x-dev]. - Conclusion: don't install cache/adapter-common 0.3.3 - florianv/laravel-swap 2.0.x-dev requires cache/illuminate-adapter ^0.2.0 -> satisfiable by cache/illuminate-adapter[0.2.0]. - cache/illuminate-adapter 0.2.0 requires cache/adapter-common ^1.0 -> satisfiable by cache/adapter-common[1.1.0, 1.0.0, 1.1.x-dev]. - cache/illuminate-adapter 0.2.0 requires cache/adapter-common ^1.0 -> satisfiable by cache/adapter-common[1.1.0, 1.0.0, 1.1.x-dev]. - Can only install one of: cache/adapter-common[0.3.3, 1.1.0]. - Can only install one of: cache/adapter-common[1.0.0, 0.3.3]. - Can only install one of: cache/adapter-common[1.1.0, 0.3.3]. - Can only install one of: cache/adapter-common[1.1.x-dev, 0.3.3]. - Installation request for cache/adapter-common (locked at 0.3.3) -> satisfiable by cache/adapter-common[0.3.3]. Installation failed, reverting ./composer.json to its original content.

I have followed the installation procedure



via Chebli Mohamed

Laravel Localization with validation.php file newbie Post

newbie_post

I am using localization for multiple language support in a project. I set locale='myLanguage' in config>app.php for testing purpose. My login validation(auth.php) file working properly with formatted translation also but when I check my other validation (CRUD validation) it shows me the errors.

[2019-07-28 20:17:55] local.ERROR: syntax error, unexpected ''array'' (T_CONSTANT_ENCAPSED_STRING), expecting ']' {"userId":3,"email":"tanvira1993@gmail.com","exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): syntax error, unexpected ''array'' (T_CONSTANT_ENCAPSED_STRING), expecting ']' at C:\Users\Tanvir Ahamed\Desktop\Remote_job\marketplex esources\lang\Bengali\validation.php:62) [stacktrace]

Example : auth.php-> 'failed' => 'এই তথ্য-প্রমাণের সাথে আমাদের রেকর্ড মেলে না।', 'throttle' => 'অনেক ভুল প্রচেষ্টা। অনুগ্রহপূর্বক আবার চেষ্টা করুন :seconds সেকেন্ড পরে । ', in auth.php it's working well.

validation.php-> 'after' => 'এই :attribute must be a date after :date.', 'after_or_equal' => 'এই :attribute তথ্যটি :date তারিখের সমমান বা পরের তারিখ হতে হবে । ', in validation.php it recives the below errors.



via Chebli Mohamed