lundi 30 janvier 2017

Laravel 5.1 How to build forgot password functionality

I am using laravel 5.1 and I do not know how I should built in the functionality that a user can reset his / her password.

Typing the mail address and getting a route to reset and submit a new password.

I could not find a good tutorial for this purpose so I ask here.



via Chebli Mohamed

dimanche 29 janvier 2017

Laravel Collection In One To Many Relationships

I have a query like this(A one to many relationships)

Camp is related to Campaign

$camp =Camp::where('campaign_id', $cid)->where('weight','!=',0)->lists('weight','id')->toArray()

That would result long sql queries

 select `weight`, `id` from `camp` where `campaign_id` = '15' and `weight` != '0'


select `weight`, `id` from `camp` where `campaign_id` = '25' and `weight` != '0'


select `weight`, `id` from `camp` where `campaign_id` = '48' and `weight` != '0'

select weight, id from campaign_creatives where campaign_id = '20' and weight != '0'

select `weight`, `id` from `campaign_creatives` where `campaign_id` = '38' and `weight` != '0'


select `weight`, `id` from `campaign_creatives` where `campaign_id` = '23' and `weight` != '0'

How to make this in one query with multiple campaign_id?



via Chebli Mohamed

samedi 28 janvier 2017

Triggering a function after ajax call has finished loading images in Laravel

I've got an image gallery on my page, which works a lot like pinterest.

$images = Images::paginate(5);

On my image page, I start off with 5 images.

Controller:

if($request->ajax()) {
    return [
        'images' => view('browse.partials.imagePartials')->with(compact('images'))->render(), 'next_page' => $images->nextPageUrl()
    ];
}           

return view('browse.combined_results')->with('images', $images);

Markup:

<div id="freewall" class="freewall endless-pagination" data-next-page=>
@foreach ($images as $image)
<a href="">
    <div class='brick featuredTextContainer' style="width:150px">
        <img src='' width='100%' class="profileImg">
        <span class="featuredArtistName"></span>             
    </div>
</a>
@endforeach
</div>

These images are arranged using freewall:

var wall = new Freewall("#freewall");
wall.reset({
    selector: '.brick',
    animate: true,
    cellW: 150,
    cellH: 'auto',
    onResize: function() {
        wall.fitWidth();
    }
});

var images = wall.container.find('.brick');
images.find('img').on('load', function() {
    wall.fitWidth();
});

wall.fitWidth();    

wall.fitWidth() is the method that arranges the images all neatly, like so:

enter image description here

However, if you scroll down, you get an ajax request

$(window).scroll(fetchImages);

function fetchImages() {
    var page = $('.endless-pagination').data('next-page');

    if(page !== null) {

        clearTimeout( $.data( this, "scrollCheck" ) );

        $.data( this, "scrollCheck", setTimeout(function() {
            var scroll_position_for_images_load = $(window).height() + $(window).scrollTop() + 100;

            if(scroll_position_for_images_load >= $(document).height()) {
                $.get(page, function(data){
                    $('.endless-pagination').append(data.images);
                    $('.endless-pagination').data('next-page', data.next_page);
                });

            }
        }, 350))

    }
}

The ajax request loads a partial, which is essentially just the next page of the pagination.

imagePartial.blade.php

@foreach ($images as $image)
        <a href="">
            <div class='brick featuredTextContainer' style="width:150px">
                <img src='' width='100%' class="profileImg">
                <span class="featuredArtistName"></span>             
            </div>
        </a>
@endforeach

In other words, it loads in more images from the $images pagination into the images container.

Which is great. It works. However, the images aren't arranged right away. You have to execute wall.fitWidth() once more for the images to fit into place. The problem is, I can't simply put this at the end of the fetchImages function, because the images take a moment to load in. Therefore, all the images are loaded behind the other images, unarranged.

A solution to this would be to, say, have the new images loaded in with opacity set to 0, have the wall.fitWidth() function executed after a check to make sure all the images have been loaded into the DOM, THEN set the images back to opacity: 1. But I'm not sure how to do this.

Help?



via Chebli Mohamed

vendredi 27 janvier 2017

Apply math operations over column of table

This question is about finding approaches to solve a specific problem.

I have a table which has several metrics with values.

[metric1] [metric2] [metric3] [metric...N]

Those columns are fixed.

I need the user to be able to generate calculated metrics using the existing columns.

Let's say that a user made a custom metric which looks like:

[custom_metric] = ([metric1] + [metric3])*[metric2]

Therefore the user would be able to select a report using this custom metrics and other metrics as well.

I have two options. One is to manage this in the database which is a PostgreSQL. Other one is to split the math formula into pieces and store it which I think is the way to go. For PHP I'm using Laravel 5.1. The problem is how to store the formula in a way that could be easily applied when I'm generating the report.



via Chebli Mohamed

jeudi 26 janvier 2017

Laravel 5.1 - Skip Route with Route Model Binding

Say I've got this set in RouteServiceProvider::boot():

$router->bind('user', function ($value) {
    return \App\Models\User::where('name', str_slug($value))->first();
});

And I have this route:

Route::get('/{user}', ['as' => 'profile', 'uses' => 'ProfileController@getProfile']);

But the unfortunate structure of the website means that the routing rules that would check this are at the same level of other rules which are inserted statically. If a model doesn't exist, it would be ideal for it to skip the routing rule in question.

I've tried shifting the route that needs this change behind every other route, but alas, the problem persists. It tries to match this route no matter what.

What do I need to do to resolve this? I cannot change the structure of the whole web app, but I still need dynamic routing at this path level.



via Chebli Mohamed

Laravel 5.1 - Filtering on Collections

I have the following tables.

 basket_items:

 id  |  basket_id | product_id
 -----------------------------
 1   |  4         |   1
 2   |  4         |   2
 3   |  4         |   1
 4   |  4         |   1
 5   |  4         |   1


 prepaid_credits:

 id  |  order_item_id  |  product_id  | quantity
 ----------------------------------------------
 1   |  2              |   1          |  1
 1   |  3              |   1          |  2

