jeudi 31 mai 2018

Error while registering in Laravel

I'm getting the following error while registering in Laravel:

Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\users given, called in /home/procui74/procurementz/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35

Below is the create() function from my RegisterController.php file:

protected function create(array $data)
{
$userTypeId = user_types::where('userTypeTitle', $data['regTypeRadio'])
                ->pluck('userTypeId')
                ->first();

$user = users::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
    'isActive' => '0',
    'isAdmin' => '0',
    'userTypeId' => $userTypeId,
    'contactPersonName' => $data['personName'],
    'contactNumber' => $data['contactNumber'],
]);

$verifyUser = VerifyUser::create([
    'users_id' => $user->id,
    'token' => md5(uniqid(mt_rand(), true))
]);

Mail::to($user->email)->send(new VerifyMail($user));
return $user;

$notification = array(
    'message' => 'Registration successful! Your account would be activated post verification.', 
    'alert-type' => 'info',
);

return redirect('/')->with($notification);
}

I understand that the error is due to this line: return $user; but what to do not. I need the $user->id to save the user's id in the verifyUsers table.

This code works absolutely fine on my local machine (PHP 7.0.2.4) but doest work on web server (PHP 7.1).



via Chebli Mohamed

Laravel take about 10s before rendering a simple view

I'm working on an existing project built with laravel 5.4 and after I run it in my local machine I realized that all the requests are very slow, so in order to see what slowing down the pages I created a new route:

Route::get('/some/route','TestController@index');

TestController:

class DashboardAutoEvalController extends Controller {

    public function index() {
        echo "Access controller action at: " . time() . "\n"; 
        return view('dashboard.index');
    }

}

index.blade.php

<h1>Access view at </h1>

Here is the result:

enter image description here

As you can see the view take about 9s after it compiles and renders



via Chebli Mohamed

How to accept and process external request in Laravel

Its probably been asked a million times but I can't seem to get the right answer!

How would I make a request to a laravel application externally and process it?

This is what I have so far (built from other stack overflow questions),

My Website

//Send details to Laravel System
$url = 'http://mylaravelsystem.fake/processExternalData';
$data = array('firstname' => $name_first, 'lastname' => $name_last, 'email_address' => $email, 'method' => 4);
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);

My Laravel application

Routes > api.php

Route::post('/processExternalData', 'OptController@insertViaRequest');

OptController@insertViaRequest

    //First create new candidate
    $user = new Candidates;
    $user->firstname = $request->firstname;
    $user->lastname = $request->lastname;
    $user->email_address = $request->email_address;
    $user->created_by = 1;
    if(!$user->save()){
        Log::info((array) $user->save());
    }

My task is to be able to send a POST Request to my laravel application and insert it into the database. Am I missing something with the CSRF Token?

Sorry if this is a stupid question, I just can't seem to figure it out!



via Chebli Mohamed

How to fetch an Aray in laravel using MongoDB database

I have the following document

{
    "_id" : ObjectId("5b1005f8f2468f0fe0007c46"),
    "question" : "my question",
    "answere" : " my answere",
    "options" : [
            {
                    "A" : "dfd"
            },
            {
                    "B" : "fdf"
            },
            {
                    "C" : "fdfdf"
            }
    ],
    "explanation" : "my Explanation",
    "correctans" : "A",
    "updated_at" : ISODate("2018-05-31T14:26:00Z"),
    "created_at" : ISODate("2018-05-31T14:26:00Z")
 }

And now I want to print the options how can this possible. I am trying this.

@foreach($questions as $key => $question)
<tr>                         
 <td></td>  
 <td></td>
 <td></td>
 <td></td>
 <td>
    @foreach($question->options as $key => $option )
       
    @endforeach
  </td>
  <td></td>
</tr>
@endforeach

getting this error

"Trying to get property 'A' of non-object

Fetching the data using this

$questions = Question::all();

Please tell how to fetch



via Chebli Mohamed

Laravel 5 Mail template showing html tags

I have the main mail template (resources/views/mail.blade.php). This is a common template to use all of my mail like for forgot password or for change new password. The content for mail.blade.php is below:

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

I'm storing the content of email template (in mySql db) through CKEditor and it looks like:

<p>Dear ,</p>
<p>This is your new password: </p>

Now I using mail function in laravel 5.5 as below:

$content = str_replace(array('username', 'newPassword'), array($userName, $request->confirm_password), addslashes($emailTemplate->templateBody));

Mail::send(['html' => 'mail'], ['content' => $content], function ($message) use($emailTemplate, $user){
$message->from($emailTemplate->fromEmail, $emailTemplate->fromName);
$message->to($user->email);
});

After sending email in mailtrap.io, I see the mail looks like:

SiteName
<p>Dear Niladri,</p> <p>This is your new password: 123456</p> 

Please note, the table, tr, td where SiteName is written in the mail.blade is working and no HTML code is showing in the email. That's fine. But only the content from the CKEditor is showing with HTML tags (<p></p>).

Have I did anything wrong?



via Chebli Mohamed

htmlspecialchars() expects parameter 1 to be string, array given - Laravel

These are my controllers

public static function getAccessToken()
{

    $url = 'http://api.tech/oauth/authenticate';
    $query = [
        'grant_type' => 'client_credentials',
        'client_id' => 'E3PuC',
        'client_secret' => 'IhvkpkvMdAL7gqpL',
        'scope' => 'bookings.read,images.create,images.read,images.update,locations.read,rates.read,rates.update,reports.read,reviews.read,rooms.create,rooms.delete,properties.read',
    ];

    $client = new Client();

    $response = $client->get($url, ['query' => $query]);

    $content = json_decode($response->getBody()->getContents());

    if ($content) {

        return $content->access_token;
    } else {
        return null;
    }
}
 public function getReviews()
{
    $client = new Client();
    $access_token = $this->getAccessToken();
    $url = 'http://api.tech/hotels/88244/reviews';
    $query = [
        'access_token' => $access_token,
    ];

    $response = $client->get($url, ['query' => $query]);

    $content = json_decode($response->getBody()->getContents());

    if ($content->status == 'success') {

        // return $content->access_token;
       return $content->data;
    //    return $response;
    } else {
        return null;
    }

}
 public function index()
{
    $content = $this->getReviews();
     return view('channel.channel', [
        'content' => $content
    ]);
}

When i try to output the content in my blade as a link, it says ---

htmlspecialchars() expects parameter 1 to be string, array given

and this is my blade file

<a href="">This</a>

It also throws an error when i try to output it like thus



Please How can i solve the error



via Chebli Mohamed

laravel dompdf taking to long to download pdf

I want to make pdf invoice from a template (blade html) using dompdf in laravel 5.5.

The problem is when click on download button the page is loading and after ~3 min a get the pdf.

Why is taking so long?

the download link

<a href="" target="_blank" class="btn btn-danger"><i class="fa fa-file-pdf-o"></i> Download Invoice</a>

web route:

Route::get('/order/download-invoice/{OrderID}', 'Admin\AdminOrderController@downloadOrderInvoice')->name('admin.download-invoice');

