lundi 31 juillet 2017

Laravel Serialization of 'UploadFile' class is not allowed

Running tests written by other programmers and encountered the following error:

ErrorException: Serialization of closure failed: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

/home/vagrant/Code/punto/vendor/jeremeamia/SuperClosure/src/SerializableClosure.php:116
/home/vagrant/Code/punto/vendor/jeremeamia/SuperClosure/src/Serializer.php:69
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php:272
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php:193
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:219
/home/vagrant/Code/punto/app/Services/NotificationService.php:126
/home/vagrant/Code/punto/app/Exceptions/Handler.php:42
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:269
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:89
/home/vagrant/Code/punto/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:394

I am not familiar with the system yet. This error seems like I have to implement Serialization to some class.



via Chebli Mohamed

vendredi 28 juillet 2017

how to solve this exception in laravel ? Symfony\Component\Debug\Exception\FatalThrowableError

I run this command to create model.

php artisan make:model BaseModel

but issue this exception

[Symfony\Component\Debug\Exception\FatalThrowableError]                   
 Parse error: syntax error, unexpected '<<' (T_SL), expecting end of file 

may i know how to handle this issue.



via Chebli Mohamed

Connection could not be established with host smtp.gmail.com Network is unreachable #101 error in Laravel email

I am trying to send email from my laravel 5.1 system. I can send emails from my localhost and unable to send from the server. See my email configuration settings in .env file,

MAIL_DRIVER=smtp
MAIL_HOST= smtp.gmail.com
MAIL_PORT= 587
MAIL_USERNAME= username***@gmail.com
MAIL_PASSWORD= *********
MAIL_ENCRYPTION=tls

This configuration only work on my localhost. On server I am getting this error,

Swift_TransportException in StreamBuffer.php line 268:
Connection could not be established with host smtp.gmail.com [Network is unreachable #101]

I also try with changing MAIL_PORT from 587 to 465 and MAIL_ENCRYPTION from tls to ssl. But I am geeitng the same error. How can I fix this issue?



via Chebli Mohamed

jeudi 27 juillet 2017

Only mailables may be queued

i have to update from 5.1 to 5.4

this was code for mail with 5.1

  Mail::queue('emails.welcome_client', compact('user', 'userPassword'), function ($message) use ($user, $adminEmails) {
        $message->subject('Welcome to Enterprise Solutions!');

        $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
        $message->to($user->email);
        foreach($adminEmails as $adminEmail) { 
                       $message->bcc($adminEmail);
}  
});

I have to change from laravel 5.1 to 5.4 so i create object mail

here it is

<?php

 namespace App\Mail;

 use Illuminate\Bus\Queueable;
 use Illuminate\Mail\Mailable;
 use Illuminate\Queue\SerializesModels;
 use Illuminate\Contracts\Queue\ShouldQueue;

 class ClientMail extends Mailable
 {
use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */
public $user;
// protected $content;

public function __construct($user)
{

    $this->content = $user;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->from(('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'))
                ->subject('Welcome to Enterprise Solutions!')
                ->view('emails.welcome_client');
    }
}

and in controller i do this

 Mail::to($user->email)
    ->bcc($adminEmail)
    ->queue(new ClientMail($adminEmails)); 
        }

when I try to run I get this error Undefined $adminEmail How I can fix this problem ?



via Chebli Mohamed

mercredi 26 juillet 2017

Define a relationship as a union

In several parts of my code I have for example these lines:

$user->movements()->get();
...
$user->movements()->where(...)->get();
...
$user->movements()->where(...)->select(... sum, count, avg ...)->get();
...

But now I'm facing an important change on the movements table structure. Now I need two tables with a similar structure (the data HAVE to be in separate tables), movements and ticket_movements.

These tables are consulted by two system, one of then needs the data to be separated and the other needs the data to be as in one table.

So, in one of the systems, I would like to define the relationship movements() as an union of movements and ticket_movements tables.

So, having the relationship movements defined as:

public function movements()
{
        $movements = $this->hasMany('App\Model\Movement')
            ->select(\DB::raw("
                id,
                user_id,
                movement_type_id,
                amount,
                description
            "));

        $tickets_movements = $this->hasMany('App\Model\TicketMovement')
            ->select(\DB::raw("
                id,
                user_id,
                movement_type_id,
                amount,
                description
            "));

        return $movements->union($tickets_movements->getQuery());
    }

If I do this:

$user->movements()
    ->whereIn('movement_type_id', [1, 2])
    ->select(\DB::raw('
        SUM(CASE WHEN movement_type_id = 1 THEN 1 ELSE 0 END) as credit,
        SUM(CASE WHEN movement_type_id = 2 THEN 1 ELSE 0 END) as debit
    '))
    ->first();

The query I get is:

SELECT 
SUM(CASE WHEN movement_type_id = 1 THEN 1 ELSE 0 END) as credit, 
SUM(CASE WHEN movement_type_id = 2 THEN 1 ELSE 0 END) as debit 
FROM "movements" 
WHERE "movements"."user_id" = 2 
AND "movements"."user_id" is not null 
AND "movement_type_id" in (1, 2)

UNION

SELECT id, user_id, movement_type_id, amount, description
FROM "ticket_movements" 
WHERE "ticket_movements"."user_id" = 2 
AND "ticket_movements"."user_id" is not null limit 1

Besides it's not the query I need, it give me an error because of the columns:

Syntax error: 7 ERROR: 
each UNION query must have the same number of columns

The query I need is something like this:

SELECT 
SUM(CASE WHEN movement_type_id = 1 THEN 1 ELSE 0 END) as credit, 
SUM(CASE WHEN movement_type_id = 2 THEN 1 ELSE 0 END) as debit 

FROM (

SELECT id, user_id, movement_type_id, amount, description
FROM "movements" 

UNION

SELECT id, user_id, movement_type_id, amount, description
FROM "ticket_movements" ) as movements

WHERE "movements"."user_id" = 2 
AND "movements"."movement_type_id" in (1, 2)

Without modifying each line where I do $user->movements()...

I don't know is that is possible...



via Chebli Mohamed

Trying to get property of non-object laravel 5.4

We have a project upgraded from laravel v 5.1 to v 5.4 and many issues and bugs appear after upgrade anyway have this one

Trying to get property of non-object for index.blade.php

and this is the code

<tbody>
 @foreach($routeFEmails as $routeFEmail)

 <tr>
 <td></td>
 <td> ()</td>
 <td>:&nbsp; </td>
 <td></td>
 <td></td>
  </tr>
  @endforeach
 </tbody>

i check model and no value from what mention is null no NULL

i did also

php artisan cache:clear 
php artisan route:clear 
php artisan view:clear 

HOW I CAN FIX THIS ? :(



via Chebli Mohamed

mardi 25 juillet 2017

Attaching pivots using Laravel model on a different connection

I am trying to copy some data from one database to another (both share the same schema). Both databases share the same host.

In config/database.php I have the following:

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'connection1',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => [
    'connection1' => [
        'driver'    => 'mysql',
        'host'      => 'host.link.here'
        'database'  => 'db1',
        'username'  => env('DB_USERNAME'),
        'password'  => env('DB_PASSWORD')
    ],

    'connection2' => [
        'driver'    => 'mysql',
        'host'      => 'host.link.here',
        'database'  => 'db2',
        'username'  => env('DB_USERNAME_2'),
        'password'  => env('DB_PASSWORD_2')
    ],
],

I wrote a command to duplicate an experiment from db1 to db2. The relevant part of the code is here:

$experiment = App\Experiment::where('key', 1234)->first();
$connection = 'connection2';

DB::connection($connection)->transaction(function() use ($experiment, $connection) {
        $clone_experiment = $experiment->replicate();
        $clone_experiment->setConnection($connection);
        $clone_experiment->save();

        $this->info('Created experiment on destination DB with ID ' . $clone_experiment->id);

        // Copy objectives
        foreach ($experiment->objectives as $objective) {
            $clone_objective = $objective->replicate();
            $clone_objective->setConnection($connection);
            $clone_objective->save();

            // Attach objective to experiment with pivot data
            $pivot_data = [
                'field_1' => $objective->pivot->field_1,
                'field_2' => $objective->pivot->field_2,
            ];

            $clone_experiment->objectives()->attach([$clone_objective->id => $pivot_data]);
        }
        $this->info('Duplicated objectives');
});

There seems to be an issue with attaching the pivot to the model on db2. I get this output when running the command:

Created experiment on destination DB with ID 3626
Exception: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db1`.`experiment_objective`, CONSTRAINT `experiment_objective_experiment_id_foreign` FOREIGN KEY (`experiment_id`) REFERENCES `experiments` (`id`) ON DELETE CASCADE) (SQL: insert into `experiment_objective` (`created_at`, `experiment_id`, `objective_id`, `field_1`, `field_2`, `updated_at`) values (2017-07-25 23:54:25, 3626, 4973, 10, exploration, 2017-07-25 23:54:25))

The error indicates that the constraint for db1 is failing, but I do not know why it is looking at that since both $clone_experiment and $clone_objective are using connection2, which connects to db2. Is there any way around this?



via Chebli Mohamed

dimanche 23 juillet 2017

Laravel 5.1 Traits not found

My trait is in App/Traits/MyTrait.php and this is how the file looks like:

namespace App\Traits;

trait MyTrait
{
    // ..
}

And this is how my model that includes the trait looks like:

use App\Traits\MyTrait;

class MyClass
{
    use MyTrait; <-- errors out here

    // ..
}

But I still get Trait Not Found error. Any idea why? I am using Laravel 5.1. Do I have make changes in some configuration file?



via Chebli Mohamed

samedi 22 juillet 2017

laravel: how can I output the filepath of a video file

When I uploaded some videos via a form it saved my videos on the public folder but in the view I can't access them.

my view (tyring to output the filepath)

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

result

C:\Users\Jeffrey\AppData\Local\Temp\phpBB7C.tmp
C:\Users\Jeffrey\AppData\Local\Temp\phpBB7C.tmp

it supposed to be on a different path (my project path).

On my local computer on the videos folder I can see that the videos was uploaded.

enter image description here

Mycontroller.php

    public function store(Request $request)
   {
      // Validation //
      $validation = Validator::make($request->all(), [
         'about_me' => 'required',
         'video_ogg'    => 'required|mimes:mp4,ogx,oga,ogv,ogg,webm|min:1|max:3240',
         'video_mp4'    => 'required|mimes:mp4,mov,ogg,qt,webm|min:1|max:3240'
      ]);

      // Check if it fails //
      if( $validation->fails() ){
         return redirect()->back()->withInput()
                          ->with('errors', $validation->errors() );
      }

      $profile = new Profile;

      // upload the media //
      $file = $request->file('video_ogg');
      $destination_path = 'videos/';
      $filename = str_random(6).'_'.$file->getClientOriginalName();
      $file->move($destination_path, $filename);

      // upload the media //
      $file = $request->file('video_mp4');
      $destination_path = 'videos/';
      $filename = str_random(6).'_'.$file->getClientOriginalName();
      $file->move($destination_path, $filename);

      // save media data into database //
      $profile->about_me = $request->input('about_me');
      $profile->video_mp4 = $request->file('video_mp4');
      $profile->video_ogg = $request->file('video_ogg');
      $profile->save();

      return redirect('/profile')->with('message','You just created your profile!');
   }

file permission (on Windows powershell)

enter image description here

So how can I can get the right path on the view?

because it supposed to be : videos/QvWjJ2_mov_bbb.mp4 and videos/muWzE9_mov_bbb.ogg



via Chebli Mohamed

Laravel 5.1: can't upload a video file

On submitting a file I had this following error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'video_ogg' cannot be null (SQL: insert into `profiles` (`about_me`, `video_ogg`, `updated_at`, `created_at`) values (lorem, , 2017-07-23 02:15:50, 2017-07-23 02:15:50))

which states that the field video_ogg cannot be null but when I verify on debugging mode this field is not empty (see below)

controller

    public function store(Request $request)
   {
      // Validation //
      $validation = Validator::make($request->all(), [
         'about_me' => 'required',
         'video_ogg'    => 'required|mimes:mp4,ogx,oga,ogv,ogg,webm|min:1|max:3240',
      ]);

      // Check if it fails //
      if( $validation->fails() ){
         return redirect()->back()->withInput()
                          ->with('errors', $validation->errors() );
      }

      $profile = new Profile;

      //Debugging
      dd($request->files);

      // save media data into database //
      $profile->about_me = $request->input('about_me');
      $profile->video_ogg = $request->input('video_ogg');
      $profile->save();

      return redirect('/profile')->with('message','You just created your profile!');
   }

debugging result

FileBag {#45 ▼
  #parameters: array:1 [▼
    "video_ogg" => UploadedFile {#30 ▼
      -test: false
      -originalName: "mov_bbb.ogg"
      -mimeType: "audio/ogg"
      -size: 614492
      -error: 0
    }
  ]
}

Here as you can see on debugging the video is uploaded or I mean is in the request array but I still have an error message.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'video_ogg' cannot be null (SQL: insert into `profiles` (`about_me`, `video_ogg`, `updated_at`, `created_at`) values (lorem, , 2017-07-23 02:15:50, 2017-07-23 02:15:50))

view

{!! Form::open(['url'=>'/profile', 'method'=>'POST', 'files'=>'true']) !!}
...
      <div class="form-group">
         <label for="video_ogg">Upload Video (ogg)</label>
         <input type="file" class="form-control" name="video_ogg">
      </div>
...

which output this

<form method="POST" action="http://localhost:8000/profile" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="KxvK6tONoUhBCx58ESlbE1hh9eP8hy5nQyNqb62W">

So I did verify that enctype="multipart/form-data" is in the form.



via Chebli Mohamed

Laravel Select Field: How to get selected the saved value of a Model

On the Edit view I have a Select field and I want that select field to have the saved value for a given Model to be selected.

mediaController.php

public function edit($id)
{
    //
     $media = Media::find($id);
     $categories = Category::lists('category', 'id');
     return view('medias.edit-media')->with('media', $media)->with('categories', $categories);
}

edit.blade.php

   <div class="form-group">
       {!! Form::select('categories', $categories, $media->category ) !!}
   </div>

On the index view (i.e the first Media as a Category of Video)

enter image description here

On the edit view (the first Media doesn't have the Category 'Video' selected)

enter image description here

even if I change my edit.blade.php to this: ...

<div class="form-group">
    <label>Category of Upload
        <select name="category" id="category" class="form-control input-sm">
            @foreach($categories as $category)
            <option value="" ></option>

            @endforeach
           </select>
    </label>

</div>

I still have the same result (the right Category is not selected)



via Chebli Mohamed

vendredi 21 juillet 2017

Laravel5.1 user_id insert issue in multiple insertion of records

I need to insert student_id into a table(exam_marks). Data is from a table where a user filters students according to various categories then can assign them marks respectively. When i currently submit... the student_id on exam_marks table gets populated with default array key[0,1,2....] as id's

                       ** #Adding marks view:#** 

         <table id="students" class="table table-striped table-bordered datatable">
                                            <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>photo</th>
                                                <th>Student Name</th>
                                                <th>Reg No</th>
                                                <th>Exam Mark</th>
                                                <th>Action</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            @foreach($students as $student)
                                                <tr>
                                                    <td></td>
                                                    <td><img height="60" width="60" src="" alt="" id="imagePreview"></td>
                                                    <td> </td>
                                                    <td></td>
                                                    <td></td>
                                                    <td class="form-group">
                                                        <div>
                                                            {!! Form::text("examMark[]",null,['class'=>'form-control spinner_default'])!!}
                                                        </div>
                                                    </td>
                                                </tr>
                                                
                                            @endforeach
                                            </tbody>
    </table>
    [marks table][1]

                   **#Marks Controller:#**

    public function store(Request $request)
        {
          //dd($request);
            $this->validate($request, $this->rules);

            $stage_id   = Input::get('stage_id');
            $stream_id  = Input::get('stream_id');
            $year_id    = Input::get('year_id');
            $exam_id    = Input::get('exam_id');
            $subject_id = Input::get('subject_id');
            $term_id    = Input::get('term_id');

            $examMarksList = array();
            $examMarks = Exam_mark::where('exam_id',$exam_id)->where('class_id',$stage_id)->where('subject_id',$subject_id)
                ->where('stream_id',$stream_id)->where('term_id',$term_id)->where('year_id',$year_id)->get();
            foreach ($examMarks as $stMark) {
                $examMarksList[$stMark->student_id] = array("examMark"=>$stMark->examMark);
            }

            $mark = (Input::get('examMark'));
            while (list($key, $value) = each($mark)) {
    //            print "$key is $value\n";
                if(!isset($examMarksList[$key])){
                    $examMarks = new Exam_mark();
                    $examMarks->exam_id = $exam_id;
                    $examMarks->class_id = $stage_id;
                    $examMarks->subject_id = $subject_id;
                    $examMarks->stream_id = $stream_id;
                    $examMarks->term_id = $term_id;
                    $examMarks->year_id = $year_id;
                    $examMarks->student_id = $key;
                    $examMarks->examMark = $value;
                    $examMarks->save();
                }else{
                    $examMarks = Exam_mark::where('exam_id',$exam_id)->where('class_id',$stage_id)
                        ->where('subject_id',$subject_id)->where('stream_id',$stream_id)->where('term_id',$term_id)
                        ->where('year_id',$year_id)->where('student_id',$key)->first();
                    $examMarks->examMark = $mark[$key];
                    $examMarks->save();
                }
            }
        }


    [i want to populate this table with the right student_ids][2]

                **Captions**
      [1]: http://ift.tt/2twXSYb
      [2]: http://ift.tt/2tNIZMj



via Chebli Mohamed

mardi 18 juillet 2017

How to present categories on 2 pages

I Need some help to presnet all the categories in 2 pages. Right now I display them in 1 pages. my quetsion is how can I display them in other page also? this is the controller:

class ShopController extends MainController
{
    public function categories(){       
        self::$data['categories']=Categorie::all()->toArray();
        self::$data['title']=self::$data['title'].'| Shop Categories';
        return view('content.categories', self::$data);   
    }

if im trying to use extends and yield it from the page 'content.categories' it says that $categories is undefined. (so it works only from content.categories)



via Chebli Mohamed

Isuue in query(ordering products)

I want to order products by price with one link for low to high and the other high to low, But after I click "low to high" or "high to low" the order is not changing, it stays on the same page but the url is changing. I tried to debug the query and I got: "select * from products where categorie_id = ? order by price asc" is that means that it can't find the id from categories table? if it is, I can't find whats the problem

this is the function in the controller:

public function products(Request $request, $category_url, $sort= 'ASC')
{
    Product::getProducts($category_url, self:: $data);

    if ( $category1 = Categorie::where('url', '=', $category_url)->first() ) {

        $products = Product::where('categorie_id', $category1->getAttribute('id'))->orderBy('price', $sort)->get();

        return view('content.products', self::$data , compact('products', 'sort')); 
    }
}

this is the route:

  Route::get('shop/{category_url}/sorting-{sort?}', 'ShopController@products');

those are the link from the view, the view is content.products

  <a href="  " style="color:black"> High to low</a> |
  <a href="  " style="color:black">Low to high</a>

the model:

class Product extends Model {


static public function getProducts($category_url, &$data){

    $data['products']=$data['category']=[];


    if ($category=Categorie::where('url','=', $category_url)->first()){

        $category= $category->toArray();
        $data['category']=$category;
        $data['title']=$data['title']. ' | ' . $category['title'];


        if ($products=Categorie::find( $category['id'])->products){

            $data['products']= $products->toArray();
        }
    }
}



via Chebli Mohamed

InvalidArgumentException: Only mailables may be queued

updating from laravel v 5.1 to v 5.4 I got this error

InvalidArgumentException: Only mailables may be queued.

this error for testing for method it was passing before update so how i can fix it ?



via Chebli Mohamed

lundi 17 juillet 2017

Laravel 5.1 Fetch Rows between start_time and end_time (two different fields)

I've been working on reservation project, I collect request (time_start and time_end) and add 1:30 hour to each so i can prevent user to select conflicts.

I tried using "Between" already but it doesnt seems to work.

->whereBetween('reservation_time_start', [$time_from, $time_to])
->whereBetween('reservation_time_end', [$time_from, $time_to])

I also tried this,

->whereRaw('((reservation_time_end <= ? AND reservation_time_end >= ?) OR (reservation_time_start >= ? AND reservation_time_start <= ?))',[$time_end, $time_start,$time_start, $time_end])

It work but in some cases like between some time range, i dont get any results. Like This.

+----+------------------------+----------------------+
| id | reservation_time_start | reservation_time_end |
+----+------------------------+----------------------+
|  1 | 10:00:00               | 13:00:00             | <- i need to get this
|  2 | 12:00:00               | 14:00:00             |
|  3 | 14:00:00               | 15:00:00             |
+----+------------------------+----------------------+

sample user input's: $reservation_time_start = 12:00:00 (-1:30 Hour) $reservation_time_end = 14:00:00 (+ 1:30 hour)

and when i run my code, it returns null. Please help.



via Chebli Mohamed

AWS SNS HTTP subscription confirmation in PHP

I am unable to get the confirmation of AWS SNS Http connection in PHP. My application is developed on Laravel 5.1

In AWS I have created a Topic and added a subscription. I have selected endpoint as HTTP and provided the URL http://myurl.com/sns.

My PHP code is below

public function getSnsMessage()
{
   $message = Message::fromRawPostData();
   $validator = new MessageValidator();
   // Validate the message and log errors if invalid.
   try {
       $validator->validate($message);
    }catch (InvalidSnsMessageException $e) {
       // Pretend we're not here if the message is invalid.
       http_response_code(404);
        error_log('SNS Message Validation Error: ' . $e->getMessage());
       die();
    }

    // Check the type of the message and handle the subscription.
   if ($message['Type'] === 'SubscriptionConfirmation') {
       // Confirm the subscription by sending a GET request to the SubscribeURL
       file_get_contents(public_path() . '/awssns.txt','SUB URL MESSAGE = '.$message['SubscribeURL'].PHP_EOL, FILE_APPEND );
    }
  }

My route file entry is:

Route::get('/sns', [
'as'   => 'sns',
'uses' => 'SnsEndpointController@getSnsMessage',
]);

In the browser when I call the URL – http://myurl.com/sns, I get the below error.

RuntimeException in Message.php line 35:SNS message type header not provided.
1.    in Message.php line 35
2.    at Message::fromRawPostData() in SnsEndpointController.php line 26
3.    at SnsEndpointController->getSnsMessage(object(Request))
4.    at call_user_func_array(array(object(SnsEndpointController), 
       'getSnsMessage'), array(object(Request))) in Controller.php line 256

I have the following in my composer:

"aws/aws-sdk-php-laravel": "^3.1",
"aws/aws-php-sns-message-validator": "^1.2"

Any help on how to resolve this error and to get confirmation of my subscription?



via Chebli Mohamed

Stop bootstrap modal from closing when submitting a blank form to allow Laravel messages to display

I'm using a bootstrap modal window for user to fill out a form, and I'm processing the validation using Laravel 5. The issue I'm having is that the modal window closes when the user hits the submit button, even if the form fields are blank. When the user logs back in to the form, the messages are displayed.

I tried adding the 'required' option to the input elements; however, it doesn't display the laravel error but rather the HTML error.

How can I stop the modal window from closing if any of the required fields are not filled in?

MY MODAL CODE

<div class="modal fade" id="editItemModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                 @include('includes.info-box-error')
                <h4 class="modal-title">Modal Title</h4>
            </div>

            <div class="modal-body">
                <form action="" method="post" name="myEditForm" >
                    <div class="form-group">
                        <label for="code">Code:</label>
                        <input type="text" size="5" maxlength="5" minlength="3" class="form-control" name="code" id="code" required> 
                    </div>

                    <div class="form-group">
                        <label for="description">Description:</label>
                        <input type="text" class="form-control" name="description" id="description" required>     
                    </div>

                    <div class="form-group">
                        <label for="amount">Amount:</label>
                        <input type="number" class="form-control" name="amount" id="amount" size="5" maxlength="5" required>
                    </div>

                    <div class="form-group">
                        <label for="newImage">Upload Image</label>
                        <input type="file" class="form-control" name="newImage" id="newImage">
                    </div>

                    <div class="form-group">
                        <label for="radio">Type:</label>
                        <div class="radio">
                            <label><input type="radio" name="optradio" value="in">In</label>
                            <label><input type="radio" name="optradio" value="out">Out</label>
                        </div>
                    </div> 

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary pull-right">Submit</button>
                        <input type="hidden" name="_token" value=""/>
                    </div>                
                </form>

            </div><!--Modal Body-->
        </div><!--Modal Content-->
    </div><!--Modal Dialog-->
</div><!--Modal-->  

MY PHP CODE

 <?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use \App\Product;

 class ProductsController extends Controller
 {
   public function getIndex()
      {
     $products = Product::orderBy('created_at', 'desc')->paginate(10);
    return view('index', ['products' => $products]);
}

public function postNewProduct(Request $request)
{
    $this->validate($request, [
        'code' => 'required|max: 5|alpha_num|unique:products',
        'description' => 'required|max: 20',
        'amount' => 'required|numeric'
    ]);

    $product = new Product();
    $product->code = strtoupper($request['code']);
    $product->description = ucfirst($request['description']);
    $product->in = $request['amount'];
    $product->out = 0;
    $product->save();

    return redirect()->route('index')->with(['success' => 'New product successfully added.']);


}
}



via Chebli Mohamed

Octobercms disable translations on a different domain

I'm trying to build a website wich can be accessed through the main domain, wich will use the main theme. But can also be accessed through different domains wich are saved in the database, these will use a different theme.

The problem i am having is that the main website uses the rainlab translations plugin wich automatically changed the normal url to url+locale. This is something i do not want to use in my other theme, wich result in a 404.

I change the theme in my own plugin like so:

$currentHostUrl = Request::getHost();

    Event::listen(
        'cms.theme.getActiveTheme',
        function () use ($currentHostUrl) {
            $domain = Domain::where('domain', $currentHostUrl)->first();
            if($domain !== null)
            {
                return 'differentTheme';
            }
        }
    );

This is based on the way keios made their multisite plugin.

I would like to know how i can stop the localisation url change when the other domains are visited.

I hope someone knows how to help me. Thanks in advance.



via Chebli Mohamed

vendredi 14 juillet 2017

Laravel Multiple Image upload

I want to upload multiple image for my restaurant site. where I want to add many food item with image. but problem is when i submit with my input it only enter multiple image and only first data of entry to the database again and again with those image respectively. Here is my store method code:

         $id=$restaurant->id;
        $files=$request->file('image');

            foreach ($files as $file) {
           $menu=time().'.'.$file->getClientOriginalName();
     foreach ($request->category_name as $key => $v) {
            $data = array(
                'rest_id'=>$id,
                'cat_id'=>$v,
                'menu_name'=>$request->menu_name [$key],
                'menu_price'=>$request->menu_price[$key],
                'image'=>$menu
                );

                 Mnu::insert($data);
                 break;
     }
     } 
    }

Here is My Html Code:

<tbody>
                                    <tr>
                                        <td>
                                            <select name="category_name[]" class="form-control productname">
                                                <option value="0" selected="true" disabled="true">Food Category</option>
                                                @foreach($category_name as $key =>$p)
                                                <option value="{!! $key !!} ">{!! $p !!}</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td> <input type="text" name="menu_name[]"> </td>
                                        <td> <input type="text" name="menu_price[]"> </td>
                                        <td> <input type="file" name="image[]" multiple> </td>
                                        </tr>
                                </tbody>

Here is my Database table: .

Database Here in id 347 and 348 have same data expect image field. but my input was difference . But it take only diffrences images and same data

Please Help me to sort out this problem. pleasee



via Chebli Mohamed

jeudi 13 juillet 2017

How can I retrieve the information I want using MySQL `joins` or Laravel `relationships`?

I am working on a project using the Laravel framework. In this project I have three tables:


1) Master Part Numbers (master_part_numbers)

Columns: id, part_number

Values: 1, MS26778-042


2) Inventory (inventory)

Columns: id, master_part_number, stock_qty

Values: 1, 1, 7


3) Inventory Min Maxes (inventory_min_maxes)

Columns: id, master_part_number, min_qty

Values: 1, 1, 10


I am trying to find the inventory where the stock level is below the min_qty. I have been attempting this using joins, like so:

$test = MasterPartNumber::table('master_part_numbers')
                            ->join('inventory', 'master_part_numbers.id', '=', 'inventory.master_part_number_id')
                            ->join('inventory_min_maxes', 'master_part_numbers.id', '=', 'inventory_min_maxes.master_part_number_id')
                            ->select('master_part_numbers.part_number')
                            ->where('inventory.stock_qty', '<=', 'inventory_min_maxes.min_qty')
                            ->get();

However I am getting an empty collection every time. I have tried removing the where() clause and I get all the part numbers in the inventory, so it feels like I'm on the right track, but missing a critical component.

Also, I don't know if there is an easier or more efficient way to do this using Laravel's Eloquent Relationships, but that option is available.

Note: I added the space after table('master_part_numbers') in my query displayed here on purpose, for readability.



via Chebli Mohamed

laravel upload files in many inputs

I'm trying to upload files in 4 inputs files i get the solution from here but the problem the last file4 input file uploaded in all fields in database

in my blade form

{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}

in my controller

$input = $request->all();
    $files =[];
    if ($request->file('file1')) $files[] = $request->file('file1');
    if ($request->file('file2')) $files[] = $request->file('file2');
    if ($request->file('file3')) $files[] = $request->file('file3');
    if ($request->file('file4')) $files[] = $request->file('file4');
    foreach ($files as $file)
    {
        if(!empty($file)){
            $destinationPath = public_path() . '/uploads';
            $filename = $file->getClientOriginalName();
            $file->move($destinationPath, $filename);
        }

    }
    $model = new Project($input);
    $model -> file1 = $filename;
    $model -> file2 = $filename;
    $model -> file3 = $filename;
    $model -> file4 = $filename;
    $model->save();



via Chebli Mohamed

mercredi 12 juillet 2017

Laravel delete related data?

If have a system that works like this.

There is a theme, Within a theme, are many topics and in those topics are many replies. To delete a topic you have to delete the replies that are related to that topic too. So I made that with the following code

$topic = Topic::find($id);

$topic->replies()->delete();

$topic->delete();

return redirect('/');

But now I'm trying to delete a theme. Which has to delete every topic that is related to that theme and every reply that is related to every topic within that theme. But how do I do this? I figured it may be something like this?

$theme = Theme::find($id);
$theme->topics()->delete();
$theme->topics()->replies()->delete()
$theme->delete();

return redirect('/');

But that doesn't work. How can I make this work? Thanks in advance



via Chebli Mohamed

database connection error while connecting database in live server error 1045

my .env file setup like this on the live server. but while I am

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=onlyaruv_notepad-apps
DB_USERNAME=onlyaruv_notepad
DB_PASSWORD=mypassword

the error was

SQLSTATE[28000] [1045] Access denied for user 'onlyaruv_notepad'@'127.0.0.1' (using password: YES) (SQL: select * from `users` where `email` = ih76632@gmail.com limit 1)

I access my ssh via putty using this host and password http://ift.tt/2tLULbM I am confused .



via Chebli Mohamed

mardi 11 juillet 2017

Proxy url routing in Laravel

I have been recently handed a project which has a very weird proxy routing setup in it. Basically the setup is that they have the app setup and hosted on an AWS instance which is pointed to by a domain say project.example.com. They have set this project.example.com to as their APP_URL in the env file and this all works like its supposed to. Then there comes the proxy url into play, which is basically a domain like http://ift.tt/2ub4x9y, this subfolder routing actually points to the same domain and codebase that I mentioned earlier, project.example.com. I don't actually know much about the setup of the http://ift.tt/2ub4x9y domain that is pointing to the actual codebase domain but whenever we hit it we are routed correctly.

On the laravel side what the previous devs have done is basically defined a new variable say PROXY_URL in the env file and set this as http://ift.tt/2ub4x9y and on the top of the routes.php file they do a forceRootUrl to basically set the base/app url to what has been defined in the PROXY_URL. Now I and the app are having problems due to this weird kinda routing as devs were reporting me issues previously due to urls not being made properly. The current problem I'm having is that a package for laravel to handle grid listings which is being used here, Nayjest, makes the grid properly but inside the table listing it messes up all the urls it has made, basically the urls are correct but the base urls are set in it as the old APP_URL, like http://ift.tt/2v9r9V5 when it should've been http://ift.tt/2ub4B9i. The reason I found for this was that the package was using the base url from the Request object of laravel, which on the runtime checks the servers hostname which is set to of course project.example.com, so basically not using the Laravel's Url() method to fetch the base/app url (which has now been over ridden due to forceRootUrl). Now the solution could be to ask the package's dev to change it to use Url() method, but I have seen the use of this Request object's base url in core laravel code as well (there must be a reason they are doing it which I would like to know as well).

My questions are many here, firstly this approach to handle the proxy domain, is this correct or is there a better one ? Secondly if one is using this approach how can we ask or tell the package to use the Url() method instead of the Request object's getSchemeAndHttpHost without changing the source of the package(a hack basically in our code). Thirdly are we looking straight at the problem coz I kept thinking that instead of correcting the base url in the grid listing we can keep it as it is and handle the routing of it along with query parameters correctly so we reach say from this http://ift.tt/2v9r9V5 to this http://ift.tt/2ub4B9i correctly.

Any help would be greatly appreciated, thanks.



via Chebli Mohamed

Larave Dotenv on beanstalkd Queue

I have three dot env, default .env for example.com, .env.sub1 for sub1.example.com and .env.queue2 for sub2.example.com

I am able to load different .env when I bootstrap using the following code in bootstrap/app.php. This works really well when I access the websites.

$env = $app->detectEnvironment(function () {
    $environmentPath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;
    $environmentFile = null;
    switch (getenv('HTTP_HOST')) {
        case 'sub1.example.com':
            $environmentFile = '.env.sub1';
            break;
        case 'sub2.example.com':
            $environmentFile = '.env.sub2';
            break;
    }
    if (!empty($environmentFile) && file_exists($environmentPath . $environmentFile)) {
        Dotenv::load($environmentPath, $environmentFile);
    } else {
            // .env will be in affect, do nothing
    }
});

This also works really well when your QUEUE_DRIVER is set to sync.

But the problem when my QUEUE_DRIVER is set to beanstalkd it take the environment variables always from .env.

Where is beanstalkd queue loading the .env while executing a queued job.

Thanks,

K



via Chebli Mohamed

Angularjs laravel 5 posting form data using post method 404 page not found error. But get method works

Using Angularjs laravel 5.1 posting form data using post method 404 error comes but get method works fine

controller

`(function (ng, app) { app.controller('app.promocodeCtrl', function($scope,$http) { // create a message to display in our view

    $scope.newPromocode = function(){


        $scope.onSubmit = function(){
            console.log($scope.form);
            // $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            //$http.defaults.headers.post["Content-Type"] = "text/plain";
            var request = $http({
                method: "POST",
                url: "backend/statistics/promo",
                data: {
                    promocode : $scope.form.codetxt,
                    discount : $scope.form.discount,
                    minvalue : $scope.form.minvalue
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (data) {
                alert(data);
            });
        }

    };

});

})(angular, angular.module('app'));`

route

Route::post('statistics/promo', ['uses' => 'Api\Backend\Statistics@promoCode']);



via Chebli Mohamed

lundi 10 juillet 2017

Laravel 5.1 Redis - create cache for existing data

I am looking for some way to create cache for the existing data I have in laravel db. I have searched around the web. There are plenty of tips on how to enable caching for new data but none for existing. Example would be a large number of products for sale that are in my inventory database. Please advise.



via Chebli Mohamed

Call to undefined relationship [topic] on model [App\Theme]

I'm trying to display the latest Topic that is related to a Theme. I did this before and I tried the following code in the ThemesController (Index method, Sinse it's the homepage),

$topics = Theme::with('topic', 'lastTopic.user')->get();
$themes = Theme::all();

return view('themes.index')->with('themes', $themes)->with('topics', $topics);

And the method I'm calling is this.

public function lastTopic()
{
    return $this->hasOne(Topic::class)->latest();
}

The method sits inside the Theme Model, It doesn't matter if i put the method in the Topic Model of the Theme Model, It still gives me the same error. So what is causing this issue? This is for my homepage so the route is this Route::get('/', 'ThemesController@index')->name('home');. I know it is something I've done before but I can't figure it out. Thanks in advance



via Chebli Mohamed

how to publish vendor from package Laravel 5

So I've my custom Laravel 5.4 package, and i want to publish the vendor packages located into my package, this is my code (PackageServiceProvider.php):

$this->publishes([
  __DIR__.'/../vendor/soundasleep' => public_path('soundasleep'),
], 'html2text');

but when i run php artisan vendor:publish --tag=html2text the vendor is published into public folder and i want to be published into my application vendor, because when i tried use \Html2Text\Html2Text as html2text; into my package routes.php i got class Html2Text\Html2Text not found.

so please if someone has any idea i'll be very appreciative.



via Chebli Mohamed

Laravel 5.1 return eloquent between time_start and time_end

Here's my Sample Table:

reservation_date | time_start | time_end 7/10/2017 | 12:00:00 | 14:00:00

what i'm trying to do is to return all reservations between time_start and time_end base on the request by the user. and sub/add 2 hours from time_start and time_end to prevent conflicts. I tried

$times_data = $this->getTimesData($request->reservation_time_start, $request->reservation_time_end);

$reservations =  $reservations->whereBetween('reservation_time_start', $times_data)

protected function getTimesData($time_start, $time_end)
    {

        $time_from = $this->getTimeFrom($time_start);

        $time_to = $this->getTimeTo($time_end);

        return [$time_from, $time_to];
    }

protected function getTimeFrom($time)
    {
        $time = Carbon::parse($time);

        return $time->subHours(2)->toTimeString();
    }


    protected function getTimeTo($time)
    {
        $time = Carbon::parse($time);

        return $time->addHours(2)->toTimeString();
    }

But the result is not what i expected. i also tried

->whereRaw("(reservation_time_start BETWEEN ? AND ?) AND (reservation_time_end BETWEEN ? AND ?) ",$times_data)

but it returns null. Please help.



via Chebli Mohamed

vendredi 7 juillet 2017

Laravel 5.1 Search API Capability on an existing table with data

I need to build an API that will query mysql database that already has data in it to provide real time matches so that user can select on. Any suggestions? I am using Laravel 5.1 on EC2 and RDS.



via Chebli Mohamed

Laravel show last reply left on post

I'm trying to show the last reply that was left on a post. But only the name and date of it. I tried the following things

What I think this one should do is look at the replies to the post. Sort them by ID and then display the first one's username. But it doesn't work. $topic->replies->sortBydesc('id')->first()->user->username }}

I also tried this one where I requested all the replies in the entire forum and displayed the last one. It worked but I wasn't the one related to the post.

Does anyone know how I can make this work? Currently, i'm passing these two into the view (There is nothing wrong with these, they work but I think there should be something added)

public function show($id)
{


    $topics = Topic::with('theme')->find($id);
    $theme = Theme::with('topics')->find($id);

    return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}

Thanks in advance



via Chebli Mohamed

how to install vendor package from laravel package

So i'am in Laravel 5.4 and i've my custom package packages/dev/mypackage.

And i want to install soundasleep/html2text into my package, so i add this to my packages/dev/mypackage/composer.json :

{
  "require": {
    "soundasleep/html2text": "~0.5"
  }
}

then composer update , but when i tried to call html2text i got always class Html2Text\Html2Text not found.

So please if someone has any idea i'll be very appreciative.



via Chebli Mohamed

jeudi 6 juillet 2017

Autofill / Autocomplete using Larave 5.1 / php backend

I want to auto-submit a third party multi-step form using php on the back end and possibly crawl a couple of pages after submission. A good example would be log into an e-commerce site on a user's behalf and look get their purchase history. Or fill out a multi-page college application and get the submission confirmation page along with the application id. Any suggestions?



via Chebli Mohamed

mercredi 5 juillet 2017

Node js file upload empty request in lumen

When i upload a file in Node JS, ajax request send to Lumen. But the request is empty.

This happen only on server, In my localhost working fine.

Please advice..

Ajax request :

uri: config.apiEndpoints.uploadStatement,
headers: {
    'Authorization': token
},
method: 'POST',
formData: {
    lender: "lender",
    product: "product",
    source: "statement",
    "document[]": formData[1].statement ? fs.createReadStream(formData[1].statement[0].path) : "",
    "document_key[]": formData[0].password[0],
} 

Lumen :

public function uploadstatement(Request $request)
{
  \Log::info(json_encode($request->all()));
  
  $basicRules = [
      'lender' => 'required|in:'.implode(',', config('api.lenderList')),
      'source' => 'required|in:'.implode(',',  config('api.sources'))
  ];
  $validator =  Validator::make($request->all(), $basicRules, [
      'lender.in' => 'Requested lender doesn\'t exist in our list',
      'source.in' => 'Requested source doesn\'t exist in our list'
  ]);
  if ($validator->fails()) {            
      return $this->showValidationResponse($validator->messages());
  }
}


via Chebli Mohamed

mardi 4 juillet 2017

QueryGrammar is null in Laravel5.1/Jessenger 3.0 and MongoDB 3.4

I have a Laravel 5.1 application running on Ubuntu 16.04 and PHP 5.6

This was previously using mongo.so (the older MongoDB PHP driver) and I have migrated it to the new driver mongodb.so - this was required since I upgraded MongoDB to 3.4 and would like to connect to a MongoDB Replica Set

I was using Jennseger's library to connect, which I also upgraded - and updated the to the laravelcollective/html library as well

The current composer.json file looks like this:

..
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"laravelcollective/html": "5.1.*",
"jenssegers/mongodb": "3.0.*",
..

When I login to the application, it generates the following error:

in Builder.php line 214
at HandleExceptions->handleError('4096', 'Argument 2 passed to Illuminate\Database\Query\Builder::__construct() 
must be an instance of Illuminate\Database\Query\Grammars\Grammar, null given, called in 
<app_root>/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 1873 and defined', 
'<app_root>/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php', '214', array('connection' => object(Connection))) in Builder.php line 214

I have followed the guidelines to a similar error and replaced my Eloquent models

e.g. the following:

use Jenssegers\Mongodb\Model;

class Alert extends Model
{
.. 
..
}

is replaced by:

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Alert extends Eloquent {
..
..
}

and the User model is now:

use App\Scopes\Traits\ReportingTrait;
 use Illuminate\Auth\Authenticatable;
 use Illuminate\Auth\Passwords\CanResetPassword;
 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
 use Bican\Roles\Traits\HasRoleAndPermission;
 use Bican\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
 {
     use Authenticatable, CanResetPassword, HasRoleAndPermission, ReportingTrait;
..
..
}

There is a readme from a previous version for the jennsegers library here

I seem to have the requirements checked - including:

> php -i | grep 'Mongo'
MongoDB support => enabled
MongoDB extension version => 1.2.9
MongoDB extension stability => stable



via Chebli Mohamed

lundi 3 juillet 2017

Laravel Mail send even if cc and bcc is null

I have mail send function in laravel

public static function Compose($to,$cc,$bcc,$subject,$body)
    {

        // return $to;
        try
        {
            $data = [
                'body' => $body
            ];

            if(env('APP_ENV') == "local") 
            {
                $email["subject"] = $subject;
                $email["to"] = $to;
                $email["cc"] = $cc;
                $email["bcc"] = $bcc;
                Mail::send('email.composeMail', $data, function ($message) use ($email) {

                    $message
                        ->subject($email["subject"])
                        ->to($email["to"]);
                        ->cc($email["cc"]);
                        ->bcc($email["bcc"]);
                });
            }
            else
            {
                $email["subject"] = $subject;
                $email["to"] = $to;
                $email["cc"] = $cc;
                $email["bcc"] = $bcc;

                Mail::send('email.composeMail', $data, function ($message) use ($email) {

                    $message
                        ->subject($email["subject"])
                        ->to($email["to"]);
                        ->cc($email["cc"]);
                        ->bcc($email["bcc"]);
                });
            }
        } 
        catch (\Exception $e) 
        {
            Log::critical('Critical error occurred upon processing the transaction in Email.php -> Email class -> RevertPropertyToInbox method');
            throw new CustomErrorHandler($e->getMessage(),Constant::LogLevelCritical);
        }
    }

In many cases CC and BCC is Null. But mails aren't sent and I am getting error message

enter image description here

Here , I want to use code as it is without checking if CC or BCC is null, Is there any thing missed by me so that I can achieve what I am planning to .



via Chebli Mohamed

Laravel checkbox implementation for updating database

I've been trying to make an attendance management system in Laravel. In the attendance view,when a checkbox is checked ,the controller function is supposed to increment the appropriate database column.

I've been having some issues.Here's my code: views:

<div class="container">
<!--<div class="row">-->
    <div class="col-md-8 col-md-offset-2">
       <div class="panel panel-default">

            <div class="panel-heading">Take Attendance</div>
            <h4><center>Teacher: </center></h4>
            <div class="form-inline">

             @foreach ($second as $sec)
                            <br>
                          <div class = "form-group">

                            
                            &nbsp&nbsp&nbsp&nbsp
                            
                            </div>
                            <div class = "form-group">
                            <!---->
                            <input tabindex="1" type="checkbox" value=""  name=""  />
                            </div>
             @endforeach

             </div>
             <br>
            <form action ="report_generate&<?php echo $name ?>" method = "post" enctype = "multipart/form-data" >
            <!--<input type = "hidden" name = "_token" value = "}"/>-->
             <div class = "form-group">
             <input type="submit" value= "Submit">
            <center><a href ="/home/report&<?php echo $name ?>">Report</a></center>
             </div>
            </form>

            </div>
    </div>
</div>

@endsection

Controller(for submit button):

public function report_generate($tabu)

{

$year = DB::table('sub')->select('Year')-
>where('sub.Subject_Name','=',$tabu)->get();

$sub_id = DB::table('sub')->select('Subject_Id')-
>where('sub.Subject_Name','=',$tabu)->get();

            ob_start();
            echo $year;
            $output=ob_get_contents();
            ob_end_clean();

            if ( $output=='[{"Year":1}]')
            {

                    $req = "first";
            }
            elseif ( $output=='[{"Year":2}]')
            {

                    $req = "second";
            }
            elseif ( $output=='[{"Year":3}]')
            {

                    $req = "third";
            }
            elseif ( $output=='[{"Year":4}]')
            {

                    $req = "fourth";
            }

            $final = DB::table($req)->get();
            //dd($final);
            //$columns = Schema::getColumnListing($req);
            //dd($sub_id);
            ob_start();
            echo $sub_id;
            //dd($sub_id);
            $va=ob_get_clean();
            $va = stripslashes($va);
            $txt = rtrim($va,"}]");
            $txt = ltrim($txt,"[{Subject_Id:");
            $txt = ltrim($txt,"Subject_Id:");
            $txt = explode(":",$txt);
            $txt = str_replace('"','', $txt);
            //dd($txt[1]);

            $columns = Schema::getColumnListing($req);
            //dd($columns);
            //dd($txt);
            foreach ($columns as $col)
            {
                    //dd("Y");
                    if($col == $txt[1])
                    {
                            $got=DB::table($req)->select($col)->get();
                            //dd($got);
                            foreach($got as $g)
                                    {

                                            //want to increment that cell value

                                    }
                    }
            }
    }



via Chebli Mohamed

dimanche 2 juillet 2017

laravel artisan migrate: when table already exist goes into memory loop

I am using laravel 5.1

when i try $ php artisan migrate:install first time

I have a mysql database "quickstart" with "migrations" table in it.

When i try second time:

$ php artisan migrate:install

(it just hangs)

so i tried

$ strace php artisan migrate:install

i found the following:

.
.
.
poll([{fd=5, events=POLLIN|POLLERR|POLLHUP}], 1, 1471228928) = 1 ([{fd=5, revents=POLLIN}])
recvfrom(5, "le 'migrations' already exists", 93, MSG_DONTWAIT, NULL, NULL) = 30
brk(0x2ee0000)                          = 0x2ee0000
mmap(NULL, 401408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe96b647000
mremap(0x7fe96b647000, 401408, 405504, MREMAP_MAYMOVE) = 0x7fe96279d000
mremap(0x7fe96279d000, 405504, 409600, MREMAP_MAYMOVE) = 0x7fe96b645000
mremap(0x7fe96b645000, 409600, 413696, MREMAP_MAYMOVE) = 0x7fe96279b000
mremap(0x7fe96279b000, 413696, 417792, MREMAP_MAYMOVE) = 0x7fe96b643000
mremap(0x7fe96b643000, 417792, 421888, MREMAP_MAYMOVE) = 0x7fe962799000
mremap(0x7fe962799000, 421888, 425984, MREMAP_MAYMOVE) = 0x7fe96b641000
mremap(0x7fe96b641000, 425984, 430080, MREMAP_MAYMOVE) = 0x7fe962797000
mremap(0x7fe962797000, 430080, 434176, MREMAP_MAYMOVE) = 0x7fe96b63f000

.
.
.

Instead of going into some memory loop and hang why its not showing the message that the table already exists.



via Chebli Mohamed

samedi 1 juillet 2017

Update laravel 5.0 to 5.1 on a server with php below 7

I am running a laravel 5.0 app and I am planning to upgrade to 5.1 to gradually get to 5.4, I'm using an Arvixe server with SSH, CPanel and WHM access I know 5.1 needs PHP 5.6.30 to run and right now my application is running with PHP 7.0 but in order to do it I had to change in Cpanel the php selector to PHP 7 because by default PHP 5.4 was in place and now when I try to update my app is telling me that php version is below requirements I even try to install laravel 5.1 from 0 and I am getting the same error, is that and indication that my server has only PHP 5.4 and is so how I was able to change the PHP selector to 7?

what I can do to update my app?



via Chebli Mohamed