I get a list of prepaid credits as follows which tells me user 1 has 3 credit available for product_id 1

  $prepaidCredits = DB::table('orders')
                   ->join('order_items', 'orders.id', '=', 'order_items.order_id')
                   ->join('prepaid_credits', 'order_items.id', '=', 'prepaid_credits.order_item_id')
                   ->where('orders.user_id', '=', 1)
                   ->select(DB::raw('SUM(prepaid_credits.quantity) as quantity, prepaid_credits.product_id'))
                   ->groupBy('prepaid_credits.product_id')
                   ->havingRaw('SUM(prepaid_credits.quantity) > 0')
                   ->get();

I get a list of basket items as follows:

  $basketItems = DB::table('basket_items')->where('basket_id', '=', 4)->get();

Now I want to create two new collections. One collection of basket items where the user can use an available credit and another collection where the user has to pay. How do I loop through and check the basketItems collection with the prepaidCredits collection to give me the above? So in the example above I should end up with $basketItemsUseCredits with basket_items with id's 1,3 and 4. $basketItemsPay should end up with basket_items with id's 2 and 5.

  $basketItemsUseCredits = $basketItems->filter(function ($basketItem) {
       // return items where user has pre paid credits for that product
  })

  $basketItemsPay = $basketItems->filter(function ($basketItem) {
       // return items where user has no pre paid credits
  })

Any help appreciated.



via Chebli Mohamed

mercredi 25 janvier 2017

how to redirect with https for particular page only in laravel

i want to redirect particular page only to https, rest of page will remain in normal http.

i want to do this for payment page only.after successful payment site will run with normal http.

so please help me for do this.

i already try this one.

Route::resource('paynow', ['uses' => 'Account\PaymentController', 'https' => true]); 

but this will not work for me.



via Chebli Mohamed

mardi 24 janvier 2017

Get records within a specific timeframe in Laravel

On my website, I use Laravel's created_at to store the time at which images are uploaded.

However, I want to be able to create a query that gets images only within a specific time frame.

Those would be:

-The past 24 hours

-The past week

-The past month

-The path year

I was thinking of something like...

$images = Images::where('created_at', '>=', Carbon::now()->hours(24))->get();

It would be easy to get records from within specific hours, since I could simply go from 24 to 168 to 672 to 2087 (day, week, month, year).

Thoughts?



via Chebli Mohamed

Querying counts from large datasets using eloquent

I have the following relationships:

A Job has many Roles.

public function roles()
{
    return $this->hasMany(Role::class);
}

A Role has many Shifts and Assignments through shifts.

public function shifts()
{
    return $this->hasMany(Shift::class);
}


public function assignments()
{
    return $this->hasManyThrough(Assignment::class, Shift::class);
}

A Shift has many Assignments.

public function assignments()
{
    return $this->hasMany(Assignment::class);
}

I need to get a count of all assignments with a certain status, let's say "Approved". These counts are causing my application to go extremely slowly. Here is how I have been doing it:

foreach ($job->roles as $role){
    foreach ($role->shifts as $shift) {   
        $pendingCount = $shift->assignments()->whereStatus("Pending")->count();
        $bookedCount = $shift->assignments()->whereIn('status', ["Booked"])->count();
    }
}

I am certain that there must be a better, faster way. Some of these queries are taking upwards of 30+ seconds. There are hundreds of thousands of Assignments, which I know is affecting performance. How can I speed these querie up?



via Chebli Mohamed

REPLACE in FIND_IN_SET raw query

I try do something like this:

 <?php $prodottix = \App\Models\Prodotti::whereRaw('FIND_IN_SET(?, REPLACE(categoria_composta, ">", ',') )', [$id])->paginate(30); ?>

basically i need to FIND_IN_SET in a field WHERE , is >... but i'm get array to string error...



via Chebli Mohamed

Laravel localization: optional placeholders

In Laravel, you can use placeholders in localization files, so that if you have a welcome.php file set up with the following rule:

'welcome' => 'Welcome, :name. Everything alright in :city?',

and you use this to print out a message:

echo trans('messages.welcome', ['name' => 'Dayle', 'city' => 'Boston']);

you will see this:

Hello, Dayle! Everything alright in Boston?

Here :name is a placeholder. My question is: can you make these placeholders optional, i.e. if their value is null, a different text will be displayed? In the above case, if we skipped the city argument in the trans function, I would like to see this:

Hello, Dayle!



via Chebli Mohamed

lundi 23 janvier 2017

ErrorException Argument 1 passed to Zizaco\Entrust\Middleware\EntrustRole::__construct()

I got this ERROR in LARAVEL 5.1 while using Entrust Package.

After autoload in command line, I got this error

C:\xampp1\htdocs\project>composer dump-autoload Generating autoload files

C:\xampp1\htdocs\project>php artisan db:seed --class=RolesTableSeeder

[ErrorException] Argument 1 passed to Zizaco\Entrust\Middleware\EntrustRole::__construct() must be an instance of Illuminate\Contracts\Auth \Guard,

I'm very new to LARAVEL, Please anyone Help me.....

//////////////// Role Migration Class ////////////////////////

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class EntrustSetupTables extends Migration
{
    public function up()
    {
        // Create table for storing roles
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });
   }

   public function down()
    {
       Schema::drop('roles');
    }
}
?>

/////////////////// Role Model //////////////////////////////////

<?php

namespace App;

use Zizaco\Entrust\Middleware\EntrustRole;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class Role extends EntrustRole
{
    use EntrustUserTrait;
    protected $fillable = ['name', 'display_name', 'description'];
}
?>

//////////////////// RolesTableSeeder ///////////////////////////

<?php
use App\Role;
use Illuminate\Database\Seeder;
use Zizaco\Entrust\Middleware;


class RolesTableSeeder extends Seeder
{

    public function run()
    {
        $owner = new Role();
        $owner->name         = 'owner';
        $owner->display_name = 'Project Owner'; // optional
        $owner->description  = 'User is the owner of a given project'; // optional
        $owner->save();

        $admin = new Role();
        $admin->name         = 'admin';
        $admin->display_name = 'User Administrator'; // optional
        $admin->description  = 'User is allowed to manage and edit other users'; // optional
        $admin->save();
    }
}
?>

/////////////////////////// .env file //////////////////////////////