a simple template (invoice.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other 
head content must come *after* these tags -->
<title>Invoice</title>
<link rel="stylesheet" href="" media="screen">
</head>
<body>
   <div> </div>
</body>
</html>

donwload invoice controller function:

use Barryvdh\DomPDF\Facade as PDF;
public function downloadOrderInvoice($OrderID){  

    $invoice = Invoice::where('OrderID', $OrderID)->first();
    $pdf = PDF::loadView('invoice.invoice', compact('invoice'))->setPaper('a4', 'landscape');

    return $pdf->download('invoice.pdf');
}

What i did wrong? Did i miss something?



via Chebli Mohamed

Laravel returns "Incorrect datetime value" on update

For reasons unknown our Laravel 5.5 installation fails on all updates where the date starts with "2018-03-25".

Invalid datetime format: 1292 Incorrect datetime value: '2018-03-25 03:00:00' for column 'done_date' at row 1 (SQL: update `hours` set `done_date` = 2018-03-25 03:00:00, `updated_at` = 2018-05-31 12:19:36 where `id` = 481)

All other datetimes are fine.

Here's the table syntax:

CREATE TABLE hours ( id int(10) unsigned NOT NULL AUTO_INCREMENT, task_id int(11) DEFAULT NULL, project_id int(11) DEFAULT NULL, done_hours double(8,2) DEFAULT NULL, done_date timestamp NULL DEFAULT NULL, user_id int(11) DEFAULT NULL, info text COLLATE utf8mb4_unicode_ci, archived_at timestamp NULL DEFAULT NULL, created_at timestamp NULL DEFAULT NULL, updated_at timestamp NULL DEFAULT NULL, deleted_at timestamp NULL DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=906 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

What could cause this?



via Chebli Mohamed

Laravel local scope on eager load

Lets say I have three tables in DB (and three models).

  1. Destination (id, title, region_id)
  2. Region (id, title)
  3. Translations (id, region_id; nullable, destination_id; nullable, translated_value)

Then I have those relations and scopes defined:

  1. Destination

    public function getRegion(){
        return $this->belongsTo('App\Models\Region', 'region_id')->translate();}
    
    public function scopeTranslate($query){
        return $query->join('translations', function($join){
        $join->on('destinations.id', '=', 'translations.destination_id')
           ->where('language_code', app()->getLocale());
    })->select('destinations.*', 'translations.value as translated_title');}
    
    
  2. Region

    public function scopeTranslate($query){
        return $query->join('lm_translations', function($join){
        $join->on('regions.id', '=', 'lm_translations.region_id')
            ->where('language_code', app()->getLocale());
    })->select('regions.*', 'lm_translations.value as translated_title');}
    
    

Then I fetch destinations and eager load translations on both.

 $destinations = Destination::whereHas('getRegion')
     ->with('getRegion')->translate()->get();

Problem: Region gets translation from destination when eager loading, but if I load it usualy everything is fine.

I ran queries directly in DB and they are executed as they should, this means eager loading is not connecting relations correctly.

Where is the catch?



via Chebli Mohamed

first query is sending data even though the last query is failing in a multiple query set up

I am trying to pass multiple query for execution for which i don't want data from 1st query to execute if the last query is having issues.

$user = Gateway::user()->storeDoctorUser(\Input::all(), 'doctor'); 
$address = Gateway::address()->storeDoctorAddress(\Input::all(), $user->id);
$doctors = Gateway::doctor()->storeDoctorData(\Input::all(), $user->id,$address->id);

As stated above how to solve this issue.If somehow the doctor query is failing then also user and address are working ,which should not happen .If the last one fails all should fail.



via Chebli Mohamed

Laravel fetch only pivot columns in many to many relationship

I have a User model that relates to a Section model through a pivot model UserTrainingSection. I have a pivot table that stores the foreign keys for both tables called section_user.

I have 2 additional pivot table columns called completed and completed_date.

The problem I am having is that when I fetch my data it returns all the columns from the User model along with the additional pivot columns.

    class Section extends Model
    {
        public $table = "sections";

        public $fillable = [
            'id',
            'name',
            'description',
            'parent',
            'position',
            'completion_percentage'
        ];

        public function users()
        {
            return $this->belongsToMany(User::class, 'section_user')->using('App\Models\UserTrainingSection')->withPivot('completed', 'completed_date');
        }
    }

In my API service I fetch my data like this:

Section::with(['users' => function ($q) {
                $q->where('users.id', Auth::user()->id);
            }])->first();

How do I only return the pivot table columns and exclude the columns from the user table?



via Chebli Mohamed

laravel dusk and if else statements

I am using laravel dusk to test local websites, there is this one submit that can either go to one of 2 pages and I am wondering if someone could assist me with that.

I am using an if elseif statement but it is not working to see what the next url path begins with

 $this->browse(function (Browser $browser) {
                $browser->visit('/')
                    ->mouseover('@Appliances-mouseover')

                            ->type('@enter-city', 'Location')
                        ->type('@enter-postal-code', '0165')
                        ->click('@select-province')
                        ->click('@selected-province-some-province')
                        ->click('@select-hear-about-us')
                        ->click('@hear-about-us-email')
                        ->click('@agree-terms')
                        ->press('@submit-step-1');

       //                   prevet or step 3 forms in application B
                if ($URL = $browser- 
>assertPathBeginsWith('/application/prevet')) {
                    $browser->screenshot('Prevet form')
                        ->assertUrlIs('/application/prevet')
                        ->pause(25000);

                } elseif ($URL = $browser- 
>assertPathBeginsWith('/application/step3')) {
                    $browser->screenshot('step3 form')
                        ->assertUrlIs('/application/step3')
                        ->click('@uploadPayslip')
                        ->assertSee('Personal Documents')



via Chebli Mohamed

How to implement Laravel5.6 API Resource with Angular 5

i want to connect laravel api resource with angular 5, but i am not able to show result, i faced with this error ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed



via Chebli Mohamed

Passport-Get user by Access token in header

In larvel5.2 Oauth 2 Integration there is a way to get the user data by access token

      Authorizer::getResourceOwnerId();

But how to do it in Passport integration in laravel5.6. How to get the user details by Auth package in laravel.



via Chebli Mohamed

mercredi 30 mai 2018

A default localization lang file doesn't work

I am making small fields changes to the register a user form in register.blade.php file generated by artisan make:auth by changing the Name input field to First Name

so within /resources/lang/en/moo.php I put

return [
    'fname' => 'First Name',
    'lname' => 'Last Name'
];

and in the blade template

<label for="fname"></label>

however the page shows fname as a result so the localization property is not applied. Any ideas what is causing the issue?



via Chebli Mohamed

PHP check if "multidimensional array(array([key]=>value))" values is empty

I have this array I am posting in Laravel from my view to my controller, and I am trying to check if there is any values inside the array, the array is initialized and sent to the view and inside the view I have a table with inputs to fill, if the user doesn't fill the table and submits the form, the array will come back as following:

Array
(
[51] => Array
    (
        [5] => 
        [2] => 
        [8] => 
    )

[78] => Array
    (
        [18] => 
        [23] => 
        [21] => 
    )
)

for clarification and communication:

array(
   [key1]array(
     [key1_1]=>value
   )
)

and I want to check if all of value are empty or not which they are in this example, it would be something similar to empty($array) for 1 dimensional arrays.

I have tried array_filter() but it doesn't serve if the value is inside a key inside a key inside an array.

I know I can use foreach to enter to key1 and then foreach again to enter key1_1 and recursively check if the value is null or not and return false and break the loop whenever a value is not null.

But is there any other way or a method in PHP that allows checking those values? something similar to empty($array) but goes inside the array and checks value only? or something that has the logic of array_filter(array_filter(empty($array)))?

or there is no other way except recursively check each value manually by using foreach?

NOTE: I am using Laravel 5.5, PHP 7.1.9

NOTE: I am not trying if find a specific value is null, I am asking if there is a built-in method in PHP or a simpler method than the one I use to check if the values are all null or not.



via Chebli Mohamed

Laravel 5.6 - eloquent create won't accept array

For some reason the create method won't accept the passed array when I try to create new user.

I am getting following error:

SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2018-05-30 13:24:33, 2018-05-30 13:24:33))

This is the current code:

public function storeUser($data, $request)
    {
        if($request->hasFile('avatar'))
            $data['avatar'] = $this->uploadAvatar($request->file('avatar'));

        $password = \Hash::make($data['temp_password']);

        $data['password']           = $password;
        $data['temporary_password'] = $password;
        $data['social']             = Strings::arrayToJson($data['social']);

        // Assign the clinic_id from the select menu (only super admin have the permission to do this)
        if(\Auth::user()->hasRole('super_admin') && isset($data['clinic_user']))
            $data['clinic_id'] = (int) $data['clinic_user'];

        // If the admin of the clinic is creating the user we wiil use his clinic_id for the new user
        if(\Auth::user()->hasRole('admin'))
            $data['clinic_id'] = \Auth::user()->clinic_id;

        if($this->create($data)){

            event(new NewUser($this, $data['temp_password']));

            if(\Auth::user()->hasRole('super_admin') && isset($data['clinic_owner']))
                event(new ClinicUpdate($this));

            if(\Auth::user()->hasRole('super_admin', 'admin') && \Auth::user()->id !== $this->id)
                $user->giveRole($data['user_role']);

            return true;
        }

        return false;

    }

Fillable:

protected $fillable = [
        'first_name', 'last_name', 'about', 'education', 'position', 'phone',
        'social', 'title', 'gender', 'avatar', 'location', 'email', 'password',
        'temporary_password', 'verified', 'clinic_id'
    ];

This the dd for the data:

array:17 [▼
  "user_role" => "admin"
  "clinic_user" => "1"
  "first_name" => "Sasha"
  "last_name" => "Miljkovic"
  "email" => "xxxxxx@xxxxx.com"
  "temp_password" => "12345678"
  "title" => "10"
  "gender" => "0"
  "position" => "Tester"
  "phone" => "1234"
  "location" => "Pirot"
  "about" => "Maecenas gravida tellus augue, sed mollis quam viverra at. Aenean sit amet dui non eros laoreet porta et nec nisi. Cras lectus justo, porttitor quis mattis nec, ▶"
  "social" => "[]"
  "avatar" => "avatar_5b0ea46d2af8d.jpg"
  "password" => "$2y$10$gxGPBbwS44KHXLn57leRpukX/zu/rX3SSn7jRdM27kvQb9N84CcGa"
  "temporary_password" => "$2y$10$gxGPBbwS44KHXLn57leRpukX/zu/rX3SSn7jRdM27kvQb9N84CcGa"
  "clinic_id" => 1
]



via Chebli Mohamed

Instamojo Payment Integration - Webhook Issue

The response from the instamojo api is successfully extracted but the issue is that, the webhook service is not working. In this I've provided a webhook url in request and i want to exclude the CSRF verification, for that I've included Except array with 'instamojo/*' in middleware but still no use.

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'instamojo/*',
    ];
} 

The current Route

Route::post('webhook','HomeController@webhook');



via Chebli Mohamed

When a Parent has no child in a one to many relationship I get a non-object error when checking it

I have a 'Parent' Table (server) and a 'Child' Table (Server Status) the server status is connected to the server table via its id e.g. the servers id is the same as the server_id in the server status migration using a one to many relationship. What I am trying to do then is iterate through my list of servers and then display the status of the server, which is stores in the server status table. For some reason I am getting non-object error when trying to iterate through a server that has no status. This works then a server has a status that is corresponding to it but but not when I have only a server and no status. Can anyone give me some insight on to why this may be happening? Here is the current code for the controller calling this view, and the loop used to iterate through the data.

index.blade.php:

@guest  
 @if(count($servers) > 0)
   @foreach($servers as $server)
     @if($server->isPublic === 1 )
        @include('inc.statuses')
     @endif
   @endforeach
 @endif
@endguest

@auth
 @if(count($servers) > 0)
   @foreach($servers as $server)
     @include('inc.statuses') 
   @endforeach
 @endif
@endauth

statuses.blade.php:

@if($server->serverStatus->last()->status_id === 1)
    <a href="/servers/"  class="text-dark list-group-item list-group-item-success"></a>
@elseif($server->serverStatus->last()->status_id === 2)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" ></a>
@elseif($server->serverStatus->last()->status_id === 3)
    <a href="/servers/" class="text-dark list-group-item list-group-item-danger" ></a>
@elseif($server->serverStatus->last()->status_id === 4)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > is under maintinance</a>
@elseif($server->serverStatus->last()->status_id === null)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > has no inputted staus</a>
@else
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > has no inputted staus</a>
@endif

controller:

public function index(){
        $servers = Server::orderBY('created_at', 'desc')->get();

        // foreach($servers as $server){
        //     var_dump($server->name);
        //     var_dump($server->serverStatus->last()->status_id);
        //     var_dump($server->serverStatus->last()->server_id);
        // }

        $incidents = Incident::orderBY('created_at', 'desc')->paginate(10);

        return view('pages.index', ['incidents' => $incidents, 'servers' => $servers]);
    }



via Chebli Mohamed

Protocol error in Laravel

I am using Laravel 5.6.23

This is my error message:

UnexpectedValueException    
There is no existing directory at "C:\timereg-project\Laravel\storage\logs" and its not buildable: Protocol error

The directory logs do in fact exist in my Laravel project. I have tried this which is not working:

php artisan cache:clear
php artisan clear-compiled

I have tried this which is also not working:

composer dump-autoload

If I try this:

sudo chmod -R 777 storage
sudo chmod -R 777 storage

I get error

chmod: cannot access 'Laravel/storage/logs': no such file or directory

What can i do about this? It feels like i am totally blocked from the logs folder.

Full error message



via Chebli Mohamed

Eloquent where clause not working as expected

I'm currently working on a private messaging system in Laravel.

I am trying to display a list of message threads in a user's inbox. This works similar to how an instant messaging system displays messages whereby all messages between 2 users are stored in a single thread.

The issue I am having is that I have multiple message types: "Message" and "Task". In the "Message" inbox, I only want to display message threads with the thread type as "Message". To do this I am using the following code in my controller:

    $messageThreads = Thread::where('type', 'Message')
    ->where('sender_id', $user)
    ->orWhere('recipient_id', $user)
    ->get()
    ->sortByDesc('updated_at');

This however isn't working and is still retrieving message threads where the type is "Task" instead of being limited to "Message"

I have also tried:

     $messageThreads = Thread::where('sender_id', $user)
    ->orWhere('recipient_id', $user)
    ->where('type', 'Message')
    ->get()
    ->sortByDesc('updated_at');

But this also returned the same result.

The interesting thing is if I just leave it as

$messageThreads = Thread::where('type', 'Message')

It will only retrieve messages with the type "Message". It is only when I add the other "where" clauses, that it stops working properly.



via Chebli Mohamed

Adding access token to url - Laravel

I have an api url and an access token url in my controller, I use Guzzle/Client for api authentication, The api url I have given the user when loaded asks for the access token url.

How can i merge the access token url to the api url, so that when the api url is accessed it gives the information i want it to give not asking for the access token.



via Chebli Mohamed

Query inside a scope function in Laravel

Is it possible to do a query inside a scope function in Laravel, What am trying to do is get the total sum of available products in a model and compare it with the defined restocking level in another model.

This is what I have so far and its not working

public function scopeDuereorders($query)
{
    return $query->with(["centerdesc"])->where('reorderLevel',"<",Stockdetails::where('partNumb', $this->partcode)->sum('quantity'))->orderBy("partDesc", "ASC")->get();
}



via Chebli Mohamed

Laravel password reset with mongodb

I am working on a laravel project. It's database is mongo db. I am using this package to connect laravel and mongo. I customized laravel login functionality because table fields are not same as default laravel fields. Login customized code is working fine. Is it possible to customize reset password functionality?

In user table the field name are usrEmail and usrPassword. Working code of login is given below.

LoginController.php

protected function attemptLogin(Request $request)
    {
        $authUser     = User::where('usrEmail', $request->email)
            ->whereIn('usrlId', [1, 2, 5, 6])
            ->first();

        if($authUser) {
            $password = md5(env('MD5_Key'). $request->password. $authUser->usrPasswordSalt);
            $user     = User::where('usrEmail', $request->email)
                ->where('usrPassword', $password)
                ->where('usrActive', '1')
                ->where('usrEmailConfirmed', '1')
                ->where('is_delete', 0)
                ->where('usrlId', 2)
                ->first();

            if ($user) {
                $updateLoginTime            = User::find($user->_id);
                $updateLoginTime->lastlogin = date('Y-m-d H:i:s');
                $updateLoginTime->save();

                $this->guard()->login($user, $request->has('remember'));
                return true;
            }
            else {
                return false;
            }
        }

        return false;
    }



via Chebli Mohamed

Register using Telegram bot in Laravel

I try to create registration system with telegram bot in laravel 5.4 , first I install telegram-bot-sdk on my project then I set webhook and everything works nice, but when I want to grab data from users I don't know how should do it ? Because I can only access to last users updates and I cannot detect which message containt to which user ?

These are my problems and I want to know first how can I grab information from different users.



via Chebli Mohamed

Laravel: How to authenticate users without DB

In short, is it possible to authenticate without DB (instead, using User Provider)?

I've seen posts about how to authenticate without password, but would it be ever possible to authenticate without DB?

Here is what I've been trying to achieve...

Ask the user to submit a PIN

Compare the PIN with a value within .env

If the PIN is correct, authenticate the user

It seems to be possible to do authenticate without a traditional RDBMS by introducing a user provider.

However, the doc doesn't seem to describe how the user provider should look like.

Here are snippets of my code (well, I simply mimicked the doc)...

class AuthServiceProvider extends ServiceProvider {

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

        Auth::provider('myUser', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new MyUserProvider($app->make('myUser'));
        });
    }
}

