vendredi 2 décembre 2016

newQuery() in Laravel

Whats the difference between doing:

$model = User::newQuery();
$model->published(1);
$model->get();

And:

$model = new User;
$model = $model->published(1);
$model = $model->get();

I know with the second example you have to assign the call back to the model. But is there any difference to these?

Note, I'm not chaining as there would be some conditions between checking if it should be published or not etc.



via Chebli Mohamed

sql update sentence with sentence columns in laravel 5.3

How I can add a column in a sql parameter on laravel 5.3?

I have a table with : id,name,zipcode,nearag1. and a variable named agent

and I want a sql sentence for laravel 5.3 like this

UPDATE items set near_ag1=ABS(zipcode-$agent) traslate to laravel 5.3 Imade a sql raw sentence like this:

$Agzc1= $request2->input('Agzc1');

Item::raw("UPDATE items set near_ag1=ABS(zipcode-?)",[$Agzc1]);

this sql sentence can done without erorrs but in column near_ag1 is saving only 0 values.



via Chebli Mohamed

How to refresh bootstraps model using ajax call..?

Actually I am trying to refresh model pop-up for getting session value.which is every time different.but its not working proper.I am working on laravel fremework.

anchor link :

 <a class="btn btn-primary btn-sm btn-sm1 btn_modal"  data-backdrop="static" data-keyboard="false" data-id="@,@,@,@"   style="margin-top:0px;">

My ajax call for which is open in class call

 $(document).on("click", ".btn_modal", function () 
      { 
         var passedID=$(this).data('id');

        var string = passedID;
        var array = string.split(",");

        $('#productid').data('id', array[0]);
        $('#productname').text(array[1]);
        $('#productdescription').text(array[2]);
        $('#productprice').text(array[3]);
        $('#mainvalue').val(array[3]);
        // $("#addmodel").load(location.href + "#addmodel");


        var a = array[0];

        $.ajax({
                url: '<?= URL:: to('pdtsession') ?>',
                type: 'GET',
                async : false,
                data : {
                            'productid' : a,
                       },

                success: function(html)
                 {

                    if(html == 0)
                    {

                        $("#addmodel").modal('show');
                    }
                    else
                    {
                       alert('error');
                    }
                 },


            });


      });

controller code:

public function pdtsession(Request $request)
{ 

      session()->flush();
      $postuser1 =  $request->all();
      $request->session()->put('pdt_id',$postuser1['productid']);
      if(session()->has('pdt_id'))
      {
        return 0;
      }
      else
      {
        return 1;
      } 


}

public function destroypdt1()
{
    session()->forget('pdt_id');
    session()->flush();
    if(session()->has('pdt_id'))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}   

My model pop-up which is open on ajax success call

<div id="addmodel" class="modal fade abc123" role="dialog">


             <?php


                        if(session()->has('pdt_id'))
                        {
                            echo  $pdt_id = session()->get('pdt_id');
                        }
                        else
                        {
                                $pdt_id = "";
                        }
                ?>

</div>

but when pop-up open everytime I didn't get diffrent value which store in session though session.can someone help..?



via Chebli Mohamed

laravel pulling data from database

I'm still trying to wrap my head around whereHas() method. My case is this. I want to pull all users that belong to class

This is relations

Classes model

 public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

User model

 public function classes()
{
    return $this->belongsToMany('App\Classes')->withTimestamps();
}

controller

 $class_us = User::whereHas('classes', function ($query) {
            $query->where('class',1);
        })->get();

When I do dd($class_us) i get an empty collection



via Chebli Mohamed

With query Issue in Eloquent

I have following query which works fine and gives result for StatusType

AddOnModel::with('StatusType')->get();

But when I write below, it does not bind StatusType Records