DB_HOST=localhost
DB_DATABASE=project_api
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null



via Chebli Mohamed

Laravel Eloquent Chat Inbox Query

I keep trying to ask this question here on stackoverflow several times but cant seem to get any help. Maybe third time is the charm.

I'm building a chat feature inside laravel app and I'm struggling to get the inbox section right. I've read a tonn of other threads on here but mysql is not my strongest suit so I'm having an issue.

Basically, I got this query to get me the last message from the user who just messaged me to show up in my inbox. The problem is, if I'm the one sending out a message to another user, it will not display anything in my inbox since I'm the author not the recipient. How would I make this query to display the latest message from another user in my inbox and also show that I have started a conversation to another user.

 $chat_inbox = Message::where('author_id', $this->user->id)
        ->orWhere('recipient_id', $this->user->id)
            ->join(DB::raw('(Select max(id) as id from messages where author_id ='.$this->user->id.' group by unique_chat_id) LatestMessage'), function($join) {
                $join->on('messages.id', '=', 'LatestMessage.id');
            })
            ->get();

Mysql table columns are: unique_chat_id, author_id, recipient_id, viewed, user_read, created_at, and updated_at

If you need any further details, please let me know. Thanks in advance!



via Chebli Mohamed

Retrieving the last user message from chat - inbox

I'm building a chat section of my website and here is what I came up with for the query for retrieving last message for inbox and the conversation.

     $chat_inbox = Message::where('author_id', $this->user->id)
        ->orWhere('recipient_id', $this->user->id)
        ->groupBy('unique_chat_id')
        ->latest();

the problem is that I need to find the last message that the other user sent, not the one sending the message. I can then display this message as unread in the inbox, but I also need to retrieve the conversation that the current user started even if the other use still have not responded.

This current query will get me the last message no matter who sent it. Any help is appreciated.



via Chebli Mohamed

dimanche 22 janvier 2017

Laravel Model : filter database result based on conditions

I would like to be able to filter directly from my request if a user is available in the geographical area that he indicated. So I created a function in my User Model:

public function location(){
$function = new Jfunction();
$visitorLocation = Session::get('location');

if(!empty($this->lat && !empty($this->long)))
{
    $distance = round($function->get_distance_m($visitorLocation['lat'], $visitorLocation['lon'], $this->lat, $this->long)/ 1000, 3);
}
else
{
    $distance = 0;
}

if(empty($this->distance))
{
    $dbDistance = 0;
}
else
{
    $dbDistance = $this->distance;
}

if($distance >= $dbDistance)
{
    return true;
}
else
{
    return false;
}}

To call this function in my query, I do: -> has ('location') .... but this returns the following error: "Call to a member function getRelationQuery () on a non-object".

$users = User::has('location')->where(function($q){
                        $q->where('status', 3);
                        $q->orWhere('status', 10);
                        $q->orWhere('status', 11);
                    })->orderBy('created_at', 'desc')->get();

It looks like Laravel does not want to return a TRUE or FALSE value.

Can you help me ?



via Chebli Mohamed

Laravel 5.2: How to scheduled Command multiple times in a day

I am using laravel 5.2 commands via scheduler, i can call the command by following code:

$schedule->command('command:name')
                ->dailyAt('08:55');

but now i want to call above command daily at six different times i.e. 8:45, 9:15, 9:45,10:15 etc

$schedule->command('emails:dailyMenuEmails')
            ->when(function(){return true;});

Above code, with when function, isn't working somehow, can someone suggest best practices of laravel.



via Chebli Mohamed

laravel about inner join and subquery

ok, now ,I want get sql just like:

select field1,field2,field3  from table1  

inner join  

(select id from table1 where field4=$field4 limit 100, 20)
as temp using(id)

how can I get this by laravel 5.1?

thank you ~



via Chebli Mohamed

vendredi 20 janvier 2017

Group Conversation by latest message Laravel

I cant seem to figure this out since mysql is not my strong suit. I've done a bit of research here but can't put two and two together, so i'm turning to the community for some help.

I am building a chat function inside my laravel app where two users can talk to each other. I cant figure out how to build the inbox (group the conversations together) portion of things. I've figured out how to get lastMessage grouped by sending it.

The following is inside my User Model:

public function lastMessages() { return $this->hasMany('App\Message', 'recipient_id') ->select('*') ->join(DB::raw('(Select max(id) as id from messages group by author_id) LatestMessage'), function($join) { $join->on('messages.id', '=', 'LatestMessage.id'); }) ->orderBy('created_at', 'desc'); }

My messages table consists of the following: author_id, recipient_id, messaged, viewed.

What I need to do is group messages, whether incoming our outgoing and display the latest message as inbox entry and once I click on that messages, the rest of the conversation pops up on the page.

My current sql shown above only gives me 1 last message, not the whole conversation.

Thanks in advance for all the help.



via Chebli Mohamed

mercredi 18 janvier 2017

Generate dynamic time slot using php mysql

I am building an event based website where I need to display dynamic time slot for the attendees.

During the event every hour has 20 minutes slot where at most 30 people can do some activities. So for example - at 9:00 30 people can do their activities. Then at 9:20 other 30 people can do their activities.

This way it the activities will be running from 9 am to 5 pm for 3 days.

So when someone wants to attend to a specific time slot, the UI will populate all the available time slots counting the database table. If no slots available he will not be able to attend the event and the slot non availability message will be displayed.

I have to build this solution using PHP, MySQL.

Any suggestion will be appreciated.



via Chebli Mohamed

How to get a cookies via ajax (laravel 5.1)?

I need your help with Laravel cookies! Issue in the next:

I have two routes:

Route::get( 'url-1', function () {
    ...
    $cookie = Cookie::forever('cookie-key', 'cookie-value');
    ...
    return redirect('<external-url>')->withCookie($cookie);
});

Route::get( 'url-2', function () {
    ...
    $cookie_value = Cookie::get('cookie-key');
    ...
    return view ("<view>", [
        'cookie_value' => $cookie_value
    ]);
});

When I go to url-1 it redirects me to external URL. On this external URL I am sending the ajax request to url-2. I am getting an empty value of cookie_value=. Please help me. Thanks!