In auth.php...

'providers' => [
    'users' => [
        'driver' => 'myUser',
    ],
],

Now, I have no clue as to how to proceed.

So, I'd like to know...

  1. How the user provider should look like

  2. if it's possible to authenticate users with env() in the first place

Any advice will be appreciated.



via Chebli Mohamed

Laravel migration: How can i change the default value of a ENUM datatype?

In my migration, i have a table column called "assets.status" with datatype ENUM. The default value is set to "active" and i want to modify it by changing it to "processing".



via Chebli Mohamed

How to implement recurring payment using stripe with laravel? How to handle the payment if user upgrade the plans?

I want to implement recurring payment using stripe with Laravel 5.5, which is the best way and flow to implement that.

If the user has an annual plan and they want to downgrade to a monthly plan, then what will happen with payment which already done for an annual plan?



via Chebli Mohamed

Laravel sometimes validation rule not working

I'm trying to implement the sometimes validation rule into one of my projects (Laravel 5.6).

I have a profile page that a user can update their name and password, but i want to make it so that if the user doesnt enter a password, it wont update that field, which is what i thought the sometimes rule was.

The complete update method i am using in my controller is below.

If i leave the password field blank, then it returns a string or min error which it shouldn't be doing.

public function update()
{
    $user = Auth::user();

    $this->validate(request(), [
        'name' => 'required',
        'password' => 'sometimes|string|min:6'
    ]);

    $user->name = request('name');
    $user->password = bcrypt(request('password'));

    $user->save();

    return back();
}

Any help would be greatly appreciated.



via Chebli Mohamed

Laravel seed table from multiple csv files

I'm very new to Laravel and Database and I'm trying to understand how to insert data into my database. Please be patient the question can sounds dummy for you.

  1. STEP

I created a table in migrations. Example of a table:

public function up(){

        Schema::create('job-urls', function (Blueprint $table) {
            $table->increments('id');
            $table->foreign('job_id')->references('id')->on('jobs');
            $table->string('url')->index();
            $table->string('hash');
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();

  1. STEP

I have two csv file that correspond to the field url and hash and I want to insert them. I created a new file in migration called populate_jobs_url

class PopulateJoburls extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(){
        $fileurls = fopen('../data/urls.csv', 'r');
        $filehash = fopen('../data/urls_hash.csv', 'r');

        while (($row = fgetcsv($fileurls, 0, ',')) !=FALSE){
            DB::table('joburls')->insert(
            array(
                'url' => $row,
            )
            );
        }
        while (($row = fgetcsv($filehash, 0, ',')) !=FALSE){
            DB::table('joburls')->insert(
            array(
                'hash' => $row,
            )
            );
            }
    }

Can you help me to understand how I check if the table is correctly filled? Is this approach correct? How could I insert data otherwise in my Database? Unfortunately all examples on the web deal with inserting manually data with a form.

Thanks



via Chebli Mohamed

laravel select join and where clause

I'm learning Laravel framework in parallel developing a small project using it.

Below is the mysql query which I'm trying to incorporate

select id from emails where id not in (select distinct(e.id) from allbreaches b join breaches br on b.domain_name = br.domain_name join emails e on br.eid = e.id where b.domain_name in ("example.com","sample.com");

I'm wondering what is wrong in the below laravel query?

$domainNameList = array('example.com','sample.com');
            $idList = DB::table('emails')
                ->whereNotIn('id', function ($query) {
                    $query->DB::table('allbreaches')
                        ->join('breaches', 'breaches.domain_name', '=', 'allbreaches.domain_name')
                        ->join('emails', 'breaches.eid', '=', 'emails.id')
                        ->whereIn('breaches.domain_name', $domainNameList)
                        ->distinct()->get(['emails.id']);
                })
                ->get();



via Chebli Mohamed

mardi 29 mai 2018

GuzzleHttp Laravel login API using GET request

I want to create Laravel REST API for user registration and login. I created POST method for registration. Now I want to use GET method for login using GuzzleHttp. How can I do that? My routes:

Route::group(['middleware' => 'api'], function() {
Route::group(['prefix' => 'v1'], function () {
    Route::post('/register', 'Api\V1\AuthController@register')->name('user.register');
    Route::get('/signin', 'Api\V1\AuthController@signin')->name('user.signin');
});

});

And this is my controller:

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\JWTAuth;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

    class AuthController extends Controller
    {
         public function register(Request $request)
        {
            $this->validate($request, [
                'name' => 'required',
                'email' => 'required|email',
                'password' => 'required|min:5'
            ]);

            $name = $request->input('name');
            $email = $request->input('email');
            $password = $request->input('password');

            $user = new User([
                'name' => $name,
                'email' => $email,
                'password' => bcrypt($password)
            ]);

            if($user->save()){
                $response = [
                    'msg' => 'User created',
                    'user' => $user
                ];

                return response()->json($response, 201);
            }

            $response = [
                'msg' => 'Error occured'
            ];

            return response()->json($response, 404);
        }

        public function signin(Request $request)
        {
            $client = new GuzzleHttp\Client();
            $this->validate($request, [
                'email' => 'required|email',
                'password' => 'required'
            ]);
        }    
    }

Anyone did something like this. Thanks in advance.



via Chebli Mohamed

Laravel 5.6 - eloquent many to many error 1066

I've got a problem with a many to many relationship in my laravel 5.6 project. I've got some different many-to-many relationships already working but I can't find what is wrong in this one. I've tried google and stackoverflow already but couldn't find the answer.

So, I've got 3 tables; players, teams and players_in_teams I would like to show a player and all the teams he is a part of.

This is my (simple) table layout:

Teams - id - teamName

Players - id - firstName - lastName

PlayersInTeams - id - FKplayerID - FKteamID

my code:

Player.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Player extends Model
{
protected $fillable = [
    'firstName', 'lastName'
];

public function teams() {
    return $this->belongsToMany('App\PlayersInTeam', 'players_in_teams', 'FKteamID', 'FKplayerID');
}
}

Team.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
protected $fillable = ['FKuserID', 'teamName', 'teamDescription', 'FKmediaID'];

public function players(){
    return $this->belongsToMany('App\PlayersInTeam', 'players_in_teams', 'FKteamID', 'FKplayerID');
}
}

PlayersInTeam.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlayersInTeam extends Model
{
protected $fillable = ['FKteamID', 'FKplayerID'];
}

PlayerController.php

public function index()
{
    $players = Player::all();
    return view('players.index', compact('players', $players));
}

showplayer.blade.php

<li></li>
<li></li>
@if($player->teams)
  <li></li>
@endif

The full error i'm receiving:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'players_in_teams' (SQL: select players_in_teams.*, players_in_teams.FKteamID as pivot_FKteamID, players_in_teams.FKplayerID as pivot_FKplayerID from players_in_teams inner join players_in_teams on players_in_teams.id = players_in_teams.FKplayerID where players_in_teams.FKteamID = 1) (View: ../resources/views/players/showplayer.blade.php)

If hope someone sees what I'm missing,

Thanks in advance!



via Chebli Mohamed

PHP - How can I put a watermark in a Autocad DWG file?

I have a PHP Laravel application, and I need to insert a functionality to Insert a watermark (a stamp, better saying) from other file (another DWG, maybe) for a DWG file. I've researched a lot about it, and I haven't found any class or package for that, unfortunately. So is there another way (or trick) to do that? Perhaps convert and "reconvert" to some readible format.

Thank you in advance

P.S: Sorry about my English. That's not my native language



via Chebli Mohamed

vue-loader 15 with laravel-mix

So i am trying to update my vue-loader in laravel project to version 15.2.1. After updating dependencies and running npm run watch first i get an error that i shoul use VueLoaderPlugin. I added it like official documentation suggests. After trying to run build command again i get this error for each one of my single file components:

Invalid CSS after "...load the styles": expected 1 selector or at-rule, was "var content = requi"

If iam adding this rule to my laravel-mix config

rules: [ { test: /\.vue$/, loader: 'vue-loader' } ]

then compilation runs successfully, but in console i get

[vue warn]: failed to mount component: template or render function not defined.  

I use sass and pug in my vue components with appropriate loaders. Adding more rules to laravel-mix config seems to make no difference. All dependencies are up-to date and work well with vue-loader v.14.2.2. Node.js version is 10.1.0. and npm is 6.1.0.



via Chebli Mohamed

Laravel variable model polymorphic

I have a table as follows in my database table area_blocks;

id owner_type owner_id created_at updated_at

in the owner_type fields it has the Eloquent Model name and the owner_id is the id of that model in the database. example db;

db: area_blocks

id | owner_type            | owner_id 
1  | App\Models\Title      | 3 
2  | App\Models\Title      | 4
3  | App\Models\Textarea   | 1

So I'm expecting when I fetch all of these to also eager load the relevant field from the eloquent model stored in owner_type.

Is there an eloquent relationship that can bring back that record from the owner_type field using eager loading? I've tried $this->morphTo() e.g.

public function block()
{
    return $this->morphTo();
}

but that is returned as null. Any ideas how this can be done?



via Chebli Mohamed

store the emoji of post by laravel

enter image description here

I want to store emoji but I don't known the the way

this is the view

<li>
    <div class="box">
        <div class="Like"><a class="Like__link"><i
                class="fa fa-thumbs-up"></i>  </a>
            <div class="Emojis">
                <div class="Emoji Emoji--like">
                    <div class="icon icon--like"></div>
                </div>
                <div class="Emoji Emoji--love">
                    <div class="icon icon--heart"></div>
                </div>
                <div class="Emoji Emoji--haha">
                    <div class="icon icon--haha"></div>
                </div>
                <div class="Emoji Emoji--wow">
                    <div class="icon icon--wow"></div>
                </div>
                <div class="Emoji Emoji--sad">
                    <div class="icon icon--sad"></div>
                </div>
                <div class="Emoji Emoji--angry">
                    <div class="icon icon--angry"></div>
                </div>
            </div>
        </div>
    </div>
</li>

in the migration i add this fields :

Schema::create('likes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('likeable_id')->unsigned();
            $table->string('likeable_type', 255);
            $table->enum('type',[
                             'like', 'love',
                             'haha','wow',
                             'angry', 'sad'
                        ]);
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
        });

how can I store the emoji by simple way help me please



via Chebli Mohamed

Laravel load reduction for the large data insertion in database

As I am newbie to Laravel, please help me find the way from my issue that I have huge data of records from first database which is being used and processed within with some filters then stored into 4 different tables into second database.

There will be data in large amount so how should I manage to insert the data into second database by reducing the load time ?

Here , bulk insertion will not solve the purpose as insertion id is used to insert new records relative to main table of second database.

(Note:There are multiple condition applied to manipulate the data.)

Thanks in Advance.



via Chebli Mohamed

Laravel Not Delete record

I working on laravel to build my php project . I can retrieve data from database successfully but I can not delete records when press delete button , I trying to delete record using ajax so this my ajax code

 $('.userdelete').on('click', function() {
   alert('dfsfs');var id=$(this).data('id');
        $.ajax({
            type: 'DELETE',
            url: '/users/' + id,
            data: {
                '_token': $('input[name=_token]').val(),
            },
            success: function(data) {alert(data);
                toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
                $('.item' + data['id']).remove();
            },
              error: function(data) {console.log(data);;

            }

        });
    });

this is the route

  Route::resource('users','radcheckController');

Users Model

  namespace App;

   use Illuminate\Database\Eloquent\Model;

  class Users extends Model
  {
    protected $table="radcheck";

      }

this is the controller's destroy function

public function destroy($id)
{

  $res=Users::where('username',$id)->delete();

}



via Chebli Mohamed

Laravel 5.5 Expected response code 250 but got code "530"

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

laravel DB laravel 5

        $period = DB::select("
SET @SQL = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when date_time_r = ''',
      date_time_r,
      ''' then count_pursh else 0 end) AS `',
      date_time_r, '`'
    )
  ) INTO @SQL
