dimanche 30 avril 2017

Laravel Route Group for Views

I have below configuration in my Laravel /routes/web.php:

Route::group(['prefix' => 'admin'], function(){
    Route::get('/', function() {
        return view('admin.login');
    });
});

If you observe, I have mentioned view('admin.login') this calls /resources/views/admin/login.blade.php. Which holds good as of now.

But for this Route group, I will have all my views inside /resources/views/admin. Thus, I do not want to use admin before every view-name.

Is there any possible parameter at Route::group level by which I can define namespace of my views, so that the Laravel searches my views in the particular directory inside /resources/views/?



via Chebli Mohamed

Search by custom properties of Spatie Activity-log in laravel

I am using ActivityLog for logging my user's activities in Laravel. This package works really well in storing all the create, update and delete activities performed by the user on various models that I have setup with this package.

But there is one issue that I am facing now. I have the ActivityLog table like below-

id | log_name | description | subject_id | subject_type | causer_id | causer_type | properties
----------------------------------------------------------------------------------------------------------------------------------------
7  | default  | created     |    4       | App\Response |   1       | App\User    |{"project_id":"22295","feature_id":"2","part_id":"1","response":"yes","user_id":1}

I need to get the results of this table filtered by project_id stored in the properties column. The package documentation says that Activity is a normal Eloquent Model so we can use all the Eloquent provided default functions to use with the Activity model. But I am not sure how to achieve this with Eloquent?

Right now, I am achieving this by the code below-

$activities = Activity::latest()->get()->filter(function($item) use($projectId) {
    $properties = $item->properties->toArray();
    if(isset($properties['attributes'])) 
        $properties = $properties['attributes'];

    return ($properties['project_id'] == $projectId);
});

The problem with my above code is that it fetches all the activities logged till date, so its loading all the Activity models which exists and then filters through based on the project_id. This will take alot of time when the size of the ActivityLog with increase to a large number, say 100,000 rows. Does anyone know a better way of fetching the filtered results based on project_id without going through all the rows manually?



via Chebli Mohamed

Laravel Passport : Users only have one token not many

Laravel Passport has a very complex system for my app cause I think for this simple app it's very complex to have OAuth client's Id, Secret & ... So I create a UserController myself to solve this complexity with these codes:

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use App\User;
use Response;

class UserController extends Controller
{
    //
    public function __construct(){
        $this->content = array();
    }
     public function login(){
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
        $user = Auth::user();
        $this->content['token'] =  $user->createToken('URL APP')->accessToken;
        $status = 200;
    }
    else{
        $this->content['error'] = "Unauthorised";
         $status = 401;
    }
     return response()->json($this->content, $status);    
    }
} 

but problem is every time user sign in get new tokens & old tokens won't expire & User with old tokens can send valid request (Its should be invalid I think).
Is there any way to config passport to users has one token or I should do it myself?



via Chebli Mohamed

AWS S3 deoloy laravel to heroku

I am trying to display static image from AWS S3 in my blade. I follow the steps mentioned in laravel documentation which is asking me to require league/flysystem-aws-s3-v2 ~1.0. I did so but I keep getting "Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead". Can anyone help me Thanks.



via Chebli Mohamed

Hola, por favor ayuda con este error,

Uncaught ReferenceError: mostrarficha is not defined at HTMLButtonElement.onclick ((index):1)



via Chebli Mohamed

Download File doesnt work

Im trying to create a download file functionality, but it doesnt work, it gives me a error of: "The file "/storage/app/candidates/cvs/3/1493594353.pdf" does not exist", but im just looking at the file, and is there.

Am i missing something?

Note: im using laravel 5.4

File structure:

storage
- app
-- candidates
---cvs
----3
-----1493594353.pdf
- public

Route:

Route::post('candidate/cv/download-cv/','CurriculumVitaeController@downloadCV');

Controller:

public function downloadCV()
    {

        $candidate = Candidate::where('user_id',Auth::user()->id)->first();
        $candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();


        $path = Storage::url('app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv);
        $headers = ['Content-Type: application/pdf'];
        $newName = 'cv-'.time().'.pdf';

        return response()->download($path, $newName, $headers);

    }



via Chebli Mohamed

October CMS: Blog Plugin - How to dynamically select category

I'm using the blogPosts component from the Rainlab Blog plugin to provide a list of posts on the front page of a website.

We need to be able to switch category on the fly.

When the filter category is entered statically the filter works fine. The question is how to set this dynamically, ideally without a page refresh

Thanks for any tips



via Chebli Mohamed

Laravel collection using map and contains

I am having problem with available key in the map collection.

The available key use contains method. It should return true if the value of product id in $unavailableProducts does not contain in $products ($value->product_id == $product->id)

What did I do wrong?

    $unavailableProducts = $this->unavailableProducts();
    $products = $this->products->all();

    $allProducts = $products->map(function ($product) use($unavailableProducts) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => $unavailableProducts['result']->contains(function ($value, $key) use ($product) {
            if ($value->product_id == $product->id) {
                return false;
            }
            return true;
        }),
    ];
});



via Chebli Mohamed

If to compare two dates using Carbon on Laravel, a date from a table and a now() instance

I'm trying to display some items from a table and I'm ordering by the time they begin, I only want to show the next three items starting from now(). Here is my controller function:

Probably the whole thing is completely wrong, but still, any help will be greatly appreciated.

  public function next(Request $request)
    {

          $eventos = Event::orderBy('start','asc');
          $eventTime = Carbon::createFromDate($eventos->start);
          $mytime = Carbon::now();

          if($eventTime > $mytime){

          $eventos = paginate(3);

          return view('evento.next',compact('eventos'));
        }

    }



via Chebli Mohamed

Laravel unique row

I have a laravel application with a database. I want to make the rows in the database unique so that if someone tries to insert anything into the database when the website is running, an error is shown. The site is about TV's. I have a condition, TV and colour column in the data table. If someone inputs another exact row, I want the application to throw an error because I get duplicate data in the table. I believe I require a query looking like this: SELECT where 'TV', 'condition', 'colour', like INPUT get () Any help would be appreciated



via Chebli Mohamed

unique between 2 columns

i need to create a validation to my table "candidate_knowledges", basically in this table it accepts to columns (candidate_id, software_id), i cannot let create user_id and software more then one. but i think my validation is wrong or im not doing it right. What im trying to say in validation is that can only exist one software_id and one candidate_id on the table, this way the candidate dont have duplicate entries.

Ex:  'software_id'         => 'required|integer|unique:candidate_knowledges,candidate_id,'.$candidate->id,



via Chebli Mohamed

Laravel error upon submitting a form: MethodNotAllowedHttpException in RouteCollection.php line 218. What could this be due to?

There is a form in my view, from where, on clicking submit, data is taken to ajax script which is supposed to invoke the controllers specified in the post routes in routes.php. The controllers are expected to process the received data and throw the result back to the view. Why is this error occurring immediately after submitting the form and things aren't working as expected>



via Chebli Mohamed

Two user models in a laravel application

I'm building a SaaS web app in Laravel 5.4 where I will have my clients and the clients will have their own customers. Is it a good idea to have two user models each for clients and their customers or a single user model with roles? In case the client is also a customer of some different client, what happens then?

Any suggestions are welcome.



via Chebli Mohamed

TimThumb like dynamic image resizing bundle for Laravel 5?

Does anyone know how to achieve famous TimThumb like dynamic image resizing in Laravel 5. Basically I want to resize and show the image from external URL while loading the page and save it in the cache for the next page load. Exactly the same what TimThumb does. I am a newbie in Laravel.



via Chebli Mohamed

Call to undefined method Illuminate\Notifications\Notification::send()

I am trying to make notification system in my project these are the steps i have done: 1-php artisan notifications:table 2-php artisan migrate 3-php artisan make:notification AddPost

in my AddPost.php file i wrote this code:

<?php

namespace App\Notifications;

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

class AddPost extends Notification
{
    use Queueable;


    protected $post;
    public function __construct(Post $post)
    {
        $this->post=$post;
    }


    public function via($notifiable)
    {
        return ['database'];
    }




    public function toArray($notifiable)
    {
        return [
            'data'=>'We have a new notification '.$this->post->title ."Added By" .auth()->user()->name
        ];
    }
}

in my controller i am trying to save the data in a table and every thing was perfect this is my code in my controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
//use App\Notifications\Compose;
use Illuminate\Notifications\Notification;
use DB;
use Route;