via Chebli Mohamed

Laravel haversine calculation

I use this tool to calculate distance between 2 points:

$location = new CnpPoi(28.535153, -81.383219);
$destination = new CnpPoi(42.594018, -88.433886)
$location->getDistanceInMilesTo($destination);
$location->getDistanceInMetersTo($destination);

need to use it inside a query to get store ordered by distance from a given point that already have passed trough url his $lat e $long. How i can use this function inside a query?



via Chebli Mohamed

mardi 17 janvier 2017

How To Prevent Queued Job From Executing After Failure?

I have configured my supervisor worker to attempt laravel queued job 3 times in case of failure. Below is the sample of my worker config.

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php home/vagrant/Code/lead_reactor/artisan queue:work database --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=vagrant
numprocs=8
redirect_stderr=true
stdout_logfile=home/vagrant/Code/lead_reactor/storage/logs/laravel-worker.log

But I do have a specific laravel job queue that I want to be executed only once regardless if there is a failure or none. I want to prevent the future attempts of job execution if there is failure without changing my worker config.

Below is the structure of my job class.

class SendBugReports extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $bugReports;

    /**
     * Create a new job instance.
     *
     */
    public function __construct()
    {
        $this->bugReports = BugReport::all();
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //job processes...
    }
}

Any help will greatly appreciated! :)



via Chebli Mohamed

Laravel subdomain routing is not working

I'm trying to have an admin subdomain (like this)

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

but admin.localhost acts just like localhost. How I'm supposed to do this correctly?

I'm using Laravel 5.1 and MAMP on OSX



via Chebli Mohamed

lundi 16 janvier 2017

Laravel: Not able to access belongsToMany relation in nested whereHas

I am using whereHas in nested where clause but i am not able to do so. Following is my model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function scopePickedUser($query, $pickedTypeID)
    {
        return $query->where(function($query) use ($pickedTypeID)
        {
            $query->whereHas('photos', function($query) use ($pickedTypeID)
            {
                 $query->whereTypeId($pickedTypeID);
            });


            if($condition){
                $query->orWhere('another_column_id',$var);
            }
        });
    }

    public function photos()
    {
        return $this->belongsToMany(Photo::class);
    }
}

If i call, App\Models\User::pickedUser(4)->get() i am getting error BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::photos()'. Why is that? What am i doing wrong?



via Chebli Mohamed

how to display bootstrap success message in laravel 5.1

Hi Friend's need help how to display success message in laravel 5.1, I have applied it is working but twice display what is the reason . this is my layout.balde.php code

@if (session()->has('success'))
<div class="alert-success" id="popup_notification">
    <strong>{!! trans('main.message') !!}</strong>
</div>

@endif this is my controller page code:

  return Redirect::route($this->cdroute, array($customer_id))->with('success',trans($this->updatemsg));



via Chebli Mohamed

Updating config on runtime for a user

I am using Laravel 5.1

I created a function to get smtp info from db for a user $mail_config=STMPDetails::where('user_id',36)->first() and then I can just call config helper function and pass the array to set config value config($mail_config). and then I call Mail::queue function.

but before it reaches createSmtpDriver@vendor/laravel/framework/src/Illuminate/Mail/TransportManager.php where it reads the configuration again to send the mail, mail config are changed to the one specified in .env file.

Another thing to note is Mail sending function is in a Listener

I am not able to figure out where can I call the function such that configuration changes are retained before mail is sent.

Thanks, K



via Chebli Mohamed

How to access related model inside pagination (Laravel 5.1)

@foreach($tasks as $t)
   // works fine
   // Trying to get property of non-object
   // something similar error.
@endforeach

Given the following data structure, how could I access the last_active field of the related model?

dump

Task:

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



via Chebli Mohamed

Laravel belongsTo messes up pagination

A job has multiple tasks and one task belongs to a client.

Model:

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

View:

 // these work fine
 // works fine on 1st page, 
                     // Trying to get property of non-object on all other pages.



Controller:

$tasks = $job->tasks()->paginate(5);

I need something like this (I don't know the exact syntax), which adds the client data so that works with the pagination.

$tasks = $job->tasks()->with('client')->paginate(5); // ?



via Chebli Mohamed

ErrorException in BladeCompiler.php line 584: Undefined offset: 1

I'm learning Laravel and now I have faced a bad problem. Basically I have added a new controller called UsersController.php and I have set the route to that controller inside of web.php. Here's the controller:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index()
    {
        $users = [
            '0' => [
                'first_name' => 'Renato',
                'last_name' => 'Hysa',
                'location' => 'Albania'
            ],
            '1' => [
                'first_name' => 'Jessica',
                'last_name' => 'Alba',
                'location' => 'USA'
            ]
        ];
        return view('admin.users.index', compact('users'));
    }
}

So as you can see I have linked this to a blade which is inside of resources/views/admin/users and it is called index.blade.php and goes like this:

 @foreach($users as $user)
    <li>
    {!! $user['first_name'] !!} {!! $user['last_name'] !!}
    from {!! $user['location'] !!}
    </li>
@foreach

So when I goto this URL it must shows the users but instead of that it shows an error:

ErrorException in BladeCompiler.php line 584: Undefined offset: 1

Click to see the print screen of my page

And unfortunately I know nothing about what's going on there. I'm pretty sure that I have added everything correctly because I'm following a Youtube tutorials playlist and you can goto this link to see how it should be shown on the browser.

So if you know whats going wrong here please let me know.. Thanks!



via Chebli Mohamed

samedi 14 janvier 2017

Laravel Session remove/forget with redirect not working

What is wrong with my code here:

 use Illuminate\Support\Facades\Session;
 ...
 public function getFrontlogout(Request $request){
        d(Session::all());
        Session::forget('uid');
        return Redirect::back();
 }    
 public getIndex(Request $request){
    //ddd(Session::all());
    ....
    return view('index',$this->data);
 }

In my index blade I have a button (href) to logout that calls the getFrontlogout function and I want to reload the index AFTER removing some session variables. But the session variables seem to persist after REDIRECT.

So in the getFrontlogout if I do not do the redirect and die-and-dump there the session... it shows that I successfully removed the Session variables. But if I do not die there, and do the redirect, and display the session variables in the getIndex function... looks like nothing was removed from the Session.