FROM
(
select Date_format(vuuuee.date_time, '%Y-%M') as date_time_r from vuuuee
where 
 date(vuuuee.date_time) <= date '2018-05-15' 
 and date(vuuuee.date_time) >= date '2017-04-11' 
group by vuuuee.date_time
) d;

SET @SQL 
  = CONCAT('SELECT `id`, ', @SQL, ' 

FROM
(
select id, count_pursh, Date_format(vuuuee.date_time, \'%Y-%M\') as date_time_r from vuuuee
where 
 date(vuuuee.date_time) <= date \'2018-05-15\' 
 and date(vuuuee.date_time) >= date \'2017-04-11\' 
group by vuuuee.id, vuuuee.date_time
) r    
                group by id
                ');

PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;");

How correctly request in laravel 5? Now I get an error but in HeidiSQL it works dsSyntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to us



via Chebli Mohamed

numberic field in psql , what the relevant in laravel schema?

I want to change $table->unsignedInteger('conversion) to using numberic value store in psql

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

class CreateMoneyTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('currencies', function (Blueprint $table) {
            $table->increments('id'); //1
            $table->string('name', 50);//USD - US DollarUSD
            $table->string('country', 20);//US
            $table->timestamps();
        });

        Schema::create('conversions', function (Blueprint $table) {
            $table->increments('id');//1
            $table->unsignedInteger('currency_id');//1. USD
            $table->unsignedInteger('conversion');//=4200
            $table->unsignedInteger('to_id');//2. KHR   
            $table->timestamps();
        });



    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('currencies');
        Schema::dropIfExists('conversions');


    }
}



via Chebli Mohamed

delete item from cart

I want to delete item from cart I

I try to delete It by use this function :

public function deleteItemFromCart($id)
    {
        $items = session('cart');
        foreach ($items as $key => $value)
        {
            if ($value['item']['id'] == $id) 
            {                
                unset($items [$key]);            
            }
        }

        $request->session()->push('cart',$items);

        return redirect()->with('success', 'deleted from cart successfully');
    }



via Chebli Mohamed

I'm facing the issue mentioned below while displaying the price list for the domains suggested

While getting tld's and domain name from enom api I'm getting error as "Unsupported Operand" for particular tld's like "co.in","in.net". Suggest me a solution to solve this.

Find below my controller code

   public function domaincheck(Request $request)
  {
        $sld = $request['sld'];
        $tld = $request['tld'];
        $response = file_get_contents('https://reseller.enom.com/interface.asp?command=check&sld='. $sld .'&tld='. $tld .'&uid=decksys&pw=Amy.th3ist4917&responsetype=xml');  
        $data = simplexml_load_string($response);
        $configdata   = json_encode($data);
        $final_data = json_decode($configdata,true);// Use true to get data in array rather than object
        // dd($final_data);
 }

The blade code is given below:

     <div class="form-group">
     <div class=" col-lg-2"></div>
     <div class="col-lg-8">
         <div class="input-group m-b">
            <span class="input-group-addon" style="padding-left:10px; background-color: #999;" class='unclickable'>www</span>
            <input type="text" name="sld" class="form-control" required>
  <span class="input-group-addon">

  <select class="form-control" name="tld" style="width: 100px;">
  <option value="com">com</option>
  <option value="in">in</option>
  <option value="info">info</option>
  <option value="org">org</option>
  <option value="co.in">co.in</option>
  <option value="in.net">in.net</option>
  <option value="net">net</option>
  <option value="biz">biz</option>
      </select>  
      </span>
      <span class="input-group-addon">
      <button type="submit" class="btn btn-sm btn-success" >Submit</button>  
      </span>

My route is given below:

Route::get('/registerdomain','EnomController@domaincheck');



via Chebli Mohamed

Guzzle certification issue persists

I'm trying to post reCaptcha token vie Guzzle but it seems like there is a certification issue. I tried to handle it by myself. I copied cacert.pem into C:\wamp64\bin\php\php7.1.11 folder and changed ;curl.cainfo removed semicolon.

I tried the solution exactly as it was in this question:enter link description here

But unfortunately it didn't solve my problem. I'm sure I need to make some rearengements. hope somebody can help with that. This is the error I get:

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Laravel 5.4

Php 7.1.11



via Chebli Mohamed

Laravel Testing: assertJsonFragment fails if multiple levels need to be chcked

This is the response:

[  
  {  
    "data":{  
      "locales":{  
        "translate":[  
          {  
            "created_at":"2018-05-28 12:49:53",
            "deleted_at":null,
            "id":1,
            "key":"nl_NL",
            "name":"Netherlands (Nederlands)",
            "updated_at":"2018-05-28 12:49:53"
          }
        ],
        "validate":[  
          {  
            "created_at":"2018-05-28 12:49:53",
            "deleted_at":null,
            "id":2,
            "key":"it_IT",
            "name":"Italian (Italiano)",
            "updated_at":"2018-05-28 12:49:53"
          }
        ]
      }
    },
    "error":false,
    "message":null
  }
]

I want to assert the the following fragments are part of the response:

1) ['translate' => [['key' => 'nl_NL']]]
2) ['validate'  => [['key' => 'it_IT']]]

Is there any way to assert that the translate array contains at least an element with the key of nl_NL and validate contains an element with the key of it_IT?

$response->assertSuccessful()->assertJsonFragment([
    'translate' => [['key' => 'nl_NL']],
    'validate'  => [['key' => 'it_IT']
]);



via Chebli Mohamed

Unable to upload image through form?

Here's my HTML:

                            <label for="attachement1">Attach a file: <small style="color:#999;">(type: zip/rar and below 10mb)</small></label>

                            <input type="file" name="file1"/><br/>
                             <label for="snapshot">Snapshot / Thumbnail:</label>

                            <input type="file" name="thumbnail" required/><br/>
                            <input type="hidden" name="_token" value="">

                            <input type="submit" class="btn btn-primary" name="Submit" value="Publish" />

Here is the code in my controller file (for the update function):

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
      $this->validate($request, [

      'thumbnail' => 'mimes:jpg,jpeg,png|max:800',

      'file1' => 'mimes:rar,zip|max:10000',

      ]);



      $file1=$request->file('file1');

      if(is_null($request->file('file1'))){

        $p=pages::where('id', '=', $request['id'])->first();

        $attmt1=$p->attachment;

      }

      else

      {

      $upload_dir='uploads';

    $attmt1=$file1->getClientOriginalName();

    $move=$file1->move($upload_dir, $attmt1);

      }



      if(is_null($request->file('thumbnail'))){

        $p=pages::where('id', '=', $request['id'])->first();

        $image=$p->thumbnail;

      }

      else

      {

        $img=$request->file('thumbnail');

        $upload_dir='thumbnails';

        $image=$img->getClientOriginalName();

        $move=$img->move($upload_dir, $image);

        //end thumbnail process 

      }

    $mypage->title = $request->title;
    $mypage->body = $request->body;
    //$mypage->thumbnail = $request->thumbnail;
    $mypage->slug = str_slug($request->slug, '-');
    $mypage->menu_name = $request->menu_name;
    $mypage->save();

    return redirect()->route('menupages.index')->with('message', 'Page updated successfully.');
}

When I try to edit an item and upload an image (.jpg format), and click submit, I get a "The thumbnail must be a file of type: jpg, jpeg, png." I checked the database and the file was not recorded.

For some reason, it is detecting the image as some foreign image file type even though it is .jpg.



via Chebli Mohamed

Can we dynamically add data in the google docs in php or laravel?

I want to show the data on the web page in the google docs. Means I have a web page, this page has some data now I want to show this data on the google docs.



via Chebli Mohamed

verify that the file is not corrupted and is from a trusted source before opening the file

what are reason to open excel file corrupted while opening I'm using maatwebsite package in laravel. i have using maatwebsite package for excel in la-ravel while exporting it show Chinese character unable to read



via Chebli Mohamed

lundi 28 mai 2018

How can i submit form keeping existing query string intact in url in laravel

