mercredi 30 novembre 2016

Laravel shows entire php code as web page

I hosted laravel 5 on remote server and I did basic configuration and remove the Internal Server Error issue using virtual host. I have updated server' apache conf file by adding following rules.

<Directory "/var/www/server/data/www/http://ift.tt/2gN9r2u">
Allowoverride All
</Directory>

<Directory "/var/www/server/data/www/example.com/laravel">
Allowoverride All
</Directory>

After that it removes Internal Server Error issue. But now the index web page shows entire php code as a webpage. .htaccess file in public directory as follows.

AddHandler application/x-httpd-php56 .php .php5 .php4 .php3
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    #RewriteBase /

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

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

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

And storage directory have full 777 permission. Where is the problem?



via Chebli Mohamed

How to pass multi array to composer laravel

I'm trying to pass 2 arrays to a base view in laravel but I can't find the way to figure it out. It works well with 1 array, but can't with 2 arrays. I have a sidebar for a commercer website, which will display list of catetogories and list of shops. I use composer to handle it as a base view, but I can't pass 2 arrays of categories and shops. This is my composer class:

class SidebarComposer
{

    public function compose(View $view)
    {
        $categories = array();
        $categories[0] = "Cate 1";
        $categories[1] = "Cate 2";
        $categories[2] = "Cate 3";
        $categories[3] = "Cate 4";
        $categories[4] = "Cate 5";
        $categories[5] = "Cate 6";

        $shops = array();
        $shops[0] = "Shop 0";
        $shops[1] = "shops 1"

        $view->with('categories',$categories)->with('shops',$shops);
    }
}

Here is my view (sidebar.blade.php)

@for ($i = 0; $i < count($categories); $i++)
    <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title"><a href=""></a></h4>
    </div>
</div>
@endfor
@for ($i = 0; $i < count($shops); $i++)
            <li><a href=""> <span class="pull-right"></span></a></li>
@endfor

I have no experiences with laravel. Please help me, thanks very much.



via Chebli Mohamed

How do you match data stored in pivots? Laravel 5.3

Let's say I have an agency and a user and I want to match the currently logged in user against agencies on age. I might write something like this:

$agematch = Agency::where('Age', 'like', Auth::user()->Age)->get();

But let's say most information like Work_Preferences is stored in pivot tables. Both users and agencies access the same Work_Preferences information, however they each have a unique pivot table set up to link to Work_Preferences. How might I perform a match query on that?

Edit: The relationships we're talking about here look something like this.

Users and Agencies are both separate tables looking after separate data. Users do not belong to Agencies and Agencies do not belong to Users. We're here to match them.

So data is similar. An agency for instance will say they want users with x preferences. There's quite a number of these, but structurally they're the same. It looks something like this.

Work_Preferences table:

id | Subcategory | Description

There's an intermediary table (the pivot table) between Work_Preferences and Users, and another one between Agencies and Work_Preferences. These tables store the ids of users, agencies and their work preferences with foreign keys pointing to their respective parents.

It's, to the best of my knowledge, a pretty normal many to many association. You know the deal. But to summarise.

Users -- user_workpreferences -- Work_Preferences

Agencies -- agency_workpreferences -- Work_Preferences

I'm still very new to this, so please forgive the egregious formatting, I'm learning as quick as I can.



via Chebli Mohamed

Laravel Intersection of Model Data

I have Article and Tag models with corresponding functions in each files:

Article.php:

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

Tag.php:

public function articles()
    {
        return $this->belongsToMany('App\Article');
    }

On Blade view, I can access articles with a corresponding tag by calling

@foreach($tag->articles as $article)
   ...
@endforeach

From above, I can access a number of articles for a single tag. How can we filter articles with multiple tags, say only articles which have both tag1 and tag2 in a Tag model?



via Chebli Mohamed

How to store a relationship between a file and a model in Larave?

I have the below controller. I need to save the Document Model with the Employee_id relationship. I have the relationship set correctly but I a, having SQL error where it says employee_id cannot be null, foreign key violation.

So I think I have to find a way for the controller to recognise the currently loaded id for the employee profile view then save the document model. The upload works fine. It's writing to the DB part that I need help. Code here....

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();  
    $filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename 
     $destinationPath = config('app.fileDestinationPath').'/'.$filename;
        $uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
        if($uploaded){

            $employee = Employee::find($id); 

            EmpDocuments::create([
                'employee_id' => $employee,
                'name' => $filename
            ]);
        }    
        return redirect('employees');
}



via Chebli Mohamed

Please i need help on the laravel exception below

ErrorException in Manager.php line 137: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Session\Store' does not have a method '_token' (View: /home/socialclimber/Downloads/blog/resources/views/welcome.blade.php)



via Chebli Mohamed

laravel image validation sometimes works

I have a simple validation rule, to just require a photo being uploaded yet, some images go through no problem, and some of them tell me, 'image required'.

Am I missing something in my code? what would let some get through and some not?

// getting all of the post data
$file = array('image' => Input::file('image'));

// setting up rules
rules = array('image' => 'required',); 



via Chebli Mohamed

Laravel - Get data last 24 hours, 1 week or 1 month

So I'm trying to grab only data which are in last 24 hours, 1 week, 1 month. I have working code, but if I get it correctly it's "other way". By that I mean, If date is at the moment 30-Nov-2016 and I set the Data value to 1-Dec-2016, then the 24 Hour one still grabs the information, but it shouldn't. If date is 30-Nov-2016 and I set it to 28-Nov-2016, then the 24 Hour one doesn't grab it. For me It sounds like it's backwards. I hope the explanation is understandable.

$getItemsOneDay = Deposit::where('steam_user_id',0)->where('status', Deposit::STATUS_ACTIVE)->where('created_at', '>', Carbon::now()->subMinutes(1440))->get();
$getItemsOneWeek = Deposit::where('steam_user_id',0)->where('status', Deposit::STATUS_ACTIVE)->where('created_at', '>', Carbon::now()->subMinutes(10080))->get();
$getItemsOneMonth = Deposit::where('steam_user_id',0)->where('status', Deposit::STATUS_ACTIVE)->where('created_at', '>', Carbon::now()->subMinutes(43200))->get();



via Chebli Mohamed

laravel js best practice

I'm writing a Laravel 5.3 app using it's default layout, and I'm wondering which is the best practice for adding an external js library.

Should I have to put the js file directly in public/js, or there is another cleaner way to do it?



via Chebli Mohamed

How to get all articles that they dont have priority?

With this i get an array of articles :

 $unsortedArticles = $this->article->getAllCurentTranslation($language);

I have this relationship between article and priority:

public function priority()
    {
      return $this->hasOne('App\Models\HomepagePriority','article_id','id');
    }

So how can i now return an array of articles but just articles that they dont have priority??



via Chebli Mohamed

What's the best practice to send out bulk emails in Laravel 5.3?

I'm expecting about 200 - 400 emails to be sent every 2 - 3 weeks in one go. This is based on the event and the event being a project published on the website. So once it is published, an automatic email goes out to all the subscribers. I'm using Laravel 5.3 and the new notifications API.

So the code at the moment simply looks like this

$subscribers->each(function($subscriber) use($project) {
   $subscriber->notify(new ProjectPublished($project));
});

Would it make sense to implement ShouldQueue in this scenario?



via Chebli Mohamed

Call to a member function where() on array laravel 5.0.35