I use hard-reload for the pages, and this keeps happening.

What is wrong here? My Session changes get lost when redirecting.

I use Laravel 5.1 and I would like to keep it that way because I have a lot of code that was written for 5.1 and I do not have the time to do an upgrade that would mess up my existing code.

I understand that in 5.2 for some early versions I would have to wrap my routes inside a group(['middleware' => ['web']], function () {...}), and for later 5.2 versions I would not have to do that anymore because they are already wrapped in the middleware.

What about laravel 5.1?

What do I have to do to make the session changes persistent?

I tried to use the web middleware but I get the message

ReflectionException in Container.php line 741: Class web does not exist



via Chebli Mohamed

Laravel 5.1 Call to undefined method Illuminate\Database\Query\Builder::cartItems()

I have the following model and controller but it keeps throwing error:

Call to undefined method Illuminate\Database\Query\Builder::cartItems()

This is my model and controller:

 class Cart extends Model
{
    protected $fillable = [
       'user_id',
       'coupon_id',
    ];

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

}


class CartController extends Controller
{


    public function index()
    {

       $userId = Auth::user()->id;

       $cart =  Cart::where('user_id', '=', $userId); 

       $cartItems = $cart->cartItems()->get();

       //...some other stuff...

       return view('cart.index', compact('cartItems'));
    }

 }



via Chebli Mohamed

Laravel testing unreachable field error when there is two forms in page

I want to test a page which has two forms in. When I want to test one of my forms the following error occurs:

Unreachable field "count"