AddOnModel
::select(\DB::Raw('A.AddOnID, A.AddOn, Count(R.AddOnID) as Total'))
->from( 'tblAddOn as A' )
->with('StatusType')
->leftjoin( 'tblrevenue as R', \DB::raw( 'R.AddOnID' ), '=', \DB::raw( 'A.AddOnID' ) )
->groupBy("A.AddOnID", "A.AddOn")->get();

The part which does not work is this one: ->with('StatusType')

Am I doing something incorrectly?

Here is the Model

class AddOnModel extends Model {

    public $table = 'tbladdon';
    public $primaryKey = 'AddOnID';
    public $timestamps = true;

    public function StatusType() {
        return $this->hasOne('\StatusTypeModel', 'StatusTypeID', 'StatusTypeID');
    }
}



via Chebli Mohamed

jeudi 1 décembre 2016

Laravel Queue Notifications

I have 2 environments, QA (1 webserver) and Prod (2 webservers behind a load balancer) that have been set up the same way using a database queue.

On QA everything works just fine.

On Production, I have some strange behaviour...Mailable works fine using the Queue but an email Notification doesn't work with the queue.

If I remove the queue from the notification, the email gets sent.

On QA, I can see both jobs being created in the jobs table. On Prod, only Mailable gets created in the jobs table.

Example with Activation Email:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class SendActivationEmail extends Notification implements ShouldQueue
{
    use Queueable;

    protected $token;

    /**
     * Create a new notification instance.
     *
     * SendActivationEmail constructor.
     * @param $token
     */
    public function __construct($token)
    {
        $this->token = $token;
        $this->onQueue('social');
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject('Activation email')
            ->greeting('xxxxxx - Hello!')
            ->line('You need to activate your email before you can start using all of our services.')
            ->action('Activate Email', route('authenticated.activate', ['token' => $this->token]))
            ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

My .env file:

QUEUE_DRIVER=database

The file config/queue.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Queue Driver
    |--------------------------------------------------------------------------
    |
    | The Laravel queue API supports a variety of back-ends via an unified
    | API, giving you convenient access to each back-end using the same
    | syntax for each one. Here you may set the default queue driver.
    |
    | Supported: "null", "sync", "database", "beanstalkd",
    |            "sqs", "iron", "redis"
    |
    */

    'default' => env('QUEUE_DRIVER', 'database'),

    /*
    |--------------------------------------------------------------------------
    | Queue Connections
    |--------------------------------------------------------------------------
    |
    | Here you may configure the connection information for each server that
    | is used by your application. A default configuration has been added
    | for each back-end shipped with Laravel. You are free to add more.
    |
    */

    'connections' => [

        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'expire' => 60,
        ],

And my Mailable that works with queue:

Mail::to($user->email)
                        ->queue(new Welcome($user));

Many thanks for your help



via Chebli Mohamed

How to make Laravel controller store file upload with a relationship

I am trying to store an uploaded file with a relationship to an Employee model. I am unable to retrieve the employee id after uploading the file to save it to the DB table as a foreign key. Routes:

Route::resource('employees', 'EmployeesController');
Route::post('documents', 'DocumentsController@createdocument')

Current error:

Trying to get property of non-object.

So I am on a URL that says http://localhost/public/employees/8 when I hit upload it redirects to http://localhost/public/documents and the file does upload but shows error when writing to DB.

Here is my code. How can I do it?

public function createdocument(Request $request, Employee $id)
{
    $file = $request->file('file');
    $allowedFileTypes = config('app.allowedFileTypes');
    $maxFileSize = config('app.maxFileSize');
    $rules = [
        'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
    ];
    $this->validate($request, $rules);


    $time = time();  // Generates a random string of 20 characters
    $filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with 
     $destinationPath = config('app.fileDestinationPath').'/'.$filename;
        $uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));

        if($uploaded){      
        $employee = Employee::find($id);            
        $empdoc = new EmpDocuments();
        $empdoc->name = $filename;
        $empdoc->employee_id = $employee->id;       
        $empdoc->save();

        }    
        return redirect('employees');
}



via Chebli Mohamed