class PostNot extends Controller
{
    public function index(){
       $posts =DB::table('_notification')->get();
       $users =DB::table('users')->get();
       return view('pages.chat',compact('posts','users'));


    }
public function create(){

        return view('pages.chat');

    }


public function store(Request $request){
    $post=new Post();
   //dd($request->all());
   $post->title=$request->title;
   $post->description=$request->description;
   $post->view=0;

   if ($post->save())
   {  
    $user=User::all();
    Notification::send($user,new AddPost($post));
   }

   return  redirect()->route('chat');  
    }

}

everything was good until i changed this code:

$post->save();

to this :

if ($post->save())
       {  
        $user=User::all();
        Notification::send($user,new AddPost($post));

       }

it started to show an error which is: FatalThrowableError in PostNot.php line 41: Call to undefined method Illuminate\Notifications\Notification::send()

how to pass this one please?? thanks.



via Chebli Mohamed

Laravel Echo Event broadcasting fails to receive on Listener

the idea of Broadcasting in Laravel is great, but it's hard to figure out how to make this to work. Even after reading the docs multiple times, watching many tutorials.. Probably I'm just missing on little thing. Who knows it?

The following code I'm running in a Laravel 5.4 project on Homestead:

# Event
class NewNumber implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $number;

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

    public function broadcastOn()
    {
        return new Channel('pub-channel');
    }
}

# EventServiceProvider:
protected $listen = [
        'App\Events\NewNumber' => [
            'App\Listeners\DoSomeThingsWithNewNumber',
        ],
    ];

The config of broadcasting is set to Redis. I installed Laravel Echo Server and run this with laravel-echo-server start and see things in the console like [11:15:16 AM] - v7y-5DsMXHdBXcqzAAAA joined channel: pub-bingo

The following config it created:

{
    "authHost": "http://localhost",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

In the javascript, I added:

import Echo from "laravel-echo";

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

console.info(window.Echo.channel('pub-channel'));

window.Echo.channel('pub-channel')
    .listen('NewNumber', (e) => {
        console.info(e);
        alert('Something happened');
        console.log(e.number);
    });

The console in Chrome shows the .info with the information about the channel. All looks fine as far as I can see.

But what doesn't happen, i the alert nor the console.loggin in the listen method.

I have an URL that I trigger in different browser that has this inside: broadcast(new \App\Events\NewNumber(rand(1, 100));

And something the application logs something in the Laravel-logs that it's successful done when I trigger that url:

[2017-04-30 11:38:44] local.INFO: Broadcasting [App\Events\NewNumber] on channels [pub-channel] with payload:
{
    "number": 54,
    "socket": null
}  

And I have the php artisan queue:listen running also (QUEUE_DRIVER: database). But database stays empty..

I really can't figure out anymore what I'm missing.. What is missing?!...



via Chebli Mohamed

Laravel Eloquent - (where) and (where or where or where)

I'm working on a search query for my data, I want to get only the available rows which are those who have value 0 in is_temp column and if the user send me a search query i would like to search this value in other columns

this is what I have now:

$clients = Company::where('guid',$guid)->first()
        ->clients()
        ->where('is_temp',0)
        ->orderBy('name', $sort_order)
        ->skip($per_page*($page-1))
        ->take($per_page);

if($search_query != ""){
     $clients = $clients->orWhere('name','LIKE','%'.$search_query.'%')
                        ->orWhere('email','LIKE','%'.$search_query.'%')
                        ->orWhere('vat_number','LIKE','%'.$search_query.'%')
                        ->orWhere('contact_name','LIKE','%'.$search_query.'%');
}

$response = [
    'clients' => $clients->get() 
];
return response()->json($response, 200);

but when I use it this way I get also the rows that the field is_temp equal to 1 so I need to use (where) and (where or where or where...)

how do i do that?



via Chebli Mohamed

Laravel duplicate field in accessor

I have a created_at field in my table. In most cases, when I want to read something from that table, I'd like the created_at to be formatted in a readable way (f.e. "5 hours ago").

I can do that with an accessor:

public function getCreatedAtAttribute($value){
    return Carbon::parse($value)->diffForHumans();
}

But there are cases where I want the original date, which isn't possible with this solution.

Is there a way I can get both the original date and the formatted date automatically? I was thinking to create a separate accessor "getReadableCreatedAt" but I can't find a way to do it.



via Chebli Mohamed

How to implement role and permission in laravel

I need role based system in laravel , when i add user with role , each role have different permission how can i implement this role and permission for user in laravel Note: one user have multiple role and permission



via Chebli Mohamed

samedi 29 avril 2017

How to set a value at angularjs autocomplete directive?

I have a directive given below.

var app = anugular.directive('autocomplete', ['autocomplete-keys', '$window', '$timeout', function(Keys, $window, $timeout) {
        return {
            template: '<input type="text" id="mm" class="autocomplete-input" placeholder=""' +
                            'ng-class="inputClass"' +
                            'ng-model="searchTerm"' +
                            'ng-keydown="keyDown($event)"' +
                            'ng-blur="onBlur()" />' +

                        '<div class="autocomplete-options-container">' +
                            '<div class="autocomplete-options-dropdown" ng-if="showOptions">' +
                                '<div class="autocomplete-option" ng-if="!hasMatches">' +
                                    '<span style="color:red;">No Matches Found</span>' +
                                '</div>' +

                                '<ul class="autocomplete-options-list">' +
                                    '<li class="autocomplete-option" ng-class="{selected: isOptionSelected(option)}" ' +
                                        'ng-style="{width: optionWidth}"' +
                                        'ng-repeat="option in matchingOptions"' +
                                        'ng-mouseenter="onOptionHover(option)"' +
                                        'ng-mousedown="selectOption(option)"' +
                                        'ng-if="!noMatches">' +
                                        '<span></span>' +
                                    '</li>' +
                                '</ul>' +
                            '</div>' +
                        '</div>',
            restrict: 'E',
            scope: {
                options: '=',
                onSelect: '=',
                displayProperty: '@',
                inputClass: '@',
                clearInput: '@',
                placeHolder: '@'
            },
            controller: function($scope){
                $scope.searchTerm = '';
                $scope.highlightedOption = null;
                $scope.showOptions = false;
                $scope.matchingOptions = [];
                $scope.hasMatches = false;
                $scope.selectedOption = null;

                $scope.isOptionSelected = function(option) {
                    return option === $scope.highlightedOption;
                };

                $scope.processSearchTerm = function(term) {
                    // console.log('ch-ch-ch-changin');
                    if (term.length > 0) {
                        if ($scope.selectedOption) {
                            if (term != $scope.selectedOption[$scope.displayProperty]) {
                                $scope.selectedOption = null;
                            } else {
                                $scope.closeAndClear();
                                return;
                            }
                        }

                        var matchingOptions = $scope.findMatchingOptions(term);
                        $scope.matchingOptions = matchingOptions;
                        if (!$scope.matchingOptions.indexOf($scope.highlightedOption) != -1) {
                            $scope.clearHighlight();
                        }
                        $scope.hasMatches = matchingOptions.length > 0;
                        $scope.showOptions = true;
                    } else {
                        $scope.closeAndClear();
                    }
                };

                $scope.findMatchingOptions = function(term) {
                    return $scope.options.filter(function(option) {
                        var searchProperty = option[$scope.displayProperty];
                        if (searchProperty) {
                            var lowerCaseOption = searchProperty.toLowerCase();
                            var lowerCaseTerm = term.toLowerCase();
                            return lowerCaseOption.indexOf(lowerCaseTerm) != -1;
                        }
                        return false;
                    });
                };

                $scope.findExactMatchingOptions = function (term) {


                    return $scope.options.filter(function(option) {
                        var lowerCaseOption = option[$scope.displayProperty].toLowerCase();
                        var lowerCaseTerm = term.toLowerCase();
                        return lowerCaseOption == lowerCaseTerm;
                    });
                };

                $scope.keyDown = function(e) {
                    switch(e.which) {
                        case Keys.upArrow:
                            e.preventDefault();
                            if ($scope.showOptions) {
                                $scope.highlightPrevious();
                            }
                            break;
                        case Keys.downArrow:
                            e.preventDefault();
                            if ($scope.showOptions) {
                                $scope.highlightNext();
                            } else {
                                $scope.showOptions = true;
                                if ($scope.selectedOption) {
                                    $scope.highlightedOption = $scope.selectedOption;
                                }
                            }
                            break;
                        case Keys.enter:
                            e.preventDefault();
                            if ($scope.highlightedOption) {
                                $scope.selectOption($scope.highlightedOption);
                            } else {
                                var exactMatches = $scope.findExactMatchingOptions($scope.searchTerm);
                                if (exactMatches[0]) {
                                    $scope.selectOption(exactMatches[0]);
                                }
                            }
                            break;
                        case Keys.escape:
                            $scope.closeAndClear();
                            break;
                    }
                };

                $scope.$watch('searchTerm', function (term) {

                    $scope.processSearchTerm(term);

                });

                $scope.highlightNext = function() {
                    if (!$scope.highlightedOption) {
                        $scope.highlightedOption = $scope.matchingOptions[0];
                    } else {
                        var currentIndex = $scope.currentOptionIndex();
                        var nextIndex = currentIndex + 1 == $scope.matchingOptions.length ? 0 : currentIndex + 1;
                        $scope.highlightedOption = $scope.matchingOptions[nextIndex];
                    }
                };

                $scope.highlightPrevious = function() {
                    if (!$scope.highlightedOption) {
                        $scope.highlightedOption = $scope.matchingOptions[$scope.matchingOptions.length - 1];
                    } else {
                        var currentIndex = $scope.currentOptionIndex();
                        var previousIndex = currentIndex == 0 ? $scope.matchingOptions.length - 1 : currentIndex - 1;
                        $scope.highlightedOption = $scope.matchingOptions[previousIndex];
                    }
                };

                $scope.onOptionHover = function(option) {
                    $scope.highlightedOption = option;
                };

                $scope.$on('simple-autocomplete:clearInput', function() {
                    $scope.searchTerm = '';
                });

                $scope.clearHighlight = function() {
                    $scope.highlightedOption = null;
                };

                $scope.closeAndClear = function() {
                    $scope.showOptions = false;
                    $scope.clearHighlight();
                };

                $scope.selectOption = function(option) {

                    $scope.selectedOption = option;
                    $scope.onSelect(option);

                    if ($scope.clearInput != 'False' && $scope.clearInput != 'false') {
                        $scope.searchTerm = '';
                    } else {
                        $scope.searchTerm = option[$scope.displayProperty];
                    }

                    $scope.closeAndClear();
                };

                $scope.onBlur = function() {
                    $scope.closeAndClear();
                };

                $scope.currentOptionIndex = function() {
                    return $scope.matchingOptions.indexOf($scope.highlightedOption);
                };
            },
            link: function(scope, elem, attrs) {
                scope.optionWidth = '400px';
                var inputElement = elem.children('.autocomplete-input')[0];

                scope.setOptionWidth = function() {
                    // console.log(inputElement.offsetWidth);
                    $timeout(function() {
                        var pixelWidth = inputElement.offsetWidth > 400 ? 400 : inputElement.offsetWidth - 2;
                        scope.optionWidth = pixelWidth + 'px';
                    });
                };

                angular.element(document).ready(function() {
                    scope.setOptionWidth();
                });

                angular.element($window).bind('resize', function() {
                    scope.setOptionWidth();
                });
            }
        };
    }]).factory('autocomplete-keys', function () {
        return {
            upArrow: 38,
            downArrow: 40,
            enter: 13,
            escape: 27
        };
    });

At laravel 5 view page like this:

<autocomplete options="allOrgData" ng-model="searchTerm"
                                      place-holder="Type Organization Name"
                                      on-select="onSelect"
                                      display-property="org_name"
                                      input-class="form-control"
                                      clear-input="false">
</autocomplete>

The list is loaded from:

$http.post("/api/getOrgForUserJson")
        .then(function(data){
                $scope.allOrgData = data.data;
        })

when I type and get name, this method called as selected item:

$scope.onSelect = function(selection) {
        $scope.org_id = selection.id;

    }

view page what the autocomplete does : When I type organization name, it shows drop down list of the matched organization name. Which is load from database. (pointed on image: No. 1) When I click on update button (pointed on image: No. 2), I need to set organization name to this autocomplete as selected value.



via Chebli Mohamed

Should I use Laravel's collective Form or traditional html form? Which is better?

I'm a novice in Laravel development. I'm learning about Form. But I'm not understanding why i need to learn again about Form for Laravel as i know how to use form in pure html. I'm confused about that should i use laravel's collective form or Pure Html Form? Which is better?



via Chebli Mohamed

Add funds integration in php

m trying to find any script or integration in php or laravel to make add balance to my website.

like i have 100 us in any payment gateway and i want to put on my website.

thanks Caesar.



via Chebli Mohamed

$array[]='something' analog in Laravel array session logic

I can create session array in Laravel only with defining key by hand using Session::put('items.key','1'), but I have a situation when I just need keys to be made automatically as I would use simple PHP function $items[]=value. How can I do this in Laravel session?

P.S. I have tried Session::put('items[]','1'), but it doesn't worked.



via Chebli Mohamed

socket_connect keeps failing with permission denied

I am running into the following error message:

socket_connect(): unable to connect [61]: Connection refused

The code that I am using:

$address = 'localhost';
$port = 5600;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $address, $port);

I was trying this out on a valet .dev environment with nginx so I guessed it might have to do with not having a proper development environment that supports websockets but after testing I am getting the exact same on my homestead vagrant environment.

Any help with getting more verbose debugging information or a possible solution would be amazing.

All suggestions are welcome.

Cheers.



via Chebli Mohamed

remove all CSS image style but keep html attributes (width and height)

i am storing html text in the database for example:

<p><img title="dasdasd" src="storage/posts/April2017/lKZCxXpP.jpg" alt="asdasd" width="100" height="100"/></p>

and then in another page i am displaying this text as html, consider it as a post body that need to be displayed with formatting.

the problem is that i am using a template that contain a lot of styling. in the style.css i have

img {  max-width: 100%;   height: auto;   width: 100%; }

its from the template styling and i cannot change this because it will mess up all my template.

the problem

the template styling is overriding the style of the image width ="100" height="100" that is stored with the html in the database, so i need the image to use the width and height that are provided by the creator of the post and stored in the database.

i already tried

height: unset;  width: unset;

but it will revert back the image to its original size not the one provided by the post creator.

is there anything i can do beside changing all the img style of themplate?



via Chebli Mohamed

Can't redirect users to custom URL after succesful login in Laravel

I am trying to redirect the users to a custom URL after a succesful login but it doesn't work. It keeps redirecting users to this dashboard page "/". I already deployed the website to the server so I can't clear the route cache with artisan.

Laravel version is 5.3.29

App\Http\Controllers\Auth\LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/my-profile';
    protected $redirectPath = '/my-profile';

    protected function redirectTo()
    {
        return '/my-profile';
    }

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
}