Which count is a field in that form (it doesn't exit in the other form). When i remove the other form completely, it works correctly but I need to have both in the page.

It's my view:

    <section class="content">
        <div class="row">
            <div class="col-md-6">
                <div class="panel panel-green">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            Passenger Credit Adjustment
                        </h3>
                    </div>
                    <div class="panel-body">
                        <form method="post" action="">
                            
                            <div class="form-group">
                                <label for="amount">Name</label>
                                <input type="text" class="form-control" id="name" name="name" disabled="disabled"
                                       title="" value="">
                            </div>
                            <div class="form-group">
                                <label for="amount">Credit</label>
                                <input type="text" class="form-control" id="cashable" name="name" title=""
                                       disabled="disabled" value="">
                            </div>
                            <div class="form-group">
                                <label for="amount">Add/DeductAmount</label>
                                <input type="text" class="form-control" id="amount" name="amount">
                            </div>
                            <div class="form-group">
                                <label for="description">Description</label>
                                <input type="text" class="form-control" id="description" name="description">
                            </div>
                            <button type="submit" class="btn btn-danger">Apply</button>
                        </form>
                    </div>
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            <i class="livicon" data-name="money" data-loop="true" data-color="#fff"
                               data-hovercolor="#fff" data-size="18"></i>
                            Voucher
                        </h3>
                    </div>
                    <div class="panel-body">
                        <form method="post"
                              action="">
                            
                            <div class="form-group">
                                <label for="type">Type</label>
                                <select id="single-prepend-text" class="form-control select2" title=""
                                        name="type">
                                    <option value="5k">5k</option>
                                    <option value="10k">10k</option>
                                    <option value="20k">20k</option>
                                    <option value="15p">15%</option>
                                    <option value="20p">20%</option>
                                    <option value="25p">25%</option>
                                    <option value="30p">30%</option>
                                    <option value="50p">50% (Max 10k)</option>
                                    <option value="100p">100% (Max 20k)</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-danger" name="generate">Generate</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="panel panel-green">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            Free Ride
                        </h3>
                    </div>
                    <div class="panel-body">
                        <form method="post"
                              action="">
                            
                            <div class="form-group">
                                <label>Number of free ride(s):</label>
                                <input type="number" name="count" value="1" title="Count"  id="count"
                                       class="form-control">
                            </div>
                            <div class="form-group">
                                <label>Cap:</label>
                                <select class="form-control" name="cap" title="">
                                    <option value="">[NOT SELECTED]</option>
                                    <option value="50000">5,000 T</option>
                                    <option value="100000">10,000 T</option>
                                    <option value="150000">15,000 T</option>
                                    <option value="200000">20,000 T</option>
                                </select>
                            </div>
                            <input type="submit" class="btn btn-danger" name="generate" value="Generate">
                        </form>
                    </div>
                </div>
            </div>
        </div>

It's my test:

$this->visit($uri)
        ->type(3, 'count')
        ->select($cap, 'cap')
        ->press('Generate')

I'm using Laravel 5.1.



via Chebli Mohamed

vendredi 13 janvier 2017

Laravel Crinsane Shopping cart install migration

Has anyone installed Crinsane/shoppingcart ?

In the installation documentation there is no mention of the migration for the table. There is no mention of the configuration of the database connection. I can only assume that I am not very experienced with laravel, and it is probably something obvious that I do not know about.

Anyway: there is a config/cart.php file (in the vendor) where I found the database connection setting, but I have no idea on how to change it to make it work (I can only assume that I should change it because, of course, there is no table called shoppingcart in my application's database after I did my composer installation).

So I have this section in the cart.php file:

 'database' => [

        'connection' => null,

        'table' => 'shoppingcart',

    ],

How should I set this up? What do I write in the "connection"?

After installation, my Cart is working but it has a strange behavior, and I can only guess that it happens because there is no DB table anywhere that would hold the cart data.

The strange behavior is that when I add an item to the cart, it ends up in the cart but when I refresh the page, the cart gets empty. But when I add 2-3 products to the cart, and then refresh the page, the cart contains all the items (minus the one that I added to the cart before). Also after I add the first product, when I try to add a new item to the cart it does not do it on the first click on AddToCart button. But when I click again, the second product gets added to the cart

I am sure I am doing something wrong, Can anyone help me with a more detailed installation tutorial?



via Chebli Mohamed

How can I get access to all language keys in Laravel ioC container?

I am using Laravel 5.1. I can't upgrade to Laravel 5.3.

Laravel 5.3 has a function called addLines in the Lang facade the allow me to add Lang keys to the collection in memory.

But Laravel 5.1 and 5.2 do not have such a method. I want to be able to have a method in my code that allows me to do the same thing.

However, I am struggling to find a way to obtain the Lang keys as array where I can add keys to it.

How can I get the actual Lang keys collection so I can add keys to it at run time?



via Chebli Mohamed

production.ERROR: RuntimeException: No supported encrypter found. The cipher and / or key length are invalid.

I run my laravel 5.2 app on nginx ubuntu xenial (digital ocean)

Image don't upload in my production app whereas at localhost it works fine.

In my laravel log following error is shown :

>     production.ERROR: RuntimeException: No supported encrypter found. The cipher and / or key length are invalid.in
> /var/www/laravel/bootstrap/cache/compiled.php:7771 Stack trace:
> #0 /var/www/laravel/bootstrap/cache/compiled.php(7761): Illuminate\Encryption\EncryptionServiceProvider->getEncrypterForKeyAndCipher(NULL,
> 'AES-256-CBC')

ans so on ..

How do i resolve it.



via Chebli Mohamed

how to use pagination in groupby & orderby clause for fetching records in laravel by year wise

$newsYearCount = news::paginate(5)->groupBy(function($date) {
                      return Carbon::parse($date->created_at)->format('Y'); //
                  });

i want to use order By for above code and also it just group By 5 records, but i want a records like firstly it should group By and then apply pagination.



via Chebli Mohamed

Laravel line break in message

How do I do a line break in a message.

I tried following

$request->session()->flash('message', "first line \r\n second line");
$request->session()->flash('message', "first line <br> second line");

but they did not work, how do I accomplish this?



via Chebli Mohamed

How to save json data to mysql?

I am going to build a form customize system with Laravel 5.1 LTS. User could create forms, customize its fields and styles, release them then the other users could fill the form.

In the front-end side, i'm going to use Alpaca Forms. With this package, fields and datas are rendered with json.

Now the problem is how can i store fields' json and datas' json to mysql?(I don't really want to use mongodb or other nosql databases, cause i'm already using mysql now and i don't know how to deal with nosql.) The json is like this:

$("#form").alpaca({
    "data": {
        "name": "Diego Maradona",
        "feedback": "Very impressive.",
        "ranking": "excellent"
    },
    "schema": {
        "title":"User Feedback",
        "description":"What do you think about Alpaca?",
        "type":"object",
        "properties": {
            "name": {
                "type":"string",
                "title":"Name",
                "required":true
            },
            "feedback": {
                "type":"string",
                "title":"Feedback"
            },
            "ranking": {
                "type":"string",
                "title":"Ranking",
                "enum":['excellent','ok','so so'],
                "required":true
            }
        }
    },
    "options": {
        "form":{
            "attributes":{
                "action":"http://httpbin.org/post",
                "method":"post"
            },
            "buttons":{
                "submit":{}
            }
        },
        "helper": "Tell us what you think about Alpaca!",
        "fields": {
            "name": {
                "size": 20,
                "helper": "Please enter your name."
            },
            "feedback" : {
                "type": "textarea",
                "name": "your_feedback",
                "rows": 5,
                "cols": 40,
                "helper": "Please enter your feedback."
            },
            "ranking": {
                "type": "select",
                "helper": "Select your ranking.",
                "optionLabels": ["Awesome!",
                    "It's Ok",
                    "Hmm..."]
            }
        }
    },
    "view" : "bootstrap-edit"
});

I have come up with two solutions for save front-end json and one solution for save datas till now, but i don't think they are good enough, so i'm here asking for help to find a better one.

Save front-end json:

  1. list all the attributes of the front-end json, create a table with that and save all the value. It's not good to extend, if the package changes, i should update the table. the form field table is like:

    | id | form_id | type | name | rows | ... |

  2. resolve json to key-value array and save it to database. It's not good that if user creates a form, he will insert a lot of rows to table. the form field table is like:

    | id | form_id | key | value |

  3. save json as an attribute. I know Mysql 5.7 could support json, but i don't know if there is any other problems with this And Laravel 5.1 doesn't support json search. the form table is like:

    | id | json |

Save datas json:

  1. resolve json to key-value array and save it to database. It's not good that if user fills a form, he will insert a lot of rows to table. the data table is like:

    | id | form_id | key | value |

Thanks~



via Chebli Mohamed

jeudi 12 janvier 2017

laravel 5.1. why my update for pivot tabel dose not effected on table?

I have a user model :

namespace App\Models\UsersModels;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Model implements AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable,
        CanResetPassword,
        Authorizable,
        EntrustUserTrait // add this trait to your user model
    {
        EntrustUserTrait ::can insteadof Authorizable; //add insteadof avoid php trait conflict resolution
    }

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];



    /**
     * user belongs to many discount.
     */
    public function discounts()
    {
        return $this->belongsToMany('App\Models\Discounts\Discount', 'users_discounts')
            ->withPivot('id','earn_date_time','used_date_time','used_for_id','used_for_type');
    }

}

in this model I have a relation many to many with discounts. and other side this relation defined.

know I want update my users_discounts table .

when I use this for update:

 $a =  DB::table('users_discounts')
        ->where('discount_id', '=', 2)
        ->update(['used_for_id' => 2]);

       $d = DB::table('users_discounts')
            ->where('discount_id', '=', 2)
           ->get();

                dd($d);

and select after that, every thing is ok and return updated filed. but when I check my table any thing not updated. why ? I need define fillable for pivot table? or do more than update ?



via Chebli Mohamed

How to generate dynamic sub domain in laraval 5.2 ?

In my site (school management system) , i want to generate mini-site for each of the teacher and the admin member. Where the teachers and the admin member can put there task and other things.By using sub domain, i want to get this mini-site. So, how can i get this sub domain and how to access that sub domain?



via Chebli Mohamed

How to pass variable with response view in [Laravel 5.1]?

I am trying to pass variables with response view in laravel, but it is not allowing me to do so.
here is what i have tried so far:

return response(view('home'))->with('name','rocky');

the above method doesn't work,

the second one i tried is as follow:

return response(view('home'), ['name','rocky']);

but i don't know how to use the above one?