I have a URL something like this : foo?country=usa&state=ny and in foo I have a form which gives me values of firstname & lastname and few more with a submit button.

But when i click submit it gives foo?firstname=john&lastname=doe And the other query i.e country and state get disappear or in other word i am losing them.

Can anyone please tell me how can i peserve them even when i am submiting a form ?

Please note: I can not use any hidden field because there are many forms in foo blade as well as as there can be many query that can come to foo blade not just country and state, there can be age, zipcode etc.

My form in foo.blade.php is like this

<form method="get" action ="">
   <div class="form-group">
      <input type="text" class="form-control" name="firstname" placeholder="first name">
    </div>

    <button type="submit" class="btn btn-green-small">Apply</button>
</form>

    //Another form
 <form method="get" action ="">

       <div class="form-group">
          <input type="text" class="form-control" name="lastname" placeholder="first name">
           </div>
        <button type="submit" class="btn btn-green-small">Apply</button>
    </form>



via Chebli Mohamed

How to set the laravel environment variable from controller using phpdotenv package

Trying to set the environment variable from controller using phpdotenv package but it throws an error "Call to undefined method Dotenv\Dotenv::setEnvironmentVariable()"

use Dotenv\Dotenv;


   $env = new Dotenv(app()->environmentPath(), app()->environmentFile());
   $env->setEnvironmentVariable('APP_ENV_TEST', 'testing');

Laravel Version: 5.6

vlucas/phpdotenv: 2.4



via Chebli Mohamed

Dockerizing existing Laravel app

I'd like some help please. I have git clone a remote Laravel repository from my Bitbucket locally, I've used phpdocker.io to generate my docker-compose and docker directory which I have copied under my root-laravel-direcory, so my folder structure looks like this:

my-laravel-app/
- app/  /* all usual folders and files that Laravel generates
- bootstrap/
- database/
...
- phpdocker/ /* the folder that phpdocker.io generates
- .env
- composer.json
- ...
- docker-compose.yml /* the docker-compose that phpdocker.io generates

This is the docker-compose.yml file

version: "3.1"
services:

    mysql:
      image: mysql:5.7
      container_name: my-laravel-app-mysql
      working_dir: /application
      volumes:
        - .:/application
      environment:
        - MYSQL_ROOT_PASSWORD=secret
        - MYSQL_DATABASE=homestead
        - MYSQL_USER=homestead
        - MYSQL_PASSWORD=secret
      ports:
        - "8890:3306"

    webserver:
      image: nginx:alpine
      container_name: my-laravel-app-webserver
      working_dir: /application
      volumes:
          - .:/application
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8888:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: my-laravel-app-php-fpm
      working_dir: /application
      volumes:
        - .:/application
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.1/fpm/conf.d/99-overrides.ini

When I run docker-compose up -d and try to access http://localhost:8888 I get a white screen with 500 error. How can I fix this?

enter image description here



via Chebli Mohamed

Laravel set the environment variable from controller

I'm trying to set the environment variable from controller but it throws an "Call to undefined method Dotenv\Dotenv::setEnvironmentVariable()"

    $env = new Dotenv(app()->environmentPath(), app()->environmentFile());
    $env->setEnvironmentVariable('APP_ENV_TEST', 'testing');

Laravel Version: 5.6

vlucas/phpdotenv: 2.4



via Chebli Mohamed

Failure to extract data from a relationship with laravel

I am trying to make a one-to-many relationship, but I get the following error

Undefined property: stdClass::$client (View: C:\wamp\www\intranet\resources\views\users\list.blade.php)

The problem is that I am working with an existing database that in the tables does not have id fields, and the foreign keys would also be the typical ones like client_id

My model Client.php

class Client extends Model
{
    protected $connection = 'dpnmwin';

    protected $table = 'nmundfunc';

    public function employee(){

        return $this->hasMany('App\Employee');

    }

}

My model Employee.php

class Employee extends Model
{
    protected $connection = 'dpnmwin';

    protected $table = 'nmtrabajador';

    public function client(){

        return $this->belongsTo('App\Client', 'COD_UND');

    }
}

In nmtrabajador COD_UND field would be the foreign key that relates to nmundfunc.

And I try to get the data out like this: .

but it does not throw me the error, how can I solve it?



via Chebli Mohamed

Laravel show all records from table with joins

I want to show all records from my db in a table like this: enter image description here I have created this function but it doesn't recognize when I try to pass $ticket->id or any other column

public function index(){
       $ticket=Ticket::get();


        $user=DB::table(DB::raw('sarida_test.user AS db1_tb1'))
        ->join(DB::raw('task_flow.tickets AS db2_tb2'),'db1_tb1.Id','=','db2_tb2.user_id')
        ->where('db1_tb1.Id', '=', $ticket->user_id)->UserName;

        $priority = DB::table('priorities')
        ->join('tickets', 'priorities.id', '=', 'tickets.priority_id')
        ->select('priorities.*')
        ->where('priorities.id', '=',  $ticket->priority_id)
        ->title;


        $status = DB::table('status')
        ->join('tickets', 'status.id', '=', 'tickets.status_id')
        ->select('status.*')
        ->where('status.id', '=',  $ticket->status_id)
        ->title;
   return view('ViewTicket') ->with('ticket', $ticket)
    ->with('user', $user);

Basically how can I display all tickets with respective attributes! Thanks in advance!



via Chebli Mohamed

Laravel 5.6: How-to send emails, that clients will show them as threads / conversations?

My Laravel application has a ticket system included, which is sending email notifications.

All emails are built and sent like this one:

public function build()
{
    $email_from_name = "Support - " . config('app.name');
    $subject = "[" . $this->ticket->id . "] " . $this->ticket->subject . " - " . config('app.name');

    return $this->from('support@example.com', $email_from_name)
                    ->subject($subject)
                    ->markdown('emails.customer.ticket.comment_added')
                        ->with([
                            'nickname' => $this->user->nickname,
                            'ticket_id' => $this->ticket->id,
                            'ticket_subject' => $this->ticket->subject,
                            'ticket_text' => $this->ticket_comments->text,
                        ]);
}

Unfortunately, when I get multiple of these emails, no email client (Outlook, Thunderbird, Roundcube,...) shows these emails as thread / conversation. All clients show each email as "new email" thread / conversation.

What specifies, that some emails are one thread / conversation and some not? How can I tell my Laravel application, that these emails are one thread / conversation?

I thought, it just needs to be the same email subject, but it doesn't work.



via Chebli Mohamed

How to set a route parameter default value from request url in laravel

I have this routing settings:

Route::prefix('admin/{storeId}')->group(function ($storeId) {
  Route::get('/', 'DashboardController@index');
  Route::get('/products', 'ProductsController@index');
  Route::get('/orders', 'OrdersController@index');
});

where storeId is a required parameter.

I want storeId to be set automatically from the request URL if provided.

so, if the user requested 'admin/20/products'

then storeId will automatically have the value 20.

maybe something like this.

Route::prefix('admin/{storeId}')->group(function ($storeId) {
  Route::get('/', 'DashboardController@index');
  Route::get('/products', 'ProductsController@index');
  Route::get('/orders', 'OrdersController@index');
})->defaults('storeId', $request->storeId);



via Chebli Mohamed

How to display recently created pages on page using Laravel?

Lot of articles showing how to display on homepage, but what about on another page such as a page?

This is what I have in my controller file:

public function page($slug)
{
    $page = MenuPage::where('slug',$slug)->firstOrFail();
    return view('pages.page', compact('page'));

}

page.blade.php has my page layout code.

Curious to know what code to put into the controller file and what to put in the view file?

I saw this code in one article for the controller file to display recent posts:

 $recentPosts = Post::take(5)->latest()->get();

but where would I put that code at?

In the backend where I manage the list of pages, this is the code used to show the list of pages:

                        @foreach($pages as $page)

                          <tr>

                            <td></td>
                            <td></td>
                            <td></td>
                          </tr>
                       @endforeach

If I put that code into my page layout, I get an "Undefined variable: pages" error.



via Chebli Mohamed

InvalidArgumentException Missing required client configuration options:

I am facing a problem with missing Client region option while integrating My Laravel Project with AWS S3 with CloudFront. Here is my Code Snippet. Please Help me with this



via Chebli Mohamed

Database [dpnmwin] not configured

I'm trying to connect 2 database on my system with laravel 5, and when I try to get data from one I skip this error

Database [dpnmwin] not configured.

my file .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=spi_intranet
DB_USERNAME=root
DB_PASSWORD=null

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=dpnmwin
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=null

My file database.php

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'spi_intranet'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

    'mysql2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_SECOND', '127.0.0.1'),
        'port' => env('DB_PORT_SECOND', '3306'),
        'database' => env('DB_DATABASE_SECOND', 'dpnmwin'),
        'username' => env('DB_USERNAME_SECOND', 'root'),
        'password' => env('DB_PASSWORD_SECOND', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

the error comes out when he tried to bring data from the dpnmwin database, as follows

public function index(){

     $users = DB::connection('dpnmwin')->select('select * from datos_itu');

     return view('users.list',array(
         'users' => $users
     ));

}

but if I want to bring data from my other database spi_intranet

public function index(){

    $users = User::all();

    return view('users.list',array(
            'users' => $users
    ));

}

it brings me the data without problems.

Why do not you bring me the data from my other database?

Is it a problem in the configuration?



via Chebli Mohamed

Laravel Sending Duplicate Notifications

I am building a system where manager of employees receives notifications about tasks assigned to his/her employees as well as the employees. Initially, I get the employees from the database like this:

$users = User::whereIn('id', $employeeIds)->with('manager:id,first_name,middle_name,
                                        last_name,email,phone_no')
           ->get(['id', 'first_name','middle_name', 'last_name', 'email', 'phone_no', 
           'manager_id']);

Then create a collection of managers for each employee type:

$managers = $users->map(function ($item) {
            $manager = $item['manager'];
            $parent['employee'] = $item;
            return $manager;
        });

And finally I send notification to both users via Notification facade.

Notification::send($users, new TaskCompleted($taskData));
Notification::send($managers, new TaskCompleted($taskData));

Now the problem is that let say I have employee A and B both having Manager C as their manager. Notification will send two notifications to Manager C about Employee A only. I have debugged the arrays of data and there is nothing duplicate in there.

Can anyone please help me in the right direction? Should I iterate over the users my self and send individual notifications? As this seems a bug to me in Laravel.



via Chebli Mohamed

Laravel 5 Unable to access currently logged in user id from custom helper

In AppServiceProvider, I called a function from a custom helper as follows:

public function boot()
    {
        View::share('tree', customhelper::generateSiteTree(0));
    }

The custom helper file is calling the database function as below:

$children = UserPermission::getLeftNavByUserId($startAt); 

In the custom helper function, I want to pass the current logged in user ID however, dd(Auth::user()) is returning null.

How can I pass the Auth::user()->id with the method

getLeftNavByUserId($startAt, Auth::user()->id);



via Chebli Mohamed

Export Retrieved data to the excel

hello team I want to export retrieved data to the excel when button is clicked

 <div id="result" class="container">
    <p><button class=" pull-right" id="btn-export">Export</button></p>
    <br>
<?php echo  $usageData; ?>

</div>

please help



via Chebli Mohamed

Laravel undefined variable (but it is sent)

My PostController:

    $posts = Post::orderBy('created_at', 'desc')
                 ->where([['status', 'PUBLISHED'],['post_type', 'PORTFOLIO']])
                 ->paginate(9);

    $partners = Post::orderBy('created_at', 'desc')
                 ->where([['status', 'PUBLISHED'],['post_type', 'PARTNERS']])
                 ->get();
 //   return view('landing.onepageindex', ['posts' => $posts], ['pages' => $pages], ['partners' => $partners]);
    return view(
             'landing.onepageindex',
             ['posts' => $posts],
             ['pages' => $pages],
             ['partners' => $partners]
         );

I'm trying to do a foreach for the partners var, but it says its undefined, what am I doing wrong here? I'm rather new to Laravel, but this thing just got me confused. Am I not allowed to create 2 vars that go for the same post (just different post types)?

Posts and Pages work as they should, partners doesn't.

Thanks in advance.



via Chebli Mohamed

Convert mysql query to working with laravel

I have this mysql query which is working fine for me and now I decided to convert my project to laravel project so I want to convert mysql query to laravel query this is my query

    select c.username,
   max(case when c.attribute = 'Cleartext-Password' then c.value end) as password,
   max(case when c.attribute = 'Expiration' then c.value end) as expiration,
    max(case when c.attribute = 'ChilliSpot-Max-Total-Octets' then c.value end) as quta,
     max(case when c.attribute = 'Simultaneous-Use' then c.value end) as simul,
 max(case when c.attribute = 'Max-All-Session' then c.value end) as session,
   max(c.adsoyad) as realname, min(c.dtarih) as birthdate, min(c.telefon) as phone,min(c.tcno) as tc,max(c.email) as email,min(c.id) as id
 from radcheck c 
group by c.username

how can I do it 



via Chebli Mohamed

Adjust time format in Laravel?

This is my code:

 

The date shows up like this: May-23-2018

How can I modify the code so the date shows up like this: Posted on May 23, 2018



via Chebli Mohamed

Laravel 5.5 fail when serve

5 project and after install Laravel and make php artisan serve it fails.

PHP Warning: require(/var/www/html/sidbrint/vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/sidbrint/artisan on line 18

PHP Fatal error: require(): Failed opening required '/var/www/html/sidbrint/vendor/autoload.php (include_path='.:/usr/share/php') in /var/www/html/sidbrint/artisan on line 18

I'm using an Ubuntu Server and I don't know hat to do.



via Chebli Mohamed

Laravel 5 want to access auth user id in model

I want to access the currently logged In user ID in the model. So in the model, I have written the codes;

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Auth;

and in the method under the model, I used this code: Auth::user()->id However, I receives the error:

Trying to get property of non-object



via Chebli Mohamed

Get collection with own data and secified vars from sub collection in eloquent

First of all, sorry when the question description does not describe my question very well but i have no idea how to form my question better in one line. Suggestions are welcome..

Background info

  • Laravel 5.6.x
  • I defined my objects as eloquent models
  • Using migrations to create the database

Background info about the application

I have an application where a Game object has a one-to-many relation with Player objects. The Game object contains all game details, the Player object contains all details of an individual player.

Players gets invited for a game and can accept of deny this. This info is saved in the player themselves as the player is unique per game.

Now i want to create an overview of all games. One of the things in the overview are the amount of accepted players, the invited players and their id's.

To get all games, i use $games = Game::all(); what gives me an array with all games (without players). I was able to add the players to the array by doing:

foreach ($game as $singleGame){
   $singleGame->players
}

After that my $games array contains all games with a subcollection per game with its players. This is almost what i need, but the subcollection contains to many details about the player, e.g. the hand cards the player has.

The question Is there a simple way to just add the invite_status and player_id value of each player to the game its sub-collection instead of all the players vars?



via Chebli Mohamed

Need to display the suggestion domain price from enom API based on the domain checking API using laravel 5.6

I need to display the domain suggestion price details based to check the domain availability.how to display the domain price based on the tld value.I have displayed the price if the domain is available but i have lot of confusion how to display the suggestion domain price list(This list is based on TLD Value)

DomainName Checking API URL [https://reseller.enom.com/interface.asp?command=check&sld=decksys&tld=com&uid=decksys&pw=Amy.th3ist4917&responsetype=xml&version=2&includeprice=1&includeproperties=1&includeeap=1]

Output of Domain Checking API

{"interface-response":
{"Domains":{"Domain":
{"Name":"decksys.com","RRPCode":"211","RRPText":"Domain not available","IsPremium":"False","IsPlatinum":"False","IsEAP":"False",
"Prices":"Currency":"","Registration":"9.98","Renewal":"9.98",
"Restore":"250.00","Transfer":"9.98",
"ExpectedCustomerSuppliedPrice":null},
"Properties": {"NativeSLD":"","MinRegYear":"1","MaxRegYear":"10",
"AbleToLock":"True","ExtAttributes":"False","Transferable":"True",
"AllowWPPS":"True","TrademarkStart":{"@UTC":"","@Epoch":""},
"TrademarkEnd":{"@UTC":"","@Epoch":""}},"EAP":null}},"Command":"CHECK",
"APIType":"API.NET","Language":"eng","ErrCount":"0","ResponseCount":"0",
"MinPeriod":"1","MaxPeriod":"10","Server":"sjl0vwapi09","Site":"eNom",
"IsLockable":null,"IsRealTimeTLD":null,"TimeDifference":"+0.00","ExecTime":
"0.284","Done":"true","TrackingKey":"ad405f45-e3b7-4299-a8ea- 
fe6a9b2149ad","RequestDateTime":"5/28/2018 2:47:48 AM","debug":null}}

Domain Suggestion API URL [http://reseller.enom.com/interface.asp?command=GETNAMESUGGESTIONS&uid=decksys&pw=Amy.th3ist4917&SearchTerm=deckwsys&ResponseType=XML]

Domain Suggestion API Output

{"DomainSuggestions":{"Domain": 
["DeckSys.builders","DeckSys.build","DeckSys.tech",
"Deck-Sys.builders","DeckSys.lighting","DeckSys.bio","DeckSys.cloud",
"DeckSys.software","DeckSys.global","DeckSys.build","DeckSys.cleaning",
"DeckSys.supply","DeckSys.technology","DeckSys.solutions","DeckSys.tools",
"DeckSys.engineer","Deck-Sys.tech","Deck-Sys.lighting","Deck-Sys.bio",
"Deck-Sys.cloud","Deck-Sys.software","Deck-Sys.global","Deck-Sys.cleaning",
"Deck-Sys.supply","Deck-Sys.technology","Deck-Sys.solutions",
"Deck-Sys.tools","DeckSys.engineer","DeckSy.builders","DeckSy.build",
"TrimSys.builders","DeckSy.tech","ArraySys.builders","AdornSys.builders",
"Deck-Sy.builders","MyDeckSys.builders","TrimSys.build","DeckSy.lighting",
"ArraySys.build","DeckSy.bio","TrimSys.tech","AdornSys.build","DeckSy.cloud"
,"DeckSy.software","ArraySys.tech","DeckSy.global","DeckSysTech.builders",
"Deck-Sy.build","MyDeckSys.build","DeckSy.cleaning"]},"DomainSuggestionCount
":"50","Command":"GETNAMESUGGESTIONS","APIType":"API.NET","Language":"eng",
"ErrCount":"0","ResponseCount":"0","MinPeriod":"1","MaxPeriod":"10","Server"
:"sjl0vwapi06","Site":"eNom","IsLockable":{},"IsRealTimeTLD":{},
"TimeDifference":"+0.00","ExecTime":"0.469","Done":"true","TrackingKey":
"7bd9d667-d3b8-4c7f-91e1-9634a229e4b2","RequestDateTime":"5\/28\/2018 
2:56:20 AM","debug":{}}

Domain TLD Pricing API URL [https://reseller.enom.com/interface.asp?command=PE_GETDOMAINPRICING&uid=decksys&pw=Amy.th3ist4917&responsetype=xml]

Please suggest any solution to display the suggestion domain price based to check the domain availability



via Chebli Mohamed

Laravel - Redirect Catch / Redirect Urls with an .php ending

I have an old static PHP Website, which I would like to update and rebuild it with Laravel. My Problem, all the SEO Links are already indexed with a .php ending.

Is there any chance to catch the URLs with a .php ending and redirect to URLs without a .php ending?

www.website.com/index.php -> www.website.com
www.website.com/en/products.php -> www.website.com/en/products

Thanks for your, help!



via Chebli Mohamed

Laravel how to set middleware to kc finder

i've set Session after i login

session_start();
$_SESSION['ckfinder_auth'] = true;

where Can i set middleware



via Chebli Mohamed

Laravel 5.5 autoload a function for each page without calling that function for each controller

I'm going to create a dynamic left navigation (menu) for each users. I have already created the database table for the same. Also, I have generated the menu structure based on the user logged in. The Left navigation is located as partial view (leftnav.blade.php). I'm currently passing the left nav data (generated from database values) to the view as like:

$data['tree'] = $this->generateSiteTree(0); // left nav generated
$data['bla] = 'bla bla etc';
return view('Administrator.permission.index', $data);

But, I do not want to generate the menu structure for each page individually by writing the same code again for another controller. I know how to create Helper function. My question is - how to automatically call the function for each page?



via Chebli Mohamed

Override primary key with foreign key in hasMany relation using laravel

Here are my tables

Posts

id | name | created_At

Comments

id | comment | post_id | created_at

Post Model

function comments(){
      return $this->hasMany('App\Models\Comment','id','post_id');
 }

PostsController

function index()
{
    Post::with('comments')::get();
}

Now how can i get list of all posts along with comments?

I am trying to match post_id in the child table.



via Chebli Mohamed

Search column not working in datatable

I've Two table join table 1 and table 2, I used datatables working properly but search column not working for table 2 column i.e location. location_id is saved in table1. There is no error in ajax response.



via Chebli Mohamed

How to get data from intermediate table in laravel?

I have 3 table like this,

kelas

id | kelas | romawi

jurusan

id | alias | motto | visi | misi | tahun

kelas_jurusan (intermediate table)

id | id_kelas (from table kelas) | id_jurusan (from table jurusan)

I want to get data 'kelas' in table kelas with accessing the kelas_jurusan table, thanks for your helping



via Chebli Mohamed

dimanche 27 mai 2018

Laravel blade not working with in custom js file

Laravel blade works fine when i place the code in footer section at the bottom. But when i move the code into a custom js file the laravel blade is not working. I am not able to figure out what is the issue.

$(document).ready(function() {

    var url = "{!! url('/') !!}";

    alert(url);

});



via Chebli Mohamed

problems with router in laravel

Based on the job, I need to create an advertisement sheet that belongs to one user. I created a routs resource

Route::resource('/users', 'Users/PreviewController', ['only' => [ 'show', 'create', 'edit','store', 'update', 'destroy']]);
Route::get('/users/{id}', 'Users\PreviewController@index');
Route::get('/users/show/{id}', 'Users\PreviewController@show')->name('users.show');

He does an excellent job. I had to redo the "show" method, in order that I could output a particular user along with his articles. The problem is when I do the redirect after authorization and add the user_name method "index" to the end of the address bar, takes the parameters. But if I remove the address from the address line, I get a conflict. How can I work around this problem or can change the structure of my routing?



via Chebli Mohamed

using Localized Carbon with diffForHumans duplicate number of days

in my page i show posts and i use diffForHumans to display how mush time pass when post created and i translate it usin Localized Carbon in arabic language . it's working but in days he display number of days two times . for exemple instead of showing 5 days ago. he display 5 5 days ago

<div class="row" >
    <!-- properties -->
    @foreach($orderOffers as $key => $offer)
        <div class="col-lg-4 col-sm-6">
            <div class="properties">
                
                <div class="image-holder"><span><i class="fas fa-hourglass-start"></i></span>
                    <img src=""  class="img-responsive dimensions" alt="properties">
                    <div class="status sold">
                        @if($offer->negotiable)
                            <i class="far fa-thumbs-up"></i>  قابل للتفاوض
                        @else
                            <i class="far fa-thumbs-down"></i> غير قابل للتفاوض
                        @endif
                    </div>
                </div>
                <h4><a href="property-detail.php"></a></h4>
                <p class="price"><i class="fas fa-hand-holding-usd"></i></p>
                <p class="price"> <i class="fas fa-map-marker"></i></p>
                <?php
                $id = $hashids->encodeHex($offer->id);
                ?>
                <a class="btn btn-primary" href="">عرض المزيد</a>
            </div>
        </div>
    @endforeach
</div>



via Chebli Mohamed

Bootstrap carousel won't slide when adding dynamic data

I added data from database but they show separately and won't change or slide as they should. I tried using some JavaScript but couldn't make it work.

 
            <div class="carousel-inner">
                @foreach ($news as $row)
                    <div class="item active" onclick="javascript:getimageid('')">
                        <img src="data:image/png;base64,">
                        <div class="carousel-caption">
                            <h4><a href="#"></a></h4>
                            <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
                                tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
                            </p>
                        </div>
                    </div>
                @endforeach
            </div>
            <ul class="list-group col-sm-4">
                @foreach ($news as $rows)
                    <li data-target="#myCarousel" data-slide-to="0" class="list-group-item active">
                        <h4></h4>
                    </li>
                @endforeach
            </ul>
            



via Chebli Mohamed

Laravel Cashier & Stripe Subscription Renewals

I have implemented a subscription package on my application using Laravel Cashier and Stripe.

I would greatly appreciate assistance with understanding the following things please?

  • Does Stripe automatically renew a subscription and generate / send an invoice at the start of a new billing cycle? Or would I have to setup a cron job to renew subscriptions and send invoices?
  • What is the recommended approach to sending the user an email when issues with renewing a subscription arise such as declined cards?

I have spent a long time looking for the answer and have been unable to find anything.

Thank you in advance for any help.



via Chebli Mohamed

exception "ThrottleRequests" errors to many request in api laravel

Since many devices have the same ip address request on the api server, I have a bug to many requests, there is a way to customize the "throttle" that the request is from a single device sent to the server. help me



via Chebli Mohamed

Nested query for getting distinct category and there associated sub-category Laravel

I am working on laravel code, i am finding difficulty in getting nested query for sub-category list. My table structure is, column name below id | category_name | cat_head 1 | ultra slim suit | suit 2 | slim suit | suit 3 | Shoes | shoes 4 | Hats | accessories 5 | Cufflinks | accessories

now i want cat_head as main menu and category_name under it. Kindly help me in laravel eloquent way.



via Chebli Mohamed

creating Multiple Authentication Laravel 5.5

I plan to develop a system that has three two types (admin, users). I want to have each user types information stored in a separate table for easy access and to reduce the number of blank fields (if they were all in one table).

i need all users login in the same login form not separated form for each one of them



via Chebli Mohamed

samedi 26 mai 2018

Laravel Code into Javascript?

I am using dropzone.js in my Laravel App to upload images. The Code looks like this:

<script>
Dropzone.options.myDropzone = {
    paramName: 'file',
    maxFilesize: 5, // MB
    maxFiles: 20,
    acceptedFiles: ".jpeg,.jpg,.png,.gif",
};
</script>

I want to make "maxFiles" more dynamic and load it with data from database. I have a table "cat" where field "count" is populated with a number. I can show the number using

$cat->count

I tried with

maxFiles: $cat->count - not working
maxFiles:  - not working

Can someone advice me how to solve this issue?

Kind Regards,

Stefan



via Chebli Mohamed