I`m use

    public function getImages($array_symbols_id){

    $array_images  = DB::table('photo')
        ->whereIn('photo_symbol_id', $array_symbols_id)
        ->where('photo_moderation_id','2')
        ->orderByRaw('RAND()')
        ->get(['photo_id', 'photo_src', 'photo_symbol_id']);

then try

        $array = array();

    foreach ($array_symbols_id as $id) {
        $array[] = $array_images->where('photo_symbol_id', $id)->first()->photo_src;
    }

but i have exception Call to a member function where() on array.

Why DB::table returns an array but not a collection?

laravel v5.0.35



via Chebli Mohamed

When trying file download it shows error route not found

This is in my blade file

{!! Html::link(storage_path().'/documents/'.$file->name, $file->name) !!}

This is controller

public function download($file_name){
    $file_path = storage_path('documents').'/'.$file_name;
    return response()->download($file_path);
}

Route

Route::get('documents/{file}','FilesController@download');



via Chebli Mohamed

Catching a query exception?

I have a slug column in my database, it's unique.

If I try and store another row with a non unique slug I get a QueryException error.

I catch the error, and hope to return an error message something along the lines that "slug exists".

try {
    User::create($data);
} catch (\Illuminate\Database\QueryException $e) {
    //return the error
}

The above is fine, but I'm just wondering, what if another QueryException is thrown, not to do with the duplicate slug and i return a duplicate slug error message incorrectly.

Is there a way to find out what the query exception was and return an error message based on this? i know the exception provides its own message but I was hoping for something a little more user friendly.



via Chebli Mohamed

Laravel 5.2 appear weird : Method [validateNickName] does not exist

Version:Laravel 5.2

issue:

BadMethodCallException in Validator.php line 3295:
Method [validateNickName] does not exist.
in Validator.php line 3295
at Validator->__call('validateNickName', array('nick_name', 'chenmin', array(), object(Validator))) in Validator.php line 485
at Validator->validateNickName('nick_name', 'chenmin', array(), object(Validator)) in Validator.php line 485
at Validator->validate('nick_name', 'nick_name') in Validator.php line 425
at Validator->passes() in Validator.php line 450
at Validator->fails() in ValidatesRequests.php line 53
at Controller->validate(object(Request), array('nick_name' => 'required|nick_name|unique:users|max:30', 'cellphone' => 'required|cellphone|unique:users|numeric|phone_number|size:11', 'captcha' => 'required|numeric|size:6', 'password' => 'required|min:6|max:30')) in UserController.php line 19
at UserController->postSignUp(object(Request))
at call_user_func_array(array(object(UserController), 'postSignUp'), array(object(Request))) in Controller.php line 80
at Controller->callAction('postSignUp', array(object(Request))) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(UserController), object(Route), 'postSignUp') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(UserController), object(Route), object(Request), 'postSignUp') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\UserController', 'postSignUp') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

source code:

namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{   
    public function postSignUp(Request $request)
    {
        $this->validate($request, [
                'nick_name' => 'required|nick_name|unique:users|max:30',
                'cellphone' => 'required|cellphone|unique:users|numeric|phone_number|size:11',
                'captcha'   => 'required|numeric|size:6',           
                'password'  => 'required|min:6|max:30'

        ]);
.......

when I test the input from ,met a weird issue:BadMethodCallException in Validator.php line 3295:Method [validateNickName] does not exist.

who can help me to solve it ?thanks a lot!



via Chebli Mohamed

how to add permission model to another model in Laravel

I need add permission model id $permission->id to the this form

<form class="form-vertical" role="form" method="post" action="">

but I have this form in collaborator model

@if($collaborators) // collaborator
           @foreach( $collaborators as $collaborator)
                <div>
                    <div>
                        <span>
                            <img src="" />
                             
                             

                        </span>
                    </div>
                    <button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
                      data-action="/projects//collaborators/"
                      data-token="">
                    <i class="fa fa-trash-o"></i>
                    </button>

                    <!-- permission start -->

                    <form class="form-vertical" role="form" method="post" action="">
                        <!--<div id="cid" name="cid"></div>-->
                    <input type="hidden" id="cid" name="cid" value="" />
                    <div class="form-group">
                    <label for="status" class="control-label">Choose Permission</label>
                    <select name="status" id="status">
                    <option value="">Choose a status</option>
                    <option value="3">View Only</option>
                    <option value="2">Edit Tasks</option>
                    <option value="1">Admin</option>
                    </select>
                    @if ($errors->has('status'))
                    <span class="help-block"></span>
                    @endif
                    </div>
                      <div class="form-group">
                        <button type="submit" class="btn btn-default">Create</button>
                      </div>
                      <input type="hidden" name="_token" value=""> 

I need form action this form with $permission->id

how can do it?



via Chebli Mohamed

Laravel MassAssignmentException from firstOrNew by id

I am attempting to save data using Laravel's firstOrNew method, which is producing a MassAssignmentException error.

I don't understand why the firstOrNew method should trigger a mass assignment exception since it is merely looking at the database, not attempting to save anything. From the docs:

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database.

Why then, should my code be throwing a MAE:

$tour = Tour::firstOrNew(array('id' => $this->request['id']));

As I understand, all that the above code is saying is basically "look and see if there is a row in the database with that ID, if so then return the row, if not, then create a new object with the relevant properties". It isn't saving any data so what is the problem? Thanks.

Note that the error only occurs if the row doesn't exist.



via Chebli Mohamed

Use Laravel Collection to get duplicate values

I don´t remove this duplicate values, I want get the articles_id duplicates and sum hers quantities values, por example, this is my collection:

Collection {#306 ▼
  #items: array:3 [▼
    0 => CartLine {#294 ▼
      +quantity: 2
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
    }
    1 => CartLine {#296 ▼
      +parent_line_id: null
      +quantity: 1
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
    }
    2 => CartLine {#298 ▼
      +quantity: 1
      +article_id: 1378
      +article_name: "JARRA CERVEZA ALEMANA"

    }
  ]
}

And I want get this result:

Collection {#306 ▼
  #items: array:3 [▼
    0 => CartLine {#294 ▼
      +quantity: 3 //sum total quantity of the duplicates elements with same article_id
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
    }
    1 => CartLine {#296 ▼
      +parent_line_id: null
      +quantity: 3
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
    }
    2 => CartLine {#298 ▼
      +quantity: 1
      +article_id: 1378
      +article_name: "JARRA CERVEZA ALEMANA"

    }
  ]
}

I want sum the quantities of this duplicate elements and set the quantity property with the sum only in this elements.



via Chebli Mohamed

How to automatically update the timespamps of parent model when a relationship is being created or removed?

In Laravel a model that has a belongs to relationship to another, also has a <parent>_id field on its table that points to the id of the parent. When that model is being associated to another the updated_at timespamp naturally gets updated, as the value of the <parent>_id field changes.

The parent model though, the one with the has many relationship, doesn’t have any fields that change when it becomes or stops being related to a child model, so its updated_at timespamp doesn’t change.

What I want, is both the parent and the child models to automatically update their updated_at timespamps every time a relationship between the two gets created or removed. What is the proper way to achieve this?

I have already looked into the touches property, which causes the timestamp of the parent to get updated automatically when the child gets modified. But this only works when a new relationship is being created and not when an old one is being removed. And also, this will update the timestamp of the parent at the change of any field, not just of the <parent>_id and that's something that I don't actually want.



via Chebli Mohamed

Laravel 5.3 with AngularJs 2

i installed angularJs 2 along with other useful things with the following command for Laravel 5.3.

bower install angular angular-bootstrap angular-resource bootstrap moment

The laravel root have now bower_components,

Question :

  1. Where should i place the models and controllers of angular ?

  2. Is there any problem with the above command for installing angular in laravel ?



via Chebli Mohamed

laravel eloquent relation with 3 table

Hi I want query from 3 table

user:

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | Denny     |
|  2 | Agus      |
|  3 | Dini      |
|  4 | Angel     |
+----+-----------+

History_Education

+----+-----------+-------------+
| id |   userId  | educationId |
+----+-----------+-------------+
|  1 |  1        | 1           |
|  2 |  1        | 2           |
|  3 |  2        | 1           |
|  4 |  2        | 2           |
+----+-----------+-------------+

Education

+----+-----------+----------+
| id |   level   |   Name   |
+----+-----------+----------+
|  1 | 1         |   SD     |
|  2 | 2         |   SMP    |
|  3 | 3         |   SMA    |
|  4 | 4         |   S1     |
+----+-----------+----------+

How to query with laravel Eloquent to get the latest user education order by Level DESC expected:

+----+-----------+----------------------+
| id |   Name    |   Latest_Education   |
+----+-----------+----------------------+
|  1 | Denny     |   SMP                |
|  2 | Agus      |   SMP                |
|  3 | Dini      |    -                 |
|  4 | Angel     |    -                 |
+----+-----------+----------------------+

In normal query: select id,name ,(select E.name from education E inner join History_eductaion HE on E.id = HE.education_id where HE.userId =U.id limit 1 order by E.level DESC )latest_education from USER U

How to translate to laravel eloquent?



via Chebli Mohamed

Delete file from S3 using Laravel app

I have a small script to delete files from S3 when an object is deleted from the database. I do this with these lines:

        $s3 = Storage::disk('s3');
        $s3->delete('property/'.$id.'.jpg');

But sometimes the file is not in S3 anymore, but when that is the case I get an error FileNotFoundException in Filesystem.php line 383. File not found at path: property/11108.jpg

And of course with an error like this, the script halts.

What is the best way to first check if the file exists and if so delete it?



via Chebli Mohamed

Transform specific fields in Laravel?

How do I Transform specific fields in Laravel?

For example:

$user = \Auth::User();
return [
    'user_id'  => $user->id,
    'articles' => $user->articles,
    'pages'    => $user->pages,
];

$user->articles will show the entries the articles table and $user->pages from the pages table.

In the User model, it would be defined something like that:

public function articles()
{
    return $this->hasMany(Article::class);
}

I do not want to return all the fields from $user->articles, just id, name, and description. What is good way to transform this collection?



via Chebli Mohamed

Laravel Mail: how to send batch emails per specific domain

I am building a newsletter management system using Laravel 5.2.45 which allows the ability for users to send mass emails to mailing lists. As of the moment my example mailing list contains thousands of different email addresses with different email providers such as '@gmail.com', '@hotmail.co.uk'... etc.

When the system is in use, newsletters could potentially be sent to 1000's upon 1000's of different emails, which brings me to ask these few questions.

1) Based on research I believe that it is ideal to minimize the number of connections Laravel opens and closes when sending emails. Meaning, to order the provider domains and send them in batches, so sending all '@gmail.com' in one go so only one connection is open and closed to the gmail server. Is this accurate?

2) If question one is accurate, what would be the best route of doing this using Laravel mail (if the native Laravel mail has the capability of doing so)? I am aware of the ability to use Laravel mail's queue functionality but I am unsure if this would make sure only one connection was open and closed per domain type.

3) Additionally, is the any negative impact of using the Laravel mail class to send newsletters that could potentially go to 20,000 customer emails several times a day?

Thank You,

Kieren.



via Chebli Mohamed

Detect duplicate variable with Laravel Collections

I have this collections of cart ecommerce items, I want detect that items have the same article_id value:

Collection {#306 ▼
  #items: array:3 [▼
    0 => CartLine {#294 ▼
      +cart_line_id: 836473
      +cart_id: 12957798
      +parent_line_id: null
      +quantity: 2
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
      +data: ""
      +extradata: "{"original_dsn":"qF3Xxttr3B2w","tmp_dsn":"tmp_4k0k9q6usqd7pnu7d70rg0ta674zv8v4"}"
      +article_family_id: "AAAPTP"
      +article_on_line_v: 1
      +promotion_code: null
      +promotion_id: null
      +url_preview: "http://ift.tt/2fKxNsM"
      +available_modify: true
      +model: ArticleModel {#295 ▶}
      +cession: 5.34
      +cession_original: 5.34
      +pvp: 9.95
      +pvp_original: 9.95
      +pvp_discount: 0.0
      +cession_discount: 0.0
      +discount_regularization: null
      +total_cession: 10.69
      +total_cession_original: 10.68
      +total_pvp: 19.9
      +total_pvp_original: 19.9
      #_READ_ONLY: []
      #_HIDDEN_FIELDS: []
      +__WARNINGS: []
    }
    1 => CartLine {#296 ▼
      +cart_line_id: 836474
      +cart_id: 12957798
      +parent_line_id: null
      +quantity: 1
      +article_id: 1728
      +article_name: "TAZA CERAMICA"
      +data: ""
      +extradata: "{"original_dsn":"59avc306wjem","tmp_dsn":"tmp_vnr16irux3ebi6pwy0dmn7ypeqwnr376"}"
      +article_family_id: "AAAPTP"
      +article_on_line_v: 1
      +promotion_code: null
      +promotion_id: null
      +url_preview: "http://ift.tt/2gEOfzx"
      +available_modify: true
      +model: ArticleModel {#297 ▶}
      +cession: 5.34
      +cession_original: 5.34
      +pvp: 9.95
      +pvp_original: 9.95
      +pvp_discount: 0.0
      +cession_discount: 0.0
      +discount_regularization: null
      +total_cession: 5.34
      +total_cession_original: 5.34
      +total_pvp: 9.95
      +total_pvp_original: 9.95
      #_READ_ONLY: []
      #_HIDDEN_FIELDS: []
      +__WARNINGS: []
    }
    2 => CartLine {#298 ▼
      +cart_line_id: 836475
      +cart_id: 12957798
      +parent_line_id: null
      +quantity: 1
      +article_id: 1378
      +article_name: "JARRA CERVEZA ALEMANA"
      +data: ""
      +extradata: "{"original_dsn":"null","tmp_dsn":"tmp_8cu2ls6q18ip6vvd7qccrsbjiebgsrzj"}"
      +article_family_id: "AAAPTP"
      +article_on_line_v: 1
      +promotion_code: null
      +promotion_id: null
      +url_preview: "http://ift.tt/2fKxtdR"
      +available_modify: true
      +model: ArticleModel {#299 ▶}
      +cession: 10.21
      +cession_original: 10.21
      +pvp: 19.0
      +pvp_original: 19.0
      +pvp_discount: 0.0
      +cession_discount: 0.0
      +discount_regularization: null
      +total_cession: 10.21
      +total_cession_original: 10.21
      +total_pvp: 19.0
      +total_pvp_original: 19.0
      #_READ_ONLY: []
      #_HIDDEN_FIELDS: []
      +__WARNINGS: []
    }
  ]
}

In this case, there are two items with same article_id value, 1728. I want get only the two items with this article_id.



via Chebli Mohamed

mardi 29 novembre 2016

Could not get the image file path from the storage folder. What am i missing?

Here is the code that saves my image inside /storage/app/public folder

$path = $request->file('question_image')->store('public');

The laravel 5.3 documentation says I have to create a symbolic link from /public/storage to /storage/app/public folder hence I did by using command

php artisan storage:link

At this point I am successful to store my images inside /storage/app/public.

Now what is understood is that I can get those files using

echo asset('storage/file_name.jpeg');

But no luck whatsoever.

Please let me know what I am missing here?



via Chebli Mohamed

Trying to get property of non-object in Laravel 5

I'm getting the ErrorException: Trying to get property of non-object

I'm trying to display all the relationship that is link using this function. The relationship is ->

-Card can have many notes, Notes only have one card. -Each notes contain only one user, User contain only one card. My code is:

Model

  1. Note

    class Note extends Model { protected $fillable = ['body'];

    public function cards()
    {
        return $this->belongsTo(Card::class);
    }
    
    public function users()
    {
        return $this->belongsTo(User::class,'id');
    }
    
    

    }

  2. User

    class User extends Authenticatable { use Notifiable;

    public function note()
    {
        return $this->belongsTo(Note::class);
    }
    
    protected $fillable = [
        'name', 'email', 'password',
    ];
    
    protected $hidden = [
        'password', 'remember_token',
    ];
    
    

    }

  3. Card

    class Card extends Model { public function notes() { return $this->hasMany(Note::class);//relationship }

    public function addNote(Note $note)
    {
        return $this->notes()->save($note);
    }
    
    

    }

Controller

  1. cardsController

    class cardsController extends Controller { public function index() { $cards = Card::all(); return view('cards.index',compact('cards')); }

    public function show(Card $card)
    {
        $card->load('notes.user'); **The Error is here.**
        $return $card;
        return view('cards.show',compact('card'));
    
    
    }
    
    

    }

  2. notesController

    class notesController extends Controller {

    public function store(Request $request, Card $card)
    {
        $card->addNote(
                new Note($request->all())
            ); 
    
        return back();
    }
    
    public function edit(Note $note)
    {
        return view('notes.edit',compact('note'));
    }
    
    public function update(Request $request, Note $note)
    {
        $note -> update($request -> all());
    
        return back();
    }
    
    

    }

DB

1. notes table

$card->load('notes.user'); -when i just put (notes) in the cardControllers function, it will appear all data that link from card and notes table. -but when i try to add (notes.user) it said that trying to get non property obejct. Am i missing something?



via Chebli Mohamed

Laravel Carbon: Why is now() exactly 1 day ahead?

I am using this in a seeder:

'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),

And am getting the correct date/time, but it is exactly 1 day ahead.

I have tried:

Carbon::now(new DateTimeZone('America/Chicago')),

In my seeder files, and it seems to work. However, when I am inserting records from a controller, the date is incorrect.

I am using $table->timestamps(); to create the columns - is there a configuration setting that I can enter the correct time zone? Or, is there something else I am doing wrong?



via Chebli Mohamed

Laravel google maps hiding circle on checkbox

i'm trying to hide and show circle depends on color/index by pressing checkbox. I did form but i dont know what next. Any suggestions ?

Circle configuration :

var mark = new google.maps.Circle({
  map: map,
  center : markerLatlng,
  radius : radius,
  strokeColor:  color,
  strokeWeight: 1,
  strokeOpacity:  1,
  fillColor:    color,
  fillOpacity:  1,
  zIndex: index,
  clickable:true,
});

Form:

  {!! Form::open(['route' => 'map.index' , 'method' =>'GET' ])!!}
    <div class="form-inline">
      {!!Form::label('Very good: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('very_good','value',false,['class' => 'form-control'])!!}
      {!!Form::label('Good: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('good', 'value',false,['class' => 'form-control'])!!}
      {!!Form::label('Moderate: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('moderate', 'value',false,['class' => 'form-control'])!!}
      {!!Form::label('Sufficient: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('sufficient', 'value',false,['class' => 'form-control'])!!}
      {!!Form::label('Bad: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('bad', 'value',false,['class' => 'form-control'])!!}
      {!!Form::label('Very bad: ','', ['class' => 'navbar-form'])!!}
      {!!Form::checkbox('very_bad', 'value',false,['class' => 'form-control'])!!}
    </div>
  </div>
  {!!Form::close()!!}



via Chebli Mohamed

Enforcing one to one relationships in Laravel

I am creating an app in Laravel 5.

The app I'm creating is a recruitment site where a candidate must fill many forms. Because there are many fields, I decided to logically partition the users into many tables with one-to-one relationships.

For example:

users

  • id
  • role (e.g. admin or candidate)
  • first_name
  • surname
  • DOB

driving_licences

  • id
  • user_id (FK to users)
  • has_licence
  • number_of_points
  • licence_number

In the above simple case, the users has a one-to-one relationship to driving_licences. In other words, every User MUST have a single corresponding DrivingLicence row.

Creating the above table and corresponding Eloquent models is simple enough. However I am struggling as to the best approach to enforce that every user (or every user who is a candidate) has a corresponding DrivingLicence.

The solution I have currently is, whenever I use something from DrivingLicence I first check if the relationship exists and create it if it doesn't like so:

if ($user->drivingLicence === null) {
    $drivingLicence = new DrivingLicence();
    $drivingLicence->user_id = $user->id;
    $drivingLicence->save();
}

This has to be done every time I need to do something with DrivingLicence, which of course creates a LOT of repetition.

Therefore, my question is, how can I enforce that a one to one relationship exists between users and driving_licences.



via Chebli Mohamed

Laravel Blade @includeIfElse?

Is there an @includeIfElse directive available with Laravel Blade?

Basically I would like to include another template if it exists, otherwise include another template.

Does this functionality exist? How would I accomplish this?



via Chebli Mohamed

Laravel response()->view() 500 Error

This pushes a 500 error (that isn't handled by Laravel BTW):

return View::make('view-path-and-name');

and this:

return response()->view('view-path-and-name');

and this:

return view('view-path-and-name');

I only get this error on our production server (AWS). The code runs fine on our local machines. Also, can't find where this error is logged on AWS. Checked all the usual places: storage/logs also /var/log/.

Looks like there's something wrong with the Laravel install... but can't imagine how that might have happened. Everything was working fine until this morning and no one touched Laravel's code.

Help.



via Chebli Mohamed

Why does Eloquent (in Laravel) cast my varchar uuid primary key to an integer resulting in errors?

Following up on my last night's question, I had a good night of sleep and "discovered" that this happens due to automatic casting / type conversion or whatever.

To summerize:

  • Models use uuidas primary key
  • They get them by a trigger on insert from mySQL
  • To get the uuid generated by the database runtime I call $model_object->fresh(); fresh()
  • This works when getting the object as a whole, but not when selecting just an attribute

Model

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Address extends Model {

    protected $table = 'Addresses';
    protected $fillable = ['uuid', 'zipCode', 'houseNumber'];
    protected $primaryKey = 'uuid';
    //public $incrementing = false;
}

Controller (where it screws up)

public function store(Request $request) {
    $input = $request->all();
    $address = Address::create($input);
    var_dump($address); exit;

//result (as expected)

    $address = $address->fresh();
    var_dump($address); exit;

//result (as expected)

var_dump($address->uuid); exit;//result (wow): int(0)
}



via Chebli Mohamed

Laravel 5.3 Passing AuthorizationException a message when a Policy fails

I'm trying to find a clean way to override the AuthorizationException to take a dynamic string that can be passed back when a policy fails.

Things I know I can do are:

1) Wrap the policy in the controller with a try-catch, then rethrow a custom exception that takes a specific string, which seems a bit verbose 2) abort(403, '...') in the policy prior to returning, which seems a hacky since policies are already doing the work

and then in /Exceptions/Handler::render I can send back the response as JSON

Is there a nicer way to do this to get a message in the response of a policy failure?



via Chebli Mohamed

strange laravel query builder behaviour with dashes

This:

$stockCodes = \DB::connection('sage_accounts')
->table('sales_order_items')
->select('stock_code')
->from('sales_order_items')
->orderBy('stock_code')
->distinct()->get();

returns any stock code with an RDxxx-xx-H7-xx stock code format, but that's the incorrect format. The correct format is RDxxx-Hx-xx-xx. That query doesn’t return stock codes in that format. Take, for example sales order line item 11649, which has stock code RD0448-H7-09-28. It is not returned with the rest of the stock codes, and this:

$stockCodes = \DB::connection('sage_accounts')
->table('sales_order_items')
->select('stock_code')
->from('sales_order_items')
->where('id', 11649)
->orderBy('stock_code')
->distinct()->get();

Returns an empty data set. While this:

select distinct `stock_code` from `sales_order_items` 
where `id` = 11649 order by `stock_code` asc

returns the correct data

Why will query builder not return items where the stock code is in format RDBxxxx-Hxx ?



via Chebli Mohamed

How to changed default path '/public' name in Laravel

my server using cPanel. directory structure here

  • laravel-project
  • public_ftp
  • public_html
    • public
      • index.php

I deployed on the server following this guy http://ift.tt/2bIn4Bs

everything well but my base path is "mydomain.com/public" I don't want to remove /public out from my path but to change it, I want path like this "mydomain.com/noticed"

I using laravel version 5.3

Any Idea? Thank You



via Chebli Mohamed

Laravel 5 helper to convert class name to dot case?

Is there a helper to convert this:

\App\Models\MyModel

to this:

app.models.my_model

I have written my own helper for this, but it seems like a very common thing for the Laravel framework, so I thought I may be missing the built-in version.



via Chebli Mohamed

Method refactoring?

In the TokenRepository you can see 3 similar methods. It create new entry to the tokens table but each method has different fields.

How can I refactor this? Should I merge 3 methods into 1 method or should I use strategy pattern?

TokenRepository Class:

class TokenRepository
{
   public function createTokenDigitalOcean(User $user, $name, $accessToken, $refreshToken = null)
   {
        return $user->tokens()->create([
            'name'          => $name,
            'provider'      => 'digital_ocean',
            'access_token'  => $accessToken,
            'refresh_token' => $refreshToken,
        ]);
    }

    public function createTokenLinode(User $user, $name, $key)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'linode',
            'linode_key' => $key,
        ]);
    }

    public function createTokenAws(User $user, $name, $key, $secret)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'aws',
            'aws_key'    => $key,
            'aws_secret' => $secret,
        ]);
    }
}

I have 3 classes like DigitalOceanProvider, LinodeProvider and AwsProvider. For example of using LinodeProvider class.

class LinodeProvider 
{
  public function callback()
  {
    $this->tokenRepo->createTokenLinode($user, $name, $key);
  }
}



via Chebli Mohamed

Adding laravel CSRF token with form data

While uploading an image via wysiwyg editor I need to pass the Laravel CSRF token with the FormData(). But it seems like it fails or it does not add the csrf token using the append() method.

Here is my code:

  function uploadImage( image ) {
    var data = new FormData();
    data.append( "image", image );

    data.append( "csrfToken", Laravel.csrfToken ); // <- adding csrf token
    // Laravel.csrfToken will return the csrf token.

    console.log( data.entries() );
    $.ajax ({
      data: data,
      type: "POST",
      url: "/article/store/image",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        var image = IMAGE_PATH + url;
          $( '#editor' ).summernote( "insertImage", image );
        },
        error: function( data ) {
          console.log( data );
        }
    });
  }

Its not adding the laravel csrf token with the form data because still I am getting an error

TokenMismatchException in VerifyCsrfToken.php line 68

How to add the token with the form data?



via Chebli Mohamed

How to catch errors and best practices?

I'm performing various tasks on an eloquent model.

e.g.

Flight Repository

function store($request){

    $flight = new Flight;

    $flight->name = $request->name;

    $flight->save();
}

This method is called from a controller:

public function store(FlightRepository $flight, $request){

    $flight->store($request);

}

How should one approach potential errors? try/catch? Where should it be placed in the controller or repository? What would I catch anyway, what exception type?



via Chebli Mohamed

Laravel API with AWS

I need help in integrate AWS API gateway with luman as end point. I have working project with one web part(Laravel) and three luman project for different micro services. We are using AWS API gateway to point out to luman services. Right now we don't have any authentication on web services on luman. Anyone can have access to these if he know URL. We are planing to use oAuth2 for authentication. but i am not able to understand how it work. As we have mobile app for this project too. So my question is.

Is oAuth need to be implemented on luman project or on AWS API gateway.

In both cases how it will work. Also we are planning to move luman project to private network(no internat) which will not have public access. in that case we need to use lambda function to communicate with the private network. So how it will work in this case.

Please suggest.



via Chebli Mohamed

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel

I have two tables, one for users and one for the new items. I have reference for the id in the users table in the items table.

 public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('item_title');
            $table->timestamps();
        });

        Schema::table('items', function($table) {
             $table->foreign('user_id')->references('id')->on('users');
        });

This is my controller for adding new item

public function storeItem(Request $request){
        $user = Auth::user();

        $item = new Item([
            'user_id' => $user->id,
            'item_title' => $request->input('title'),
        ]);

        $item->save();    
    }

But when I submit the form I have this error SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (database.items, CONSTRAINTitems_user_id_foreignFOREIGN KEY (user_id) REFERENCESusers(id))

Any ideas?



via Chebli Mohamed

How to use laravel 5 and sqlserver on linux platform?

I have always been developing on linux mint using laravel 5 and mysql. This time around, the company is using sqlserver 2012. I have edited my .env file as follows:

DB_CONNECTION=sqlsrv
DB_HOST=server@domain.com
DB_DATABASE=hidden
DB_USERNAME=hidden
DB_PASSWORD=hidden

When I execute artisan migrate. I get the error [PDOException] could not find driver

I research the web and found out that there is some php_pdo_sqlserv.dll and php_sqlsrv.dll available for windows users. How can I install these dlls on XAMPP linux and continue my app development. Appreciate help. Has someone faced this problem before? How did you solve it.

Additional Info

phpinfo shows that pdo_mysql, pdo_pgsql and pdo_sqlite are all insalled. I have the following files in my linux box.

/etc/odbcinst.ini
/etc/odbc.ini
/opt/lampp/etc/freetds.conf



via Chebli Mohamed

Display tags in article based on language?

This is my relationship:

article:

  public function tags(){
        return $this->belongsToMany('App\Models\ATags', 'article_tags','article_id', 'article_tag_id');
    }

language:

  public function tags(){
        return $this->hasMany('App\Models\ATags', 'language_id');
    }

Here i get all tags for specific language. I want now to display all tags for that language for that specific article.

foreach($languages as $language){
        $tags[] = $language->tags;
      }

Any suggestion how can i do that?



via Chebli Mohamed

why do not update values in Laravel

I am going to insert and update values using My addpermission function in My Controller

public function addPermission(Request $request, $id, $permission = null) 
{
  $this->validate($request, [
    'status'   => 'required'
  ]);

  if(is_null($permission)) {
    $permission = new Permission;
    $msg = 'Permission has been added to your Collaborator successfully';
  } else {
    $permission = Permission::findOrFail($permission,['id'])->id;
    $msg = 'Permission updated successfully';
  }

  $permission->status = $request->input('status');
  $permission->project_id       = $id;
  $permission->collaborator_id =  $request->input('cid');
  $permission->save();
  return redirect()->back()->with('info', $msg);
}

My routes

Route::post('projects/{project_id}/permission', [
    'uses' => 'ProjectCollaboratorsController@addPermission',
    'as'   => 'projects.collaborators.permission',
  //  'middleware' => ['auth']
]);

data insert go successfully. but update not success when I click button to update it is insert as new record to DB.

My table name is permission and have these columns

id (autoincrement) status project_id collaborator_id

how can fix this?



via Chebli Mohamed

Facebook graph api Read objects in photos

I am developing an app where I want to access Facebook page's photo and read its object like dogs, humans, buildings, balls, cars or any other object in Photo. I review with all Graph API for page, photo but not got success. Is it possible to read Page's object via Graph API? After a long search I found this but have not find any way to implement in my laravel app. Can you please guilde me to move in right direction. Thanks



via Chebli Mohamed

Upload file in S3 using Laravel 5.3

Installation Process

I followed this tutorial to install aws Package in Laravel 5.3

My Code is below

$s3 = \App::make('aws')->createClient('s3');

$s3->putObject(array(
    'Bucket'     => 'Bucket_Name',
    'Key'        => 'AWS_ACCESS_KEY_ID',
    'SourceFile' => 'http://domainname/sample.txt',
));

I am trying a txt file with around 50 bytes contents and got below error.

A sha256 checksum could not be calculated for the provided upload body, because it was not seekable. To prevent this error you can either 1) include the ContentMD5 or ContentSHA256 parameters with your request, 2) use a seekable stream for the body, or 3) wrap the non-seekable stream in a GuzzleHttp\Psr7\CachingStream object. You should be careful though and remember that the CachingStream utilizes PHP temp streams. This means that the stream will be temporarily stored on the local disk.

Am I missing something?



via Chebli Mohamed

lundi 28 novembre 2016

table id=table - Invalid JSON response

I'm using Server side processing of DATATABLES using larvel5.3

this us my JS code

var users = $('.users-datatable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "}",
        columnDefs: [{
            targets: [0, 1, 2],
            className: 'mdl-data-table__cell--non-numeric'
        }]
    });

and this my response

{"draw":2,"recordsTotal":1,"recordsFiltered":1,"data":[["taimoor","hassan","dastisupportadmin@gmail.com"]],"input":{"draw":"2","columns":[{"data":"0","name":"","searchable":"true","orderable":"true","search":{"value":"","regex":"false"}},{"data":"1","name":"","searchable":"true","orderable":"true","search":{"value":"","regex":"false"}},{"data":"2","name":"","searchable":"true","orderable":"true","search":{"value":"","regex":"false"}}],"order":[{"column":"0","dir":"asc"}],"start":"0","length":"10","search":{"value":"","regex":"false"},"_":"1480405136776"}}

It is working fine on my local machine Ubuntu 16.04 but on server same Ubuntu 16.04 its is giving my Invalid JSON error.

Please help me



via Chebli Mohamed

Trying to get a relationship between legacy tables. - Laravel 5.3 Eloquent

I am trying to sort out a legacy system and I cannot change the field or table names.

I have a table customers and a model in a subdirectory of App\prodec\common. At the start of the model I have placed

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

class Customer extends Model
{
    protected $table = 'customers';
    protected $primaryKey = 'Reference';
    public $timestamps = false;
    protected $connection = 'common';

    public function country()
        {
            return $this->hasOne('\App\prodec\common\Country','entry','country');
        }

the Country model is

namespace App\prodec\common;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    protected $table = 'countries';
    protected $primaryKey = 'entry';
    public $timestamps = false;
    protected $connection = 'common';


public function customers()
    {
        return $this->hasMany('\App\prodec\common\Customer','entry','country');
    }
}

So customers is indexed by Reference and has a number field for the country of country, and countries is indexed by entry

I am trying to get a list of customers with their appropriate customers from a CommonController

<?php

namespace App\Http\Controllers\prodec\common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\prodec\common\Customer;

class CommonController extends Controller
{
    public function index()
        {
            return view('prodec.index');
        }

    public function customers()
        {
        $thecustomers = new Customer();
        $customers = $thecustomers->country()->get();
        return view('prodec.customers.index',['customers'=>$customers]);
    }

}

but all I get is a blank with the following in the log

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class '\App\prodec\common\Country' not found' in D:\Laravel\tdbforge\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:723



via Chebli Mohamed

Laravel : Insert data into database using Bootstrap Modal

I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?

Here is the form part in blade:

<div id="myAlert" class="modal hide">
    <div class="modal-header">
        <button data-dismiss="modal" class="close" type="button">×</button>
        <h3>Create User</h3>
    </div>
    <div class="modal-body">
        <div class="row-fluid">
            <div class="span12">
                <div class="widget-box">
                    <div class="widget-content nopadding">
                        <form action="#" method="get" id="userForm" class="form-horizontal">
                            <div class="control-group">
                                <label class="control-label">Name :</label>

                                <div class="controls">
                                    <input class="span11" placeholder="Name" type="text">
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Email :</label>

                                <div class="controls">
                                    <input class="span11" placeholder="Email" type="email">
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Password</label>

                                <div class="controls">
                                    <input class="span11" placeholder="Enter Password" type="password">
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Confirm Password</label>

                                <div class="controls">
                                    <input class="span11" placeholder="Confirm Password" type="password">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
                data-dismiss="modal" class="btn" href="#">Cancel</a>
    </div>
</div> 

Here is the Ajax Part :

 $('#userForm').on('success.form.fv', function(e) {
        e.preventDefault();

        $.ajax({
            method: 'POST',
            action:"",
            data: $form.serialize()
        });
    });  



via Chebli Mohamed

How to configure Amazon SES SMTP in PHP Laravel 5?

I have integrated Amazon SES in PHP Laravel5 project but i have troubled to send email's because i am getting this error,

Swift_TransportException in AbstractSmtpTransport.php line 383:
Expected response code 250 but got code "530", with message "530 Authentication required" 

Can anyone tell me how to configure Amazon SES..



via Chebli Mohamed

How to pass data to view returned by the route redirected to (Laravel)

The following is my situation.

I have two models with controllers containing CRUD methods.

  • Document.
  • File.

While creating a file, an already document is to be specified (selected) to which the created file will be attached to.

In the store method of my documentController after storing the newly created document I want to redirect to files/create route with the id of newly created document, so that files can be created without having to choose a document.

What I have so far

DocumentController

 $input = $request->all();
 $document = $this->documentRepository->create($input);
 return redirect(route('files.create'),array('documentID' => $document->id));

file/create.blade.php

@if( isset($documentID) )
<input type="text" name="document_id" value="" hidden="true">

@else
<div class="form-group col-sm-6">

    {!! Form::label('file_type', 'Document ID:') !!}

    <select name="document_id" class="form-control">
        @foreach( $documents as $document)
            <option value="">-</option>
        @endforeach
    </select>
</div>
@endif

How can i achive this.



via Chebli Mohamed

How to get value of id from html tag to php using Dom

I want to display the value of id using xpath but what i'm getting is only the nodeName which is h4 and the nodeValue is only empty space or none.Hope anyone could help me out how since i'm not familiar with dom.I've got this idea through research.

complete result of the echo: h4-

 <?php 
           //Value of this echo is 5 which is I want to echo inside foreach
                      echo $html='<h4 id="image-gallery-count"></h4>';

                            $doc = new DOMDocument();
                            $doc->loadHTML($html);
                            $xpath = new DOMXPath($doc);

            $result = $xpath->evaluate("//h4[@id='image-gallery-count']");
                            foreach($result as $node) {

                              echo "{$node->nodeName} - {$node->nodeValue}";

                            }

//This somewhat like $count= {$node->nodeValue}
               $c = chr(64 + $count);
               $b = chr(64 + 1);
           ?>

//here is my one line code from my script that passes the value of the id with a value of 5.

$('#image-gallery-count').text($sel.data('count'));

//If i could just get the value of this id.I will use this integer to add inside $c = chr(64 + 5);.For some reason, I want to use it to iterate the forloop to display something...

Here is the loop:

@for ($i = $b; $i <= $c; $i++)                        
    <img id="image-gallery-image-{!! $i !!}" class="img-responsive" src="">
@endfor



via Chebli Mohamed

Why does Laravel / Eloquent's fresh function return an object, but calling it's attribute return 0?

My code has an Address Model in Eloquent, it looks like this:

Noteworthy: all my models use an uuid for primary key, it is generated by a trigger in the MySQL DB. This on its own works well.

<?php namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class Address extends Model {    
        protected $table = 'Addresses';
        protected $fillable = ['uuid', 'zipCode', 'houseNumber'];
        protected $primaryKey = 'uuid';
        public $incrementing = false; //<- without this it returns 0, with it returns null
    }

In my controller I create a function to create a new Address that gets its uuid from a trigger (as mentioned above). To pass this uuid, that is also a foreign key, to my user I try to call fresh();

<?php
public function store(Request $request) {
    $input = $request->all();
    try {
        $address = Address::create($input);
        // Call fresh to also get the trigger generated uuid primaryKey
        $address = $address->fresh(); //bug!!!
        //$address = Address::query()->where('zipCode', '=', $address->zipCode)->where('houseNumber', '=', $address->houseNumber)->first(); //works, but is not as nice
    }  catch (\exception $e) {
        $response['error'] = $e->getMessage();
        return response($response, 400);
    }
}

before reloading (and getting my uuid), the $address object equals

object(App\Models\Address)#186 (23) {
  ["table":protected]=>
  string(9) "Addresses"
  ["fillable":protected]=>
  array(3) {
    [0]=>
    string(4) "uuid"
    [1]=>
    string(7) "zipCode"
    [2]=>
    string(11) "houseNumber"
  }
  ["primaryKey":protected]=>
  string(4) "uuid"
  ["incrementing"]=>
  bool(false)
  ["connection":protected]=>
  NULL
  ["keyType":protected]=>
  string(3) "int"
  ["perPage":protected]=>
  int(15)
  ["timestamps"]=>
  bool(true)
  ["attributes":protected]=>
  array(4) {
    ["zipCode"]=>
    string(6) "4651ZX"
    ["houseNumber"]=>
    string(2) "34"
    ["updated_at"]=>
    string(19) "2016-11-28 23:13:47"
    ["created_at"]=>
    string(19) "2016-11-28 23:13:47"
  }
  ["original":protected]=>
  array(4) {
    ["zipCode"]=>
    string(6) "4651ZX"
    ["houseNumber"]=>
    string(2) "34"
    ["updated_at"]=>
    string(19) "2016-11-28 23:13:47"
    ["created_at"]=>
    string(19) "2016-11-28 23:13:47"
  }
  ["relations":protected]=>
  array(0) {
  }
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["appends":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
  ["dates":protected]=>
  array(0) {
  }
  ["dateFormat":protected]=>
  NULL
  ["casts":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["with":protected]=>
  array(0) {
  }
  ["exists"]=>
  bool(true)
  ["wasRecentlyCreated"]=>
  bool(true)
}

If in my Address Model $incrementing = false; is defined, and I call $address = $address->fresh(); now the $address object equal NULL

If i omit in my Address Model $incrementing = false;, and I call $address = $address->fresh(); now the $address object equal

object(App\Models\Address)#195 (23) {
  ["table":protected]=>
  string(9) "Addresses"
  ["fillable":protected]=>
  array(3) {
    [0]=>
    string(4) "uuid"
    [1]=>
    string(7) "zipCode"
    [2]=>
    string(11) "houseNumber"
  }
  ["primaryKey":protected]=>
  string(4) "uuid"
  ["connection":protected]=>
  NULL
  ["keyType":protected]=>
  string(3) "int"
  ["perPage":protected]=>
  int(15)
  ["incrementing"]=>
  bool(true)
  ["timestamps"]=>
  bool(true)
  ["attributes":protected]=>
  array(5) {
    ["uuid"]=>
    string(36) "0e85ea0c-b5c0-11e6-9c20-002590f967ca"
    ["zipCode"]=>
    string(6) "4651ZX"
    ["houseNumber"]=>
    string(2) "34"
    ["updated_at"]=>
    string(19) "2016-11-28 23:11:56"
    ["created_at"]=>
    string(19) "2016-11-28 23:11:56"
  }
  ["original":protected]=>
  array(5) {
    ["uuid"]=>
    string(36) "0e85ea0c-b5c0-11e6-9c20-002590f967ca"
    ["zipCode"]=>
    string(6) "4651ZX"
    ["houseNumber"]=>
    string(2) "34"
    ["updated_at"]=>
    string(19) "2016-11-28 23:11:56"
    ["created_at"]=>
    string(19) "2016-11-28 23:11:56"
  }
  ["relations":protected]=>
  array(0) {
  }
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["appends":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
  ["dates":protected]=>
  array(0) {
  }
  ["dateFormat":protected]=>
  NULL
  ["casts":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["with":protected]=>
  array(0) {
  }
  ["exists"]=>
  bool(true)
  ["wasRecentlyCreated"]=>
  bool(false)
}

Which is what I want!

But as soon as I call $address['uuid'] or $address->uuid it returns int(0) (not NULL)



via Chebli Mohamed

Laravel-Excel for a Datatable and Images

What I am looking to reach is to have an excel document showing 3 columns and in the last one a list of images.

For example :

Page Title | Questions | Questions Status | Images (1,2,3)

What I've done till now is the following which is returning an empty excel !

$elements = DB::table('tour_manager')
            ->join('tours', 'tours.id', '=', 'tour_manager.tour_id')
            ->join('tour_questions', 'tour_questions.id', '=', 'tour_manager.question_id')
            ->join('tour_pages', 'tour_pages.id', '=', 'tour_questions.page_id')
            ->join('tour_manager_page_pics', 'tour_manager_page_pics.page_id', '=', 'tour_pages.id')
            ->where('tour_manager.tour_id', $tour)
            ->select('tours.status as tour_status', 'tours.pourcentConforme as pc', 'tours.id as tour_id',
                'tour_questions.title as question', 'tour_questions.id as question_id',
                'tour_manager_page_pics.imagePath1', 'tour_manager_page_pics.imagePath2', 'tour_manager_page_pics.imagePath3',
                'tour_pages.title as page', 'tour_pages.id as page_id', 'tour_manager.status as qstatus')
            ->distinct()
            ->get();

        $fcList = array();
        foreach ($elements as $c) {
            $fcList[$c->page]['questions'][$c->question] =
                $c->question_id;
            $fcList[$c->page]['status'][$c->question] =
                $c->qstatus;
            $fcList[$c->page]['images']['image1'] = $c->imagePath1;
            $fcList[$c->page]['images']['image2'] = $c->imagePath2;
            $fcList[$c->page]['images']['image3'] = $c->imagePath3;
        }

        Excel::create('Tour du Manager - Excel', function($excel) use($tour,$fcList) {
            $i =1 ;
            $j =1 ;
            $excel->sheet($tour, function ($sheet) use ($i,$j,$fcList) {
                foreach ($fcList as $c) {
                    foreach ($c as $k=>$t) {
                        foreach ($t as $m=>$o) {
                            $k = array($k);
                            $i = $i + 5;
                            $j = $j ++;
                            if ($k == "questions"){
                                $sheet->cell('A1', function ($cell) use ($o, $m) {
                                if ($o == 1) $status = "Conforme"; else $status = "Non Conforme";
                                $cell->setValue($m, $status);
                            });
                            }
                            if ($k == "images"){
                                $sheet->cell('C1', function ($cell) use ($sheet, $i) {
                                    $objDrawing = new PHPExcel_Worksheet_Drawing;
                                    $objDrawing->setPath(public_path('upload/5-20161128152607.png')); //your image path
                                    $objDrawing->setCoordinates('A' . $i);
                                    $objDrawing->setWorksheet($sheet);
                                });
                            }

                        }
                    }
                }
            });
        })->export('xls');
        redirect ('tours/'.$tour);

The 3 foreach are for accessing the right data (same foreach I used in a view and are showing the right data, I even tested those with dd() and shown right data). AFter that, the counter +5 is to give a space for images (as images are appended above a cell and not into it) so that pages (elements) are not shown one above the other.

Any help and advice are welcome !



via Chebli Mohamed

3 Methods in a repository or merge into 1 method?

I have created a TokenRepository class with 3 methods.

Those methods create an entry to same a table but each method have different fields. Is this good pattern or should I use an interface and 3 implementations or merge 3 methods into 1 method?

For example:

class TokenRepository
{

  public function createTokenDigitalOcean(User $user, $name, $accessToken, $refreshToken = null)
    {
        return $user->tokens()->create([
            'name'          => $name,
            'provider'      => 'digital_ocean',
            'access_token'  => $accessToken,
            'refresh_token' => $refreshToken,
        ]);
    }

    public function createTokenLinode(User $user, $name, $key)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'linode',
            'linode_key' => $key,
        ]);
    }

    public function createTokenAws(User $user, $name, $key, $secret)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'aws',
            'aws_key'    => $key,
            'aws_secret' => $secret,
        ]);
    }
}



via Chebli Mohamed

Allow access to different permission rules - ACL LARAVEL

The admin user can view all posts on the homepage and access the update page for each post

 $gate->before(function(User $user, $ability)
    {
        if ($user->hasAnyRoles('adm') )
            return true;
    });

This is ok

But I do not know what I am doing wrong in the policies because other users can see all posts at home page but can not access the post update page that they have created, access is denied.

Home Controller

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Post;
use Gate;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Post $post)
    {
       $posts = $post->all();
        return view('home', compact('posts'));
    }


    public function update($idPost)
    {
        $post = Post::find($idPost);


        if(Gate::denies('update-post', $post))
            abort(403);

        return view('update-post', compact('post'));
    }  

}

class AuthServiceProvider

<?php

namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Post;
use App\User;
use App\Permission;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [

    ];


    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);

        $permissions = Permission::with('roles')->get();
            foreach( $permissions as $permission)
            {
                $gate->define($permission->name, function(User $user) use ($permission){
                        return $user->hasPermission($permission);
                });
            }



        $gate->before(function(User $user, $ability)
        {
            if ($user->hasAnyRoles('adm') )
                return true;
        });

    }
}



via Chebli Mohamed

$.param() not working with file angularjs

I am new in angularjs working with file upload but it is not working giving me error

TypeError: Illegal invocation

My html code is

<form name="form" enctype="multipart/form-data" class="form-horizontal"  onkeypress="return event.keyCode != 13;" id="myform" ng-init="url =''; _token =''">
    <div class="form-group">


        <div class="col-md-6">
            <label for="name" class="control-label">*School Name:</label>
            <input  type="text" class="form-control" data-validation="required" name="school_name" ng-model="formdata.school_name"  value="<% formdata.school_name %>"  autofocus>

        </div>

        <div class="col-md-6">
            <label for="name" class="control-label">*Logo:</label>
            <input  type="file" class="form-control" data-validation="required mime size" data-validation-allowing="jpg, png, gif" data-validation-max-size="5M" name="logo" fileread="formdata.logo"  >
        </div>

    </div>
</form>

My js code is

var app = angular.module('appinit', [],function($interpolateProvider){
       $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});


app.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = changeEvent.target.files[0];
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);

app.controller('CrudController', function ($scope, $http) {

 $scope.save = function (modalstate, id) {

        var url = $scope.url;
        var method = "POST";
        var data={};
        data = $scope.formdata;

        if (!$("#myform").isValid()) {
            return false;
        } else {

            $http({
                method: method,
                url: url,
                data: $.param(data),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},

            }).success(function (response) {
            }).error(function (response) {
                alert('This is embarassing. An error has occured. Please check the log for details');
            });
        }

    }
});

I think the problem is in $.param(data) it is not processing file object. I want to make this function general it will use in all crud to save data. I am using ng-model="formdata.any_name" with all input to make it general.I will just call $scope.formdata to get all form data. It is working perfectly with my other form that is without file but problem when i use it with file. Kindly help me to solve my problem



via Chebli Mohamed

Return posts with most views in laravel 5.2

I'm working on a feature that is supposed to pull in the top 8 most viewed posts from a database. The code I'm using isn't quite returning what I need and I'm not sure why this is happening. My database row name is views. The code I'm using is below:

$most_populars = \App\Post::where('status', '=', 'PUBLISHED')->get()->sortByDesc('views');
dd($most_populars);

When I use this, I get an array of 123 posts back which is what I expect. So next I use a foreach loop to get the views like this:

foreach ($most_populars as $most_popular) {
  dd($most_popular->views);  
}

When I use the dd() inside of the foreach loop, I get the post with the most views, but I only get the first one. Why is this? Shouldn't I be seeing the view count for 123 other posts? Any help I can get is a great help =) Thanks guys.



via Chebli Mohamed

guzzle http return 504 Gateway Time-out

I try to communicate with api and it always return me 504 Gateway Time-out. I try 'get' http request in jQuery in ajax and it works fine. Here is my code:

$.ajax({
    type:'GET',
    url: 'http://example.com',
    success:function(data){
        console.log(data);
    }
});

However, the problem is when I use to call this 'get' http request from php by guzzle. I try something like this:

$this->client = new Client();

$result = $this->client->request('GET', 'http://example.com');

return $result->getStatusCode();

This doesn't work.It always return me 504 Gateway Time-out. Do you know what wrong happened? When i type url for example 'http://google.com' instead of 'http://example.com it works fine by jQuery and also by Guzzle php.



via Chebli Mohamed

How to show image from storage folder in Laravel 5.3?

I have a folder in Laravel 5.3 project located in storage and it contains image files.

How can i show image from that folder?

I have all the names with

Storage::allFiles('images');

I can't access them in the usual way due to a folder permissions and i don't want to change them. I also don't want to put the files in Public directory.

Any suggestions? Thanks in advance.



via Chebli Mohamed

How does associate work?

Im trying to get associate to work.

Relationship on User model:

public function group()
{
    return $this->belongsTo('User');
}

So I do:

$user = new User();
//save user fields
....
$user->save();

$group = Group::find(1);
$user->group()->associate($group);

A new user is inserted, but in the FK of group_id on the user table I am getting null.



via Chebli Mohamed

How to display all tags translations for article?

I have this relationships:

article:

  public function tags(){
        return $this->belongsToMany('App\Models\ATags', 'article_tags','article_id', 'article_tag_id');
    }

tags:

public function tags_trans()
    {
        return $this->hasMany('App\Models\ATagsTranslations', 'tag_id');
    }

So how can i display tags translations for that article?

I tried this but i get only last one.

foreach($tags as $tag){
          $user_tags[] = $tag->tags_trans;
        }



via Chebli Mohamed

Weird path situation in Laravel. Why is this working?

I'm working on some Laravel code in PHPStorm and I just noticed a weird path problem. Looking at the project directory

enter image description here

it's obvious the path to my models is App\Models but if you look at the code, the path is App\Http\Models. If I change the code to use App\Model, PHPStorm complains that it can't find the model, and when I run the code I get the same error.

I've looked throughout my code and this is the case everywhere.

What's going on here?



via Chebli Mohamed

Unable to access relationship Laravel HasManyThrough

I have 5 models, 2 are pivot/intermediary models.

Tenant,Landlord,Property,LandlordProperty,TenantProperty

Landlord & Tenant need to be accessible both from within the Property model and also exclusively.

Currently, I am unable to access the Landlord model from Property, it simply returns no data.

Tables:

Property table:

------------------------
|       id|   propTitle|
------------------------
|        1|  Property 1|
------------------------
|        2|  Property 2|

Landlord table:

------------------------
|       id|   firstName|
------------------------
|        1|         Bob|
------------------------
|        2|       Roger|

Tenant table:

------------------------
|       id|   firstName|
------------------------
|        1|         Ted|
------------------------
|        2|       Peter|

TenantProperty table:

-----------------------------------------------------------------
|       id|   tenant_id|   property_id|contractStart| contractEnd
-----------------------------------------------------------------
|        1|           1|             2|   01-01-1970|  01-01-1971
-----------------------------------------------------------------
|        2|           2|             1|   01-01-1970|  01-01-1971

LandlordProperty table:

-----------------------------------------------------------------
|       id| landlord_id|   property_id|contractStart| contractEnd
-----------------------------------------------------------------
|        1|           1|             1|   01-01-1970|  01-01-1970
-----------------------------------------------------------------
|        2|           2|             2|   01-01-1973|  01-01-1973

Models:

class Landlord extends TenantModel {
    public function properties(){
        return $this->hasManyThrough('App\Property', 'App\LandlordProperty',
            'property_id', 'id', 'id');
    }
}

class Tenant extends TenantModel {
    public function properties()
    {
        return $this->hasManyThrough(
            'App\Property', 'App\TenantProperty',
            'property_id', 'id', 'id');
    }
}

class Property extends TenantModel {
    public function landlords()
    {
        return $this->hasManyThrough(
            'App\Landlord', 'App\LandlordProperty',
             'landlord_id', 'id', 'landlord_id');
    }

    public function getLandlordAttribute()
    {
        return $this->landlords->first();
    }

    public function tenant()
    {
        return $this->hasManyThrough(
            'App\Tenant', 'App\TenantProperty',
             'tenant_id', 'id', 'property_id');
    }
}

class TenantProperty extends TenantModel {
    public function tenant() {
        return $this->belongsTo('App\Tenant');
    }

    public function property(){
        return $this->belongsTo('App\Property');
    }
}

class LandlordProperty extends TenantModel {
    public function property(){
        return $this->hasOne('App\Property');
    }

    public function landlord(){
        return $this->hasOne('App\Landlord');
    }
}

The following loop returns no data on $property->landlords and I am unsure why

@foreach ($properties as $property)

    <tr class="clickable-row" data-href="/property/view/">
        <td></td>
        <td></td>
        <td></td>
        <td> </td>
        @php

            echo '<pre>' . var_export($property->landlords, true) . '</pre>';
        @endphp
        <td>
        @php
            if($property->status == 1){
                echo "<b style='color: green;'>Active</b>";
            }else{
                echo "<b style='color: red;'>Disabled</b>";
            }
        @endphp
        </td>
        <td></td>
    </tr>
@endforeach



via Chebli Mohamed

Getting the value of id from html pass to php code snippet

I really hope someone can help as I'm having a tough time trying to pass the count from html attribute to php code snippets as coded below. Or is it possible to manipulate/convert to php since i need the id to get the count to be use the value inside php block.

@foreach($trans as $tran)
<tr>
 <td>{!! $tran->sponsor_id !!}</td>
 <td>{!! $tran->ship_id !!}</td>
 <th>                               
     <a class="btn" href="#" data-image-id="" data-toggle="modal" data-title="{!! $tran->tran_message !!}" 
        data-count="{!! count($tran['listImage']) !!}"
        data-target="#image-gallery"><button>View Info</button></a>
    </th>
</tr>                         
@endforeach

<script type="text/javascript">
    $(document).ready(function(){
        loadGallery(true, 'a.btn');
        function loadGallery(setIDs, setClickAttr){
            var current_image,
            selector,
            images,
            counter = 0;
            function updateGallery(selector) {
                var $sel = selector;
                images = $sel.data('count');

                current_image = $sel.data('image-id');


                $('#image-gallery-count').text($sel.data('count'));
                $('#image-gallery-caption').text($sel.data('caption'));
                $('#image-gallery-title').text($sel.data('title'));

                var b = (64 + parseInt(images.toString()));
                var a = 65;
                for (i = a; i <= b; i++) {   
                   var letter = String.fromCharCode(i);
                   $('#image-gallery-image-'+String.fromCharCode(i)).attr('src', $sel.data('image-'+String.fromCharCode(i)));
               };


               disableButtons(counter, $sel.data('image-id'));
           }

           if(setIDs == true){
            $('[data-image-id]').each(function(){
                counter++;
                $(this).attr('data-image-id',counter);
            });
        }
        $(setClickAttr).on('click',function(){
            updateGallery($(this));
        });
    }
});
</script>

//Here is the count i need to get inside php code snippet

 <h4 id="image-gallery-count"></h4>



via Chebli Mohamed

Redirect a route in Laravel 5.3

Im building an API in Laravel 5.3. In my routes/api.php file I have 3 endpoints:

Route::post('/notify/v1/notifications', 'Api\Notify\v1\NotifyApiController@notificationsPost');

Route::post('/notify/v1/alerts', 'Api\Notify\v1\NotifyApiController@alertsPost');

Route::post('/notify/v1/incidents', 'Api\Notify\v1\NotifyApiController@incidentsPost');

Several services will call these routes directly, however, when a request comes in from some services, the input data needs to be processed before it can hit these endpoints.

For example, if a request comes in from JIRA, I need to process the input before it hits these endpoints.

Im thinking that the simplest way to do this would be to have a 4th endpoint like the below:

Route::post('/notify/v1/jira', 'Api\Notify\v1\JiraFormatter@formatJiraPost');

The idea being to hit the /notify/v1/jira endpoint, have the formatJiraPost method process the input and then forward the request to /notify/v1/notifications (/alerts, /incidents) as required.

How can I have the /notify/v1/jira endpoint forward the request to the /notify/v1/notifications endpoint?

Do you see a better way to do this?



via Chebli Mohamed

Get a cookie in Laravel 5 middleware

I'm trying to retrieve a cookie from a middleware in Laravel 5.3 but it seems like $request->cookie('language') is empty. I'm guessing that it is only set after the middleware runs.

I read somewhere that I should use \Cookie::queued('language'), but it's still empty.

Is my only option using the $_COOKIE variable?



via Chebli Mohamed

PHP cant access newly created zip file

Im using Laravel 5.2 and Zipper to create ZIP archive in a fly and download it by user. I think this problem is generall not strictly related to Laravel or Zipper. Steps:

  1. User click link download_all.
  2. First php script create archive.
  3. Next the same script push created file to force user download.

Everything sounds normal but I have strange behaviour that after zip archive is created (point 2) php/server cant see this newly created file. Both filesize and file_exists on $filePath return false but file exist. I cant read file why?

When I redirect user to $filePath (instead of reading it and pushing to download) everything is okay and user get file. But why I cant access newly creatd file during "script lifetime"? $paths are correct. Tested on Windows 7 and Unix.

Any idea?

code:

public function downloadAll($id)
    {
        $sourceFilesDir   = 'upload/source/' . $id;
        $zipPath          = 'upload/source-zip/' . date('Y-m-d-H-i-s') . '.zip';

        Zipper::make($zipPath)->add($sourceFilesDir);

        $fullPath = public_path($zipPath);

        // works
        // return response()->redirectTo($zipPath);

        $headers = [
            'Content-Type: application/zip',
            'Content-Transfer-Encoding: Binary',
            'Content-Length: ' . filesize($fullPath),
        ];

        // dont works, cant see file
        return response()->download($fullPath, basename($zipPath), $headers);
    }



via Chebli Mohamed

how to get started with laravel 5's mvc structure

i have newly installed laravel 5 and now i want to know how to make it work like a "model view controller" structure. Basically where to put models, controllers and view in the file structure.



via Chebli Mohamed

Submit form after certain time interval through laravel 5.3

I am developing a time based mock test web application. I need to securely submit form after lets say 5 mins. if i do it with jquery wouldn't it be less secure?? or doing it with php/ laravel functions will make it more secure?? and if there is a way of doing it with php/laravel please guide how to do it. Thanku



via Chebli Mohamed

Laravel Model tries inserting to wrong DB Table

So, my Model is trying to insert my data to a different table than I told it to.

My Model code is as follows:

class Workplacereserve extends Model
{
    protected $table = 'workplacereserves';
    protected $fillable = ['spot', 'date', 'timefrom', 'timeto', 'client', 'cmail', 'created_at', 'updated_at'];
}

The application shows that it's trying to insert into hallreserves table, which is not to right one



via Chebli Mohamed