NOTE: i don't want to use view::make method, i want to pass variable with response method.

please help me to sort out this issue.

Thanks.



via Chebli Mohamed

laravel 5.1 : how can i have two wherePivot in eloquent?

I need check two where on pivot table. I know that I can check with this :

$dis = $user->discounts()->wherePivot('used_for_id','=',null)

I want two where. when I use OrwherePivot two where be "or" but I want "AND" two where.



via Chebli Mohamed

mercredi 11 janvier 2017

Delete Multime Row Laravel

in there i have a data, i want to add a delete data where i selected. here my code :

public function postDeleteall(){
        $id = Request::get('id');
        if($id ==''){
            Session::flash('delete', 'select first !');
            return redirect()->back();
        }else{
            foreach ($id as $q) {
                $qwery = DB::table('log_patrols')->where('id',$q)->get();
                foreach ($qwery as $a) {
                    DB::table('log_patrols')->where('id',$a->id)->delete();
                    $row =DB::table('log_patrol_details')->where('id_log_patrols',$a->id)->get();
                    foreach ($row as $qwe) {
                        @unlink(public_path("uploads/".$qwe->photo1));
                        @unlink(public_path("uploads/".$qwe->photo2));
                        @unlink(public_path("uploads/".$qwe->photo3));
                    }

                    $rows = DB::table('log_patrol_details')->where('id_log_patrols',$q)->delete();
                    Session::flash('delete', 'success');
                    return redirect()->back();
                }

            }
        }
    }

when i try to print the data $id

here

its want to get the data id where i select, but after i try to make the code its won't work like what i want. and its only delete 1 data where i selected. what should i do ? and what code need i change in my skript ?

thanks



via Chebli Mohamed

mardi 10 janvier 2017

Laravel default crypt method unexpected behaviour

I am trying to encrypt json encoded string from laravel's default encryption. But i am not sure it's using the AES-256-CBC The reason behind this i am also trying same encryption from AES custom class.

What i did.

  1. json_encode an array

  2. set the key ,mode and blocksize in AES custom class and generating the token.

  3. encrypt the token.

  4. set encrypted token using setData

  5. decrypt using AES custom class

Result is same as i was having in step1. When i tried to encrypt (Crypt::encrypt($requestToken);) and decrypt (Crypt::decrypt($encrypt)) is giving correct result. Now the problem is i am encrypting through (Crypt::encrypt($requestToken);) and want to decrypt through AES custom class. I am not sure that client is having laravel or not .



via Chebli Mohamed

lundi 9 janvier 2017

Angular http post to Laravel backend Request always empty

I have a problem that i don't know how to solve. I use AngularJS 1 to make a post to my backend (Laravel 5.1). The post is successful from AngularJS.

In my Laravel controller i use Request to recieve the posted data from AngulrJS but the $request->all() is always empty and i dont know why.

I have i missed something in my post request?

LARAVEL ROUTE:

Route::post('/signup','SignupController@Signup');


LARAVEL CONTROLLER:
<?php


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

class SignupController extends Controller
{
    public function Signup(Request $request){


       dd($request->all()); <-- is always empty
    }  
}

ANGULARJS POST:

.controller('SignupCtrl',function($scope,$http,$state){ 

  $scope.Signup = function($params){

        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
        $http.post('http://localhost:8888/vemhamtar/public/signup',{"name":$params.name,"phone":$params.phone,"email":$params.email,"password":$params.password})
        .success(function(response){

          $params.name = "";
          $params.phone = "";
          $params.email = "";
          $params.password = "";
          $state.go("app.contacts");

        })
        .error(function(error){
          console.log(error);
        });
  };
})



via Chebli Mohamed

loading image into view after ajax call

Here is the problem I ran into just now. I have a chat function part of my laravel application that loads respective users images as they type in the conversation. What I cannot figure out is when I append the url for the profile picture into the view, it will not actually display the picture, it just shows a "placeholder" of where the picture should be.

I know the code works for a fact because I can see in the console log the correct path for the picture inside the assets folder.

So my question is how would I display a picture after retrieving info from an ajax call.

$('.chat-wrapper').append(
                    "<div class='message " + sent + "'>" +
                    "<div class='media-left'>" +
                    "<a href=''><img scr=" + data.profilePicture + " class='img-circle img-50x50' title=''></a>" +
                    "</div>" +
                    "<div class='media-body'>" +
                    "<small class='small-gray p-l-10 pull-right'>" + data.time + "</small>"+
                    "<div class='heading'>" +
                    "<span>"+data.authorUserName+"</span>" +
                    "</div>" +
                    "<p>" + messageText + "</p>" +
                    "</div>" +
                    "</div>"
            );

Thank you for the help in advance!



via Chebli Mohamed

Laravel Issues - Token missmatch

I use Laravel 5.1 for an serious project and everything is almost done.

I have an big problem and biggest issue and I dont know what is exactly the problem...

When I open some url sometimes works fine but sometimes I get this screen: enter image description here

but why? What can be a problem? I on every form have

The biggest problem is becouse sometimes work without problem and sometimes show this error screen... please help.



via Chebli Mohamed

dimanche 8 janvier 2017

How to handle fatal errors when reading an Excel file from PHPExcel

I'm using Laravel Excel v2.1.* for Laravel 5.1 to read data in from Excel files. I've come across fatal errors if the Excel file is badly formatted. My end users (who are reasonably proficient users of Excel) will need good feedback to point them in the right direction to clean up an Excel file before re-trying the routine which reads in the Excel data. The example I have is where a column is formatted to accept dates but in fact has cells containing the words "Yes" or "NO". When the method ExcelToPHPObject the class PHPExcel_Shared_Date (vendor\phpoffice\phpexcel\Classes\PHPExcel\Shared\Date.php) attempts to create a DateTime object on line 168.

$dateObj = date_create('1-Jan-1970+'.$days.' days');

The $days variable does not contain a valid value and $dataObj is set to false. This generates a fatal error with all the difficulty of adding some handling code to the App\Exceptions\Handler class. A workaround is to test $dateObj to see if it is false and throw a plain old Exception like this:

            if($dateObj != false){
                $dateObj->setTime($hours,$minutes,$seconds);
            }else{
                throw new Exception("Suitable error message here...");
            }