App\Http\Middleware\RedirectIfAuthenticated.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check())
        {
            return redirect('/my-profile');
        }

        return $next($request);
    }
}

I have read that there might be some problems with Laravel in this post. It says that there might be some problems with this file: /vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php, but this error was fixed in Laravel version 5.3.29, but I can see that it is fixed and 'returnTo' method should work.

/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Support\Facades\Log;

trait RedirectsUsers
{
    /**
     * Get the post register / login redirect path.
     *
     * @return string
     */
    public function redirectPath()
    {
        Log::info("RedirectsUsers");
        if (method_exists($this, 'redirectTo')) {
            return $this->redirectTo();
        }

        return property_exists($this, 'redirectTo') ? $this->redirectTo : '/homeeeee';
    }
}

And my routes file:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Auth::routes();

Route::get('/', 'HomeController@index');

Route::get('/home', 'HomeController@index');

Route::get('/confirm-your-email', 'Auth\ConfirmEmailController@confirm_email');

Route::get('/confirm-email/{register_token}', 'Auth\ConfirmEmailController@index');

Route::get('/my-profile', ['as' => 'my-profile' , 'uses' => 'MyProfileController@show', 'userAlert' => null]);

Route::post('/my-profile/edit-about', 'MyProfileController@editAbout');

Route::post('/my-profile/edit-profile-picture', 'MyProfileController@editProfilePicture');

Route::get('/search/company', 'SearchController@searchCompany');

Route::get('/my-profile/add-job', 'MyProfileController@addJobPage');

Route::get('/my-profile/add-job/{id}', 'MyProfileController@addCompanyJobPage');

Route::post('/my-profile/add-a-job', 'MyProfileController@addJob');

Route::post('/my-profile/delete-job', 'MyProfileController@deleteJob');

Route::get('/users/{id}', ['as' => 'users', 'uses' => 'UserController@show']);

Route::get('/rate/user/{id}', ['as' => 'rate', 'uses' => 'RateController@showUserRate']);

Route::post('/rate/rate-user/{id}', 'RateController@rateUser');

Route::get('/invite-user-rate/{id}', 'RateController@showInviteUserToRateYou');

Route::post('/invite-rate/user/{id}', 'RateController@inviteUserToRateYou');

Route::get('/company/{id}', ['as' => 'company', 'uses' => 'CompanyController@show']);