This works well and the page where the user is attempting to import data from an Excel displays whatever message the developer wants to provide. However, I am very uncomfortable changing source code like this. Can you advise me how to handle fatal errors in this scenario. The Laravel application can't predict what kind of Excel file the user might attempt to read from and I would like a way of testing the file before reading it to avoid being caught out by fatal errors.



via Chebli Mohamed

vendredi 6 janvier 2017

laravel 5.1: get relation in with

I have a model called user with relation "travel" model and travel model with relation "destination"

how can I get user in eloquent with travel and relation.

I know that I can get travel like this :

    $row = $this->model
        ->find($reqId)
        ->with('travel')
        ->first();

I want get destination of travels .



via Chebli Mohamed

Laravel factory specifying column twice

I'm using factories for unit testing and so far I haven't had any problems until now:

// This is the factory definition (note: other fields removed for brevity).
// Primary key is not included just like Laravel's docs show.
$factory->define(Media::class, function (Faker\Generator $faker) {
    return [
        'id_media' => $faker->unique()->randomNumber(6),
        'type' => $faker->randomNumber(1)
        // other irrelevant fields
    ];
});


 // This is how I call it on my unit test
 $count = 5;
 $id = 3;
 factory(Media::class, $count)->create([
      'id_media' => $id
 ]);

The problem is that this generates invalid SQL (id_media is there twice):

INSERT INTO media (id_media, type, id_media) VALUES (73052, 2)

If I don't override the id_media property when I call it in my unit test, then the query is valid but it's not what I need. Two things that strike me as odd are:

  • I'm using this all over my tests but the only time invalid SQL is generated is with this factory. I've got around two dozen factories in my app and this is the only problematic one. This particular table has one primary key and no other indexes. The table is as vanilla as they come.
  • This is actually recommended in the Laravel docs. I'm not doing anything out of the ordinary.


via Chebli Mohamed

mode rewrite issue laravel 5.1

sorry for asking a question but it drives me crazy i'm working a week on this issue but i haven't found a solution, i have a website with two languages , exp( de ,en ) i wanted to disable and enable this option in a panel and my RewriteRule applies the both conditions ,

for example if i have "localhost/test/en/admin" working this url works as well "localhost/test/admin"

so i edited my htaccess file in my root directory (note: i don't use public directory i use an index file inside of my root directory)

i have two htaccess files one in my root directory one in my public directory

and roots are as below

root:

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ public/$1 [L]

</IfModule>

public:

 <IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # 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]

ok , when i load http://localhost/test/ everything is good , i have my stylesheets everything

but when i use http://localhost/test/en everything that contains urls broke , my domain name removes from my "url" helper function and instead when i call App::getLocale(), the return value is my domain name instead of my lang var!

//+++++++++++++++++++++++++++++++++++++++++++++++

this is my previous htacess file for my root directory

root:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [L]

and i had this issue every url would map to index.php and i coudnt handle it with 404 error

for example "localhost/test/en" was a valid url and "localhost/test/foo" was a valid url just showing my index page of site ! and i coudnt handle a url without lang code ,

"localhost/test/en/foo" would get 404 error but "localhost/test/foo" just the index page

i'm very confused and i dont know how to handle this , thanks in advance



via Chebli Mohamed

How can I change the language of errors in laravel 5.1 dynamically

I have been using the helper

app()->setLocale(session('lang'));

However, I can get to change the languages of views but the languages of errors still continues reading of

\config\app.php locale => ‘es’

That means that always show the same language.

How can i change it also dynamically?

enter image description here



via Chebli Mohamed

jeudi 5 janvier 2017

Laravel Model not retrieving data

Im using laravel to pull some log information from a database, but all of a sudden its stopped working, as in its not retrieving data and not returning anything. Im using vuejs to retrieve the data without page refresh, theres no problem on the front end because data can still be retrieved also in the chrome debug console its displaying as a 500 error.

Furthermore what i find weird is it works locally but not in production.

Example code of what works and what doesn't

 <?php

namespace App\Http\Controllers;

use App\Log;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class LogController extends Controller
{

    public function getLogData()
    {

          //This is the original code & it doesn't work in production! 
          //$data = Log::orderBy('id', 'DESC')->select('action', 'object_id', 'ip_address', 'user', 'time', 'date')->get();

        //This works! But only retrieves 1 row of information
        $data = Log::where('id', 1)->get();

        $data = str_replace('*', "<b>", $data);
        $data = str_replace('^', "</b>", $data);

        return $data;
    }

}

and heres the logs model, which shouldnt really affect anything but entering data into the database really but just incase anyone needs this information.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    protected $fillable = ['action', 'object_id', 'object_type', 'ip_address', 'user', 'time', 'date'];
}

Any help i get will be appreciated.



via Chebli Mohamed

mardi 3 janvier 2017

Find inside comma separated values field Laravel 5.1

need to check if a variable is present inside a comma separated string in mysql field using querybuilder. I do this

                          <?php $parents = DB::table('categorie')->whereRaw('FIND_IN_SET("$categoria->id", parent)')->get();                            ?>

but didn't return any value... Any idea?



via Chebli Mohamed

lundi 2 janvier 2017

Using Laravel what is the correct way to store menu item's phrases?

I am trying to use languages with Laravel 5.3.

I have a menu named gender that shows the user two options "i.e 'Male' and 'Female'".

I want to add the phrases 'Male' and 'Female' to the language file.

What is the correct way to store menu item's translation with Laravel?

I did the following

'gender_male' => 'Male',
'gender_female' => 'Female'

But then notices that that Laravel has "what I believe it to be" nested phrases. Here is an example from the code that is shipped with the Framework

'same'                 => 'The :attribute and :other must match.',
'size'                 => [
    'numeric' => 'The :attribute must be :size.',
    'file'    => 'The :attribute must be :size kilobytes.',
    'string'  => 'The :attribute must be :size characters.',
    'array'   => 'The :attribute must contain :size items.',
],

Should my language file then look like this instead? and if so how to I access I read it?

 'gender' => [
    'male' => 'Male',
    'female' => 'Female'
 ]



via Chebli Mohamed