Route::get('/rate/company/{id}', 'RateController@showCompanyRate');

Route::post('/rate/rate-company/{id}', 'RateController@rateCompany');

Route::get('/search/{page}/results/', 'SearchController@showSearchCompanies');

Route::get('/search/{page}/people/results', 'SearchController@showSearchPeople');

Route::get('/leave-a-rating/', 'SearchController@showLeaveARating');

Route::get('/invite', ['as' => 'invite', 'uses' => 'OtherAuthentificatedController@showInvite']);

Route::post('/email-invite', 'OtherAuthentificatedController@emailInvite');

Route::get('/contact', 'OtherController@showContact');

Route::post('/send-contact-email', 'OtherController@sendContact');

Route::get('/tyfcu', 'OtherController@thankYouForContactingUs');



via Chebli Mohamed

Laravel 5.4: Delete Modal Not Obtaining Object

So I have a table of people, with each column containing certain values. At the end of each row, I have a "Delete" button. When that button is pressed, a modal pops up to confirm if you want to proceed with deleting that person. Clicking the "Delete" button again should delete the person and display a success message for it.

With the modal, I'm trying to make sure not only that a user needs to accept the action before proceeding, but also making sure that only the specific person in question is deleted. However, when I try to clarify the request it only contains the CSRF token that I'm passing through. Even when I try to more deliberately inject the targeted person into the modal the person isn't being sent through.

The important snippets of my code, for reference:

@foreach($people as $person)
   <tr id="row">
       <td id="first_name_row"></td>
       <td id="last_name_row"></td>
       <td id="email_row"></td>
       <td>
         <input type="button" id="delete_button_row" class="btn btn-btn-submit delete" value="Delete" onclick="delete_modal('', )">
       </td>
   </tr>
@endforeach

..........

<!-- Modal -->
    <div class="modal fade" id="DeleteModal" role="dialog">
        <div class="modal-dialog">
            <form class="form-horizontal style-form" id="model-form" data-toggle="validator" role="form" method="post" action="/employer/delete-person">
              <!-- Modal content-->
              
              <div class="modal-content">

                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title">Delete This Person</h4>
                  </div>
                  <div class="modal-body">
                      <p>Are you sure you would like to do that?</p>
                      <input id="delete_ex">
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                      <button type="submit" id="modal-execute" class="btn btn-btn-submit">Delete</button>
                  </div>
              </div>
          </form>
        </div>
    </div>

......

<script>

  function delete_modal(num, person){
    $('#delete_button_row' + num).attr("data-toggle" , "modal");
    $('#delete_button_row' + num).attr("data-target", "#DeleteModal");
    $('#delete_ex').val(person);
  }

  .......

</script>



via Chebli Mohamed

Laravel 5 remember me not working

I am unable to get Laravel rememeber me functionality to work.

I added remember token column to my User Model table. My User Model Authenticatable. User model doesn't contain anything else specific related to remember me functionality

I am using default Auth drivers and guard.

My Usercontroller is different from default one. It extends from Controller. It doesn't use any Traits. In my login method, I use Auth::login($userModelObject, true) to login user. Everything works fine. Remember me token gets updated in database. I can see 3 cookies on browser XSRF-TOKEN, laravel_session, remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d.

Auth::check() returns true as expected but if I either remove, expires, or modify laravel_session, in the subsequent request, remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d cookie also gets removed for some reason (I am not able to view i$t using var_dump($_COOKIE) in only middleware I applied) and I think that's why Laravel Auth driver isn't able to use remember me Cookie to autologin user. CSRF middleware is also being applied automatically by Framework.

What could be causing this behaviour? Do I need to use some Additional Traits on my User Model or Controller?

Note: I am using Laravel 5.4 and my session config are:

'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 20,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'store' => null,
'lottery' => [2, 100],
'cookie' => 'laravel_session',
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', false),
'http_only' => true



via Chebli Mohamed

Laravel 5.3.31 post method returning 405 method not allowed

I am getting '405 method not allowed error' when I am going to send post reques using AngularJS http.post.

Below is my angular JS code:

var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post(this.baseUrl + '/user/authenticate-user', JSON.stringify({"email": email, "password": password}), {
            headers: headers
        }).map((response: Response) => {

            }
        });


- Below is my route in web.php
Route::post('user/authenticate-user', 'UserController@postLogin');

- I have written postLogin method in UserController controller.

Please help me if anyone face same issue.

[enter image description here][1]



via Chebli Mohamed

Order by relationship - Laravel 5

I've seen a couple of times Laravel people order by a relation like this:

Model::with(["relationship" => function($query) {
    $query->orderBy('relation_property');
}]);

I've never got this working. Although, it seams like many people is using it. Does someone having an idea why I cant get it to order the result by the relations property?



via Chebli Mohamed

Laravel 5 SQL Relations

I have some problem with query. I want to filter query by column in server table but I don't know how to do this. Need to modify this line:

$data = $video->files()->with('server')->get();

Model: server

public function files()
{
    return $this->hasMany('App\Models\File', 'id', 'server_id');
}

Model: file

public function server()
{
    return $this->belongsTo('App\Models\Server', 'server_id', 'id')->ordered();
}



via Chebli Mohamed

Laravel is great but... where's the consideration for HATEOAS?

I've begun using Laravel 5.4 instead of Spring boot for a web application I'm currently developing and it's going great. I'm really enjoying the lack of verbose boilerplate that Java/Spring has. However, one of my requirements is that the API must be HATEOAS.

I've literally searched for days for research material and only come up with a couple of not-so-popular libraries. Is there a reason for this complete lack of exposure of HATEOAS for Laravel when for other web application frameworks there's at least some material?

Edit: I'm not trying to talk down on Laravel, I just want to know why there's no resource on HATEOAS implementations with Laravel as the fraemwork.



via Chebli Mohamed

laravel 5; redirect to previous section after store or view

I think this is a basic problem or question, but i can't find any solution that solves this problem, so probably i'm searching in the wrong way or on the wrong keywords.

I have a bunch of articles in my DB, and there are a number of ways to read/edit them on the site. - The visitor can see them in a list, click on them and read the whole article - The registered users can see them in the same list, but click on them to read or edit the article - The admin can see a different list (an different view), and edit or delete them and i'm sure i will come up with some other ways to read or edit the articles or other data.

The point is, that if a visitor or user had read or edited the article, i want them to return to their own index of articles, but if an admin has read or edited the article i want him to go back to the admin-index.

So from the start i have a number of routes:

Route::get('/article'... will display the index of articles
Route::get('/article/{name}'... will display an article
Route::get('/article/{name}/edit'... will display the edit form for the article
Route::post('/article/{name}'... will update the article

And for the admin:

Route::get('/admin/article'... will display the index of article
Route::get('/admin/article/{name}'... will display an article
Route::get('/admin/article/{name}/edit'... will display the edit form for the article
Route::post('/admin/article/{name}'... will update the article

But..Route::post('/article/{name}' and Route::post('/admin/article/{name} should point to the same function to update the data, and that function should redirect to different routes, in this case Route::get('/article' and Route::get('/admin/article'

I really dont want to write 2 different routines to store or update the data in the database, that are in fact the same, except for the 'redirect'-line after updating or storing.

My first thought was to make 2 routes, with two entries in my controller that each call the same routine that saves the data, and return where i can redirect, but then i would have to use different 'actions' in my form. That would mean i would have to make 2 forms that are the same, except for the 'action'-line.

Whatever i do, i would have to redirect somewhere based on the section of my site where i was before i started to read or edit my data.

I read something about the 'back()'-function, but that won't help me because i want to be able to read an article, and then choose to edit it, then return back to my index.

I hope i was able to explain what i want to do, and i'm sure i'm not the only one looking for this, but again, i failed in finding a right solution.

What is het best way to achieve this?!?



via Chebli Mohamed

Laravel cashier "Unable to create Braintree customer" error

I am trying to create a subscription services using Laravel, Laravel Cashier and Braintree. I get the following error:

Unable to create Braintree customer: Unknown or expired payment_method_nonce.
CVV is required.
Expiration date is required.
Credit card number is required.
Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code.

I've done the following in my HTML:

<form class="form-horizontal" role="form" method="POST" action="">
    <select name="plan" id="plan" class="form-control">
        <option value="">Select plan</option>
        <option value="free">Free plan - €0/month</option>
        <option value="cool">Cool plan - €10/month</option>
        <option value="epic">Epic plan - €100/month</option>
    </select>

    <div id="dropin-container"></div>

    <input type="submit" class="btn btn-primary blue-button" value="Sign Up" style="margin-top: 6px;">

    <!-- Load the Client component. -->
    <script src="http://ift.tt/2pIgd2j"></script>

    <script>
        braintree.setup('', 'dropin', {
            container: 'dropin-container'
        });
    </script>
</form>

then I have the following RegisterController.php, the most important bit is in the create method:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/account';

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

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showRegistrationForm()
    {
        $braintreeToken = \Braintree\ClientToken::generate();

        return view('auth.register')
            ->with('braintreeToken', $braintreeToken)
            ->with('plan', 'none')
            ->with('route', 'register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param Request|\Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'plan' => 'required|in:free,cool,epic'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $limit = 200;
        $plan = 'free';

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'plan' => $plan,
            'limit' => $limit,
            'password' => bcrypt($data['password']),
        ]);

        switch($data['plan'])
        {
            case 'cool':
                $limit = 3000;
                $plan = 'cool';
                $planID = 'gt8m';
                break;
            case 'epic':
                $limit = 32000;
                $plan = 'epic';
                $planID = '8v3g';
                break;
        }

        $subscription = $user->newSubscription('main', $planID)->create($data['_token']);

        if ($subscription)
        {
            $user->plan = $plan;
            $user->limit = $limit;
            $user->save();
        }

        return $user;
    }
}

The error happens when I input the following credit card details (these are supposed to be the test credit card numbers used in the sandbox):

Credit card number: 4111 1111 1111 1111
Expiration date: 08/2018
CVV: 123

I've tried googling the error but nothing useful came up.



via Chebli Mohamed

Flashed Session Data not shown in login page

I was trying to send a flash session data to my login page. Though the login page has the View of showing message but it doesn't appear:

$name = $request->name;
return view('cart.login',['name'=>$name])->with('success',"Login First to add to cart");

And this is how I was trying to display the success :

@if ($message = Session::get('success'))
    <div class="alert alert-success">
        <p>
              
        </p>
    </div>
@endif

But the success message doesn't appear in the view. Can anyone help me to find out what could be possible error on that?



via Chebli Mohamed

Laravel 5.4 wrong login always gets 'These credentials do not match our records'

I have created Login with verification email which works find on Laravel 5.4

When I login with the correct 'email', 'password' and 'activated'(means the user approve his email). I can login successfully My problem is that when I try to login with inactivated user or wrong email or login I will always get the same error

Illuminate\Support\ViewErrorBag Object ( [bags:protected] => Array ( [default] => Illuminate\Support\MessageBag Object ( [messages:protected] => Array ( [email] => Array ( [0] => These credentials do not match our records. ) ) [format:protected] => :message

How can I get more meaninful wrong login message?

ps.

I didn't provide the User Scheme since with the correct data the login is ok



via Chebli Mohamed

start_time, end_time does not match the format H:i on form data Edit

I am new to laravel and facing a problem with date_format:H:i|nullable|max:8 validation in my Controller. It is working fine first time (with new record) but showing following message

Following errors occurred:

The start time does not match the format H:i. The end time does not match the format H:i.

when Editing data in edit form. When I leave the time fields unchanged (with other fields changed or unchanged). But works fine if time fields are edited(changed).

I am using <input type="time"> in my form.

The data type is Time in MySQl table. It shows "11:59 PM" in the edit view. And when submitted it submits something like "23:59".

I have googled but found not information though a similar question on other site but without any answer.

It will be nice if you can answer my question. Thanks in advance.

Zaki



via Chebli Mohamed

Laravel multiple WHERE clauses

I have a requirement to add multiple where clauses to a Laravel SQL query.

So far my PHP code has been:

date_default_timezone_set('America/Los_Angeles');

$today = getdate();
$year = $today['year'];
$month = $today['mon'];
$day = $today['mday'];

$today_ = $day.'-'.$month.'-'.$year;
$result = DB::table('task')
    ->select('*')
    ->where(
        ['rowstate', '<>', 'Ready'],
        ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
    ->get();

But above code returns:

Column not found: 1054 Unknown column '0' in 'where clause' 
(SQL: select * from `task_tab` where (`0` = rowstate and `1` = <> and `2` = Ready))

I want to generate below SQl statement:

SELET * 
FROM task
WHERE rowstate <> 'Ready'
AND DATE_FORMAT(due_date, "%d-%m-%y") < $today



via Chebli Mohamed

Use JWT with uuid lumen

I am using jwt in luman and use primary key UUID hexadecimal. And firstly i got issues to Authenticate token by passing in header the issue was - SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from users where users.id = 0 limit 1) " but i solved it using " protected $primaryKey = 'uuid'; " put in model it fine. But after i got another issue in 'jwt->attemp' it always give my UUID '30' in numeric number when i login but when i remove the code form model it's working fine. Please help me about this issues.



via Chebli Mohamed

Html tags not being inserted in database , when using pagedown

I am using pagedown as my editor, now what i get i my database once i submit is the following:

This is what i love about 

`[A-Z]+` - One or more capitalcase ASCII caracters.

`[^A-Z]*` - We are using negated chracter class here by using the ^ sign, basically we are saying, look for any character besides the one in the [] brackets, * means zero or more times.
  | - Or

`[^A-Z]+` - Look for any character besides the one in the [] brakets, another negated character class. + means one or more times.

`g` - We add the global flag, so we get all possible matches and don't just stop at one match.

My expected output is each of those line wrapped in a separate paragraph. Also, as i am typing in the pagedowneditor and see the live update below the editor:

enter image description here

Now if i check the dev tool:

enter image description here

I can see that here the text is perfectly wrapped in separate paragraphs , but why is't the same inserted in my database ?



via Chebli Mohamed

vendredi 28 avril 2017

Laravel Paginator with post form data search with session stores

i have searching routes with get and post. First time users select search filters from home page then it submit it hit on index controller search with form data and return correct results with pagination when i click on pages it does not show any thing.

Route::post('search', 'SearchController@index');
Route::get('search', 'SearchController@index');

And i have index controller for search with post first time and with session like this.

public function index(Request $request)
    {
       if( Request::get('select_menu') !='' ){
            $conditions = array();
            $conditions['city'] = Request::get('city');
            $conditions['area'] = Request::get('area');
            $conditions['purpose'] = Request::get('status');
            $results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);
            Session::set('formDataSession', $conditions);
        }
    elseif(Session::has('formDataSession')){
            $getSession = Session::get('formDataSession');
            $conditions = array();
            $conditions['city'] = $getSession['city'];
            $conditions['area'] = $getSession['area'];
            $conditions['purpose'] = $getSession['purpose'];
            $results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);

        }
return view('search', array('page' => 'search','results'=>$results));

}



via Chebli Mohamed

How to perform security testing for my laravel 5 website?

i have completed content management system in laravel 5, i need to perform security testing for this system and also want to check my code quality for international standardization. thanks in advance.



via Chebli Mohamed

Session superglobal variable [Laravel 5.4]

I have a little problem with the Session variable in Laravel. You see,I fill the Session variable cart, in the last method, but I cannot access to the data from another method, only from the addProduct() method, I do not know what more to do, I have already read the documentation of my version and posts of third persons and nothing works for me.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Productos;
use Session;

class ShoppingCart extends Controller
{
    public function getAmount(){
        $total = 0;
        $cart = Session::get('cart');
        if($cart == null){
            foreach($cart as $product) {
                $total += Productos::find($product)->precio;
            }
        }
        return $total;
    }
    public function getProducts()
    {
        return Session::get('cart');
    }

    public function addProduct($id)
    {
        if(Session::get('cart') == null){
            $cart = [$id];
            Session::put('cart', $cart);

        }else{
            $cart = array_merge(Session::get('cart'), [$id]);
            Session::put('cart', $cart);
        }
        var_dump(Session::get('cart'));
    }
}


via Chebli Mohamed

Size limit when passing a variable to Mail:send laravel

I'm trying to pass a query result into a view, but I keep getting an error: Maximum execution time of 30 seconds exceeded I'm passing smaller objects through and its working fine, but it breaks when I pass the result of $monthlyBidStatment through. If there is a better way of doing this I'd really appreciate any advice. Thanks in advance.

public function sendEmailInvoice(Request $request)
    {
        $invoice = Invoice::where('id', '=', $request->invoiceId)->first();
        $startDate = $invoice->start_billing_date;
        $startDateSql = date("Y-m-d", strtotime($startDate));
        $endDate = $invoice->end_billing_date;
        $endDateSql = date("Y-m-d", strtotime($endDate));
        $affiliate = AffiliateDetail::where('id', '=', $invoice->affiliate_detail_id)->first();
        $monthlyBidStatment = BidTracker::where('affiliate_detail_id', '=', $affiliate->id)->whereBetween('created_at', [$startDateSql, $endDateSql])->get();

        // LOG::info(gettype($monthlyBidStatment));

        Mail::send('pdf.invoicePDF', [
            'oAffiliate' => $affiliate,
            'oInvoice' => $invoice,
            'bids' => $monthlyBidStatment,
            'showBreadcrumb' => false
        ], function ($m) use ($affiliate, $invoice, $monthlyBidStatment)
        {
            $m->from(env('APP_EMAIL'), env('APP_NAME'));
            $m->to($affiliate->info_billing_email, $affiliate->info_company_name)->subject(env('APP_NAME') . ' Invoice');
            $pdf = PDF::loadView('pdf.invoicePDF', [
                'oAffiliate' => $affiliate,
                'oInvoice' => $invoice,
                'bids' => $monthlyBidStatment,
                'showBreadcrumb' => false
            ]);

            $m->attachData($pdf->output(), 'invoice.pdf');
        });

        $request->session()->flash('message', 'Successfully sent email invoice');
        return array(
            'status' => 'ok'
        );
    }



via Chebli Mohamed

Validate Arabic Numbers in Laravel 5

I have a form that contains a field for user to enter amount value of certain payment. This field is input of type number.

The validation rule in Laravel for this input is: 'amount' => 'required|numeric'

When I enter the amount in English as: 1500 => The validation is passed and every thing is OK.

But when I enter the amount in Arabic as: ١٥٠٠ => The validation is falls with error message: "validation.numeric".

Should I validate this field manually or there is another solution to this problem?

error screenshot



via Chebli Mohamed

Authentification using laravel passport and google signin in an Android app

I Have a Restful Api built with laravel and a mobile client ( android app ) using a google sign in Button,

I Want to implemnt an authentification system with laravel passport but while using the user account provided by google signin in th Android app

Is there a clear solution or a workflow to implement this ?



via Chebli Mohamed

403 error page not rendered in my live hosting?

i am using laravel 5.3, my render function for displaying errors is:

public function render($request, Exception $e)
    {
        if($this->isHttpException($e)){
            if (view()->exists('errors.'.$e->getStatusCode()))
            {
                return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode());
            }

        }
        return parent::render($request, $e);
    }

and i have the 403, 404 and 503 errors page in errors folder..

the 404 page works...so if i entered a page is not in my site the 403 blade return ....but when i try to access some folders...and i got the default cpanel forbidden page.....so how can i display the error page for 403 error. thank you



via Chebli Mohamed

how do i remove a value from array session in laravel 5.3?

how do i remove a value from array session in laravel 5.3 ? My application to collect some customer after choice customer and put some product in badge .here everything is ok but how to move other customer ?i want to delete the old product or how to notify user to pay and move to other customer and thank you advance



via Chebli Mohamed

Laravel 5.3 Post search with session for complex search

i have a search routes like that

Route::post('search', 'SearchController@index');
Route::get('search', 'SearchController@index');

now i'm searching the result from home page form etc 6 form fields then it redirect me on the search page with result but when i click it second time on pagination page it does not work for me.i'm using session in it for remember data that i post for the home. i can search also on this page if i have session then i read second condition in my case.

Controller is below

public function index(Request $request) {

    if( Request::get('select_menu') !='' ){

                $conditions = array();
                $select_menu = Request::get('select_menu');
                $conditions['property_type'] = $select_menu;
                $city =  Request::get('city');
                $area =  Request::get('area');
                if($city != 0){
                    if($area != 0){
                        $get_area = Area::where('id', $area)->first();

                        $conditions['city'] = $get_area['city'];

                        $conditions['area'] = $get_area['area_name'];
                    }
                    else{
                        $get_city = Area::where('city_id', $city)->first();
                        $conditions['city'] = $get_city['city'];
                    }

                }
                $status =  Request::get('status');
                $ptype = Request::get('ptype');
                if($status != '0'){
                    $conditions['purpose'] = $status;
                }
                if($ptype != '0'){
                   $conditions['property_sub_type'] = $ptype;
                }

                $min_price =  Request::get('minprice');
                $max_price = Request::get('maxprice');
                if($max_price == 0){
                    $max_price = 500000000;
                }                
                $results = Property::where($conditions)->whereBetween('price', array($min_price, $max_price))->paginate(6);

                $formData = array(
                                    'city'     =>  $city,
                                    'area'     =>  $area,
                                    'status'  =>  $status,
                                    'minprice' =>  $min_price,
                                    'maxprice'  =>  $max_price,
                                    'ptype'     =>$ptype,
                                    'select_menu'=>$select_menu,
                                );
                //$results->appends(['search' => $formData]);
                Session::set('formDataSession', $formData);

            }
        elseif(Session::has('formDataSession')){

                $getSession = Session::get('formDataSession');

                $conditions = array();
                $conditions['property_type'] = $getSession['select_menu'];
                $conditions['city'] = $getSession['city'];
                $conditions['area'] = $getSession['area'];
                $conditions['purpose'] = $getSession['status'];
                $conditions['property_sub_type'] = $getSession['ptype'];
                $min_price = $getSession['minprice'];
                $max_price = $getSession['maxprice'];

                $results = Property::where($conditions)->whereBetween('price', array($min_price, $max_price))->paginate(6);
                echo $results;
                $formData = array(
                                    'city'     =>  $getSession['city'],
                                    'area'     =>  $getSession['area'],
                                    'status'  =>   $getSession['status'],
                                    'minprice' =>  $getSession['minprice'],
                                    'maxprice'  => $getSession['maxprice'],
                                    'ptype'     => $getSession['ptype'],
                                    'select_menu'=>$getSession['select_menu'],
                                );


            }
    else{
            // echo 'property else';exit;
                $formData = array(
                                    'city'     =>  0,
                                    'area'     =>  0,
                                    'status'  =>  0,
                                    'minprice' =>  0,
                                    'maxprice'  =>  0,
                                    'ptype'     =>0,
                                    'select_menu'=>'home',
                                );
                $results = Property::paginate(6);
    }    

    return view('search', array('page' => 'search','formData'=>$formData,'results'=>$results));
}



via Chebli Mohamed

Create a Second Maria DB on Forge Server for Testing?

Can someone walk me through the command line steps of booting up another Maria DB instance on a Forge Server that already has one? I am trying to have two instances with two separate credentials...one for testing and another for production.



via Chebli Mohamed

How To Build An Efficient and SEO Friendly Multilingual Architecture in Laravel

I have configured my multilingual laravel(5.4) application according the blog http://ift.tt/2oFqlIN. Now I want to show the language prefix only for the public interface of the application such as
http://ift.tt/2oTsjl6

and admin dashboard url without prefix such as

1. domain.com/dashboard,
2. http://ift.tt/2oFDuSm

So I have assigned \App\Http\Middleware\Language::class class reference
at the Http\Kernel.php within 
   protected $routeMiddleware = [
     .
     .
     .
   'lang' => \App\Http\Middleware\Language::class
   ]

and I want to filter all public routes like

Route::group(['middleware' => ['lang']], function(){
Route::get('lang/{language}', ['as' => 'lang.switch', 'uses' => 'LanguageController@switchLang']);
Route::get('/', ['as' => 'home', 'uses' => 'PostController@index']);
Route::get('/post/{slug}', ['as' => 'post.show', 'uses' => 'PostController@show']);
});

So I have configured App\RouteServiceProvider with

Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
$locale = Request::segment(1);

Route::group([
'middleware' => 'lang',
'namespace' => $this->namespace,
'prefix' => $locale
], function ($router) {
require base_path('routes/web.php');
});

Now all my public route are working with language prefix but my admin dashboard route also includes the language prefix that doesn't suppose to be
What is your suggestion to configure my app to get the acquired result.

Best Regards
Manoz



via Chebli Mohamed

can we detect phone number if opened in mobile device [duplicate]

This question already has an answer here:

I am thinking of a feature for that I have to search for necessary components and this is one of them.

For instance, I have PHP LARAVEL app and if I open it in mobile device can it detect phone number?



via Chebli Mohamed

Laravel: what's the better method to retrieve current logged user and why?

I know two method:

The first is using a Request object param in the controller's function

public function index(Request $request)
{   
    $user = $request->user();
    return view('home');
}

The second is using directly the Auth facade.

public function index()
{   
    $user = Auth::user(); 
    return view('home');
}

Are there any diferences? Are one method better that the other one and, if, yes, why?



via Chebli Mohamed

Form Error Messages Are Not Displayed Laravel 5

I'm new at Laravel and I want to Use the authentification system included in Laravel. To do so I activated authentification in my laravel projet with

php artisant make:auth

Then I tryed to log in in the my projet and everthing works but the error messages like "e-mail field is required" aren't shown when I submit the empty form.

Here is an example of the error test auto implemented in my login.blade.php :

<div class="form-group">
          <div class="col-md-12">
              <input id="email" type="email" class="form-control" placeholder="" name="email" value="" required autofocus>

              @if ($errors->has('email'))
                  <span class="help-block">
                      <strong></strong>
                  </span>
              @endif
          </div>
</div>

Please notice that when I enter a bad combinaison of email/password the error message is shown correctly but for any other case the page doesn't even refresh.

Thank you for your help ...



via Chebli Mohamed

Eloquent relationship grouped by pivot relationship

I am trying to create a relationship for a model for an Order which will group items by their menu item, to end up with the following data structure (when outputted to JSON):

{
  "id": 123,
  "items": [
    {
      "menu_item_id": 32,
      "items": [
        {
          "id": 456,
          "order_id": 123,
          "menu_item_id": 32
        },
        {
          "id": 457,
          "order_id": 123,
          "menu_item_id": 32
        }
      ]
    },
    {
      "menu_item_id": 37,
      "items": [
        {
          "id": 466,
          "order_id": 123,
          "menu_item_id": 37
        },
        {
          "id": 467,
          "order_id": 123,
          "menu_item_id": 37
        }
      ]
    }
  ]
}

I have the following models & relationships:

class Order extends Model
{
    ...
    public function items()
    {
        return $this->hasMany('App\Models\OrderItem');
    }
    ...
}

class OrderItem extends Model
{
    ...
    public function menuItem()
    {
        return $this->belongsTo('App\Models\MenuItem');
    }
    ...
}

Any suggestions on how?



via Chebli Mohamed

MySQL Query doesn't check for condition

I have a query like this:

 select * from `research_purchases` left join `company_research_articles` on `research_purchases`.`researchable_id` = `company_research_articles`.`id` and `research_purchases`.`researchable_type` = 'Modules\Analystsweb\Entities\CompanyResearchArticle'

The research_purchases table structure is like this:research_purchases table

It is not filtering the "Modules\Analystsweb\Entities\CompanyResearchArticle" part and giving me the entire result. Any suggestions would be appreciated. Thank you.



via Chebli Mohamed

laravel fetch records from model if record exist in other model

hi i have two models named user and task. An user has many task and aleast one task to alloted to one user. i have already made one to many relationship but when i fetch and show username and no of task each user, it shows those users who has 0 task. My user class

class User extends Model
{
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'user';

/**
* The database primary key value.
*
* @var string
*/
protected $primaryKey = 'id';

/**
 * Attributes that should be mass-assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'type', 'status', 'punch_time'];

public function tasks()
{
    return $this->hasMany('App\Task');
}
}

My task class

class Task extends Model
{
public $timestamps = false;
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'task';

/**
* The database primary key value.
*
* @var string
*/
protected $primaryKey = 'tsk_id';

/**
 * Attributes that should be mass-assignable.
 *
 * @var array
 */
protected $fillable = ['user_id', 'name', 'description', 'punch_time',    'status', 'redemption_time'];


public function user()
{
    return $this->belongsTo('App\User', 'id');
}
public function availableTask()
{
    return $this->task()->where('user_id','!=', 0);
}
}

my controller function $users = User::with('availableTask')->paginate($perPage); Thanks in Advance



via Chebli Mohamed

Laravel+Passport as oAuth server and axios+cordova as a client

Hello Coders,

My goal is to make an API on laravel so user get/post the data on other device /client. Client code is on axios+cordova. Am I on correct path or doing wrong. First time on Laravel + Passport API as well as on axios + cordova also.

Server Side

I setup server with the help of Laravel 5.6.4 + Passport and created token on Postman successfully.

oauth token

Client Side

Now I am trying to access user data through api/user default route in separate project, here is my code for that

AUTH_TOKEN                                     =    'Bearer eyJ0eXAiOiJKV1QiLCJ...';

axios.defaults.baseURL                         =    'http://sbs-api.dev';
axios.defaults.headers.common['Authorization'] =    AUTH_TOKEN;
axios.defaults.headers.post['Content-Type']    =    'application/x-www-form-urlencoded';

axios.get('/api/user')
    .then(function (response) {
        console.log(response);
})
.catch(function (error) {
    console.log(error);
});

but I'm unable to get user data instead of getting this error Network Error and/or Preflight Error. On Postman I am getting the data with same token.

enter image description here

Please tell me what is wrong with this code and/or provide some tutorials if possible.



via Chebli Mohamed

Laravel 5 JWTAuth to check the user role is admin or not

when front-end parse a token to back-end, how to use JwtAuth to check the user relationship(role) that is a admin (role=1) or normal (role=0) ?

any idea?

The relationship with user and role

User

public function role()
{
   return $this->hasOne('FACI\Entity\User\Role','user_id','id');
}

Role

protected $fillable = ['user_id','role'];

public function user()
{
    return $this->belongsTo('FACI\Entity\User','user_id','id');
}



via Chebli Mohamed

How does sessions work in Laravel 5

I am trying to understand how sessions work in Laravel 5(.4). In one hand there are two ways of using them as described in the official documentation:

There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.

$request->session()->put('key', 'default');

and

session('key', 'default');

The documentation says:

There is little practical difference between using the session via an HTTP request instance versus using the global session helper.

But it is never explained what the difference is.

In the other hand there is the "Facade way":

Session::put('key', 'value');

And recently I found this Stack Overflow question How to use session in laravel 5.2 controller. train_fox pointed out this way:

session()->put('key', 'default');

So that makes a total of four ways. And I cannot figure out why or when use one or another.

By the way, the only way I could get sessions to work with Redis was with the two last ways.

Thank you in advance for your enlightenment.



via Chebli Mohamed

Laravel 5.4 How to update database connection for migration

I have post request where I update database config. I save data for one connection in my storage. In database config I call function to get it.

When data are updated I also update local config by config('database.connections.myconnection',$newConf)

The problem is in artisan:migrate action. In the same request I need to call to artisan:migrate but with new datbaase configuration.

Unfortunately I can set only database string to Artisan::call('migrate',['database'=>'myconnection'])

Migrate try to use old db data and I get error about db connection.

Someone have any idea how I can provide new config for migrate "in fly"?



via Chebli Mohamed

Laravel 5 route url cron execute only by server

I have url for example www.domain.com/cron/

Only the server has rights to execute the url, so nobody can not approach this url by the browser.

How can i achieve that?



via Chebli Mohamed

undefined index on empty array laravel 5

Fellow coders,

It might be a stupid question but I really am stuck on this part in my application.

I am making an hourregistration system for the company i'm an intern at. What I have done is creating a delete button in my application that deletes a record with the click of a simple button. Yet what I did was to delete all the visible records in the table I created that shows all the registrations.

When I deleted the final record I got an error of "undefined index hourregistration".

public function index()
{
    $hoursregistrations = Hoursregistration::latest()->get();
    $user_id = Sentinel::getUser();
    $project_id = Project::pluck('description', 'id');
    $company_name = Company::where('status','client')->pluck('company_name', 'id');
    $activity_name = Subproject::pluck('id');
    //dd($hoursregistrations);

    return view('hoursregistrations.index', compact('hoursregistrations', 'user_id', 'project_id',
    'activity_name', 'company_name'));

}

I think the problem lies at

$hoursregistrations = Hoursregistration::latest()->get();

Because I'm trying to get the latest value of the registration but there is none right?

Now i'm wondering how I could still show my view without breaking my inserting and/or viewing portion of the app.

 @foreach ($hoursregistrations as $hoursregistration)
                <tr>
                   <td hidden></td>
                   <td >{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}</td>      
                   <td>{!! $hoursregistration->note !!}</td>    
                   <td>{!! \App\Helpers::dateFormat($hoursregistration->date) !!}</td>
                   <td>{!! $hoursregistration->hours !!}</td>
                   <td>

                    <button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="">Edit</button>
                    <form action="hoursregistrations//delete" method="POST">
                        
                        
                        <button id="btn-delete" type="submit" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="">Delete</button>
                    </form>
                </td>
            </tr>
            @endforeach

This is the foreach loop that shows the data in the index.blade.php view

I would love some help so I can continue finishing this application



via Chebli Mohamed

jeudi 27 avril 2017

Laragon-can't detect my laravel project

I am trying to learn how to work with Laravel. I successfully installed Laravel through Laragon. The process that I followed-

Menu->Quick Create->Laravel->(Gave a Project name-laravel_CRUD)->Ok.

Then everything was installed and created successfully including database and dependencies were successfully updated. A pretty url was also generated as this format- http://laravel_CRUD.dev. But whenever I pasted this url into my browser's url bar, it didn't work and showed-"The site can't be reached". (Obviously Apache and MySql were started) I stopped those and restart those again. But still it failed to detect my project !!!!! What's wrong with it!!!! Anybody please help.



via Chebli Mohamed

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel

Im trying to create a foreign keys using artisan, but this error show up.

[Illuminate\Database\QueryException]                                                                                                                                                                             
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_comment_lot_id_foreign` foreign key (`comment_lot_id`) references `lots` (`lot_id`  
  ) on delete cascade) 

This is my migration:

<?php

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

class CreateCommentsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->text('comment');
            $table->integer('comment_lot_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table) {
            $table->foreign('comment_lot_id')->references('lot_id')->on('lots')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropForeign(['comment_lot_id']);
        Schema::dropIfExists('comments');
    }
}

in the lots table i use lot_id as id it model Lot.php i add:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Lot extends Model {
    protected $primaryKey = 'lot_id';

}

Any idea how can i resolve this error?



via Chebli Mohamed

Undefined variable: table when login using laravel5.2

When I try to login, I get this error

ErrorException in ActivationRepository.php line 41: Undefined variable: table

but user get logged successfully, this was working fine before, can you please look at this, what could be the issue?

Any help would be highly appreciated.



via Chebli Mohamed

Cannot call variables $_SESSION inside controller Laravel 5

I need to call $_SESSION in laravel controller, because I placed laravel in a subfolder of another website so I need to get the session from another website. But because of I call $_SESSION inside controller, the redirect thing is not working and shown like this when I run php artisan route:list:

enter image description here

Anyone can help me to call $_SESSION from laravel controller? Thank you.



via Chebli Mohamed

[Laravel 5.4]Reload config and reconnect to dabatabse in same action.

I need to update database configuration from atrisan action or http request action.

I have method which save new configuration. But When I try to check connection always Laravel use old database config. New is use in next command run or http request.

My code to check connection

$isConnected = (DB::reconnect('sakuicms')->table(DB::raw('DUAL'))->first([DB::raw(1)])?true:false);

It works but always with old data.

I've been tried also get again config and set config "in fly" with new data.

Config is changing ok, but connection still is with connection data like on the start of command. I can't force reload config to new connection.

My goal is, show for superuser that his new connection data are correct or not.

Any idea how I can solve it?



via Chebli Mohamed

Eloquent "all()" method [Laravel 5.4]

Eloquent is not returning me the data correctly (that's what I think).

I'm getting null variables here. What should I do?

When i do dd(Productos::all()); it shows me what is showed below (the info I want lies in 'original' and 'attributes'):

Collection {#178 ▼
  #items: array:4 [▼
    0 => Productos {#179 ▼
      +id: null
      +id_categoria: null
      +nombre: null
      +precio: null
      +descripcion: null
      +created_at: null
      +udated_at: null
      #fillable: array:4 [▼
        0 => "id_categoria"
        1 => "nombre"
        2 => "precio"
        3 => "descripcion"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 1
        "id_categoria" => 1
        "nombre" => "Invitacion 1"
        "precio" => "75.000"
        "descripcion" => """
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut ultrices quam. Phasellus eget magna in justo cursus posuere. Curabitur porta, purus eu co ▶
          \n
          """
        "created_at" => "2017-04-27 21:19:41"
        "updated_at" => "2017-04-27 21:19:41"
      ]
      #original: array:7 [▼
        "id" => 1
        "id_categoria" => 1
        "nombre" => "Invitacion 1"
        "precio" => "75.000"
        "descripcion" => """
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut ultrices quam. Phasellus eget magna in justo cursus posuere. Curabitur porta, purus eu co ▶
          \n
          """
        "created_at" => "2017-04-27 21:19:41"
        "updated_at" => "2017-04-27 21:19:41"
      ]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▼
        0 => "*"
      ]
    }
    1 => Productos {#180 ▼
      +id: null
      +id_categoria: null
      +nombre: null
      +precio: null
      +descripcion: null
      +created_at: null
      +udated_at: null
      #fillable: array:4 [▶]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 2
        "id_categoria" => 2
        "nombre" => "Invitacion 2"
        "precio" => "75.000"
        "descripcion" => """
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut ultrices quam. Phasellus eget magna in justo cursus posuere. Curabitur porta, purus eu co ▶
          \n
          """
        "created_at" => "2017-04-27 21:20:09"
        "updated_at" => "2017-04-27 21:20:09"
      ]
      #original: array:7 [▼
        "id" => 2
        "id_categoria" => 2
        "nombre" => "Invitacion 2"
        "precio" => "75.000"
        "descripcion" => """
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut ultrices quam. Phasellus eget magna in justo cursus posuere. Curabitur porta, purus eu co ▶
          \n
          """
        "created_at" => "2017-04-27 21:20:09"
        "updated_at" => "2017-04-27 21:20:09"
      ]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▼
        0 => "*"
      ]
    }
  ]
}

Controller:

public function showAll(){
    return view('productos.index',[
                'productos' => Productos::all()
                ]);
}

View:

@foreach($productos as $producto)
 <div class="row">
  <div class="col-sm-6 col-md-4">
    <div class="thumbnail clearfix">
      <img class="image-product" src="image.jpg" resposive alt="...">
      <div class="caption">
        <h3></h3>
        <p class="justify">
            
        </p>
        <p><a href="#" class="btn btn-primary pull-right" role="button"><i class="fa fa-cart-plus"></i> Añadir al carrito</a>
        </div>
      </div>
    </div>
  </div>
@endforeach


via Chebli Mohamed

PDOException in Connector.php Laravel

Today I experienced overall system down and I got the exception in the attached below image. PDOException in Connector.php line 55: SQLSTATE[HYooo][2002]

enter image description here

I solved the issue by killing mysql and running it again. But I need to prevent this from happening again. I use Laravel & mysql on Ubuntu 14 hosted on Amazon AWS EC2.



via Chebli Mohamed

Undefined variable: $_SESSION Laravel

I have problem when get PHP superglobal variable $_SESSION from inside laravel controller.

I can get Moodle session from laravel . I can get moodle session in laravel with $_SESSION['USER'] using this example http://ift.tt/2oRK9EM), but if I run php artisan route:list itu return error, like this:

enter image description here

So i cannot use laravel redirect function. Anyone can help me with this? Is there any other way to call superglobal $_SESSION in laravel controller? Thank you



via Chebli Mohamed

Looping over json responce in laravel

I'm working on a code base and need to use a Json response in laravel view. Currently in the view I'm returning the query result with:

<table>
     <tbody>


         


      </tbody>
</table>

and the response is:

HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"rows":[{"date":"2017-04-22","id":"5553","consumer_name":"Tabitha Henry","consumer_name_ctm":"Tabitha Henry","audio_url":"http://ift.tt/2prl6f5","consumer_ctm_phone":"+16305188154","email_msg":"","bid_amt":"$292 - $387","phone":"\u2713","email":""},{"date":"2017-04-21","id":"5817","consumer_name":"Josie Henle","consumer_name_ctm":" ","audio_url":"","consumer_ctm_phone":"","email_msg":"Do you have any availability for Sunday, April 30th? Would love to book you for quote #MM-27155 (one bedroom in Roger's Park to Skokie).","bid_amt":"$292 - $482","phone":"","email":"\u2713"},{"date":"2017-04-21","id":" ","consumer_name":null,"consumer_name_ctm":"Morgan Kenyon","audio_url":"http://ift.tt/2qkJsnS","consumer_ctm_phone":"+14058233483","email_msg":"","bid_amt":" ","phone":"\u2713","email":" "},{"date":"2017-04-20","id":"5722","consumer_name":"Jennifer Niendorf","consumer_name_ctm":" ","audio_url":"","consumer_ctm_phone":"","email_msg":"Hello, \nI was interested in your weekday moving rates.\nThanks!\nJennifer Niendoef","bid_amt":"$292 - $482","phone":"","email":"\u2713"},{"date":"2017-04-20","id":" ","consumer_name":null,"consumer_name_ctm":"Fears Cannon","audio_url":"http://ift.tt/2przoMD","consumer_ctm_phone":"+16302051722","email_msg":"","bid_amt":" ","phone":"\u2713","email":" "},{"date":"2017-04-19","id":" ",..........and so on.

I'm just not clear on how to convert this into usable information that I can loop over in the view. I really appreciate any help or suggestions.



via Chebli Mohamed