mardi 31 mai 2016

Model pivot not attaching properly after detaching all

I have a custom developed user/roles functionality with a roles table and a user_roles intermediate table. The user_roles table also has some additional data.

Lets suppose a user currently has 1 role assigned to him, and i have to assign 2 more roles to this user. Mostly i just detach all pivot enteries for the user, and then add all 3 roles again. This simplifies things and i dont have to check the json data for duplicate enteries. Something like this.

$user->roles()->detach();

This works fine and all the user pivot entries are removed. But when i attach all 3 roles again to the user, only the new ones are added. This is really weird and have been trying to debug it for a few hours now.

I loop through all 3 roles and i made sure that the loop is actually receiving this data properly.

$apps = json_encode(array('app1','app2'));
$user->roles()->attach($roleId, ['apps' => $apps]);

I remember that i faced a very similar issue earlier on another project as well, but dont remember the solution. Any help would be appriciated.



via Chebli Mohamed

Why isn't my "from" working sending email in Laravel?

I'm trying to send a very basic email in Laravel but the from field is not working. Instead of it being from the sender with their return address, it has MY return address and their name.

My .env has

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=chris@listingnaples.com
MAIL_PASSWORD=mypass;
MAIL_ENCRYPTION=tls

My controller has:

public function sendEmail(ShowingPageContactRequest $request) {

// email me custom email
$data = $request->all();

Mail::send('emails.propertyemail', $data, function ($message) use ($data) {
    $message->subject('Property Query from ' . $data['name'])
            ->sender($data['email'], $data['name']) 
            ->from($data['email'], $data['name'])   
            ->to('chris@listingnaples.com')
            ->replyTo($data['email'], $data['name']);
});

}

A dd($data) shows:

array:6 [▼
  "_token" => "ZSvuhAhkCetDFZOrQMtbDHBy2RfzECGFT03wixt3"
  "MLSNumber" => "216003681"
  "name" => "John Doe"
  "email" => "jdoe@gmail.com"
  "phone" => "(239) 555-1212"
  "comments" => "This is my comment or question."
]

So the email is there and John Doe is there. However, when I check my email it says it is from John Doe but chris@listingnaples.com!

My mail config file even has:

'from' => ['address' => null, 'name' => null],



via Chebli Mohamed

Laravel 5.1 ajax get requests takes drastically longer time to load the page

I am using laravel 5.1 and i want to make ajax get request calls as its a admin dashboard.

I am using DB queries for my response return and getting the data on the tables and graph using ajax, since i have dates filter and other filters.

My app is getting too slow to load when i click on apply button which makes different types of request on the page.

So this is what i am doing.

  $data = DB::table("leads")
->select((array(DB::Raw('DATE(leads.created_at) as creation'), 
DB::Raw("COUNT(leads.id) as total_leads"), DB::Raw("leads.id as id"),DB::Raw("leads.customer_name as customer_name" ),DB::Raw("leads.city as city"), DB::Raw("leads.email as email"),DB::Raw("leads.contact as contact"),DB::Raw("leads.source as source"),DB::Raw("leads.campaign_name as campaign"),DB::Raw("leads.ad_group as ad_group"),DB::Raw("leads.ad as ad"),DB::Raw("leads.keyword as keyword") )))
->where("leads.created_at",">=",$startDate)
->where("leads.created_at","<",$endDate)
->groupBy("leads.created_at")
->orderBy("leads.created_at","desc")
->get();

 return view("dashboard",compact("data"));

Now if i use this this query to get the ajax call, which look like this

  $(document).ready(function(){
  $(".applyBtn").on("click",function(){

  var i = $('input[name="daterangepicker_start"]').val();
  var e = $('input[name="daterangepicker_end"]').val();
  console.log(i);

  console.log($("input[id=daterangepicker_start1]").val($('input[name="daterangepicker_start"]').val()));
    console.log($("input[id=daterangepicker_end1]").val($('input[name="daterangepicker_end"]').val()));
  var data = "daterangepicker_start="+i+"&daterangepicker_end="+e;
  $.ajax({
    type:"GET",
    data:data,
    url:'',
    success:function(data)
      {
    $("#ack").html(data);

      }
  })

I am returning another blade template to replace the div ack.

This thing works great in localhost and its working quite faster than its loading on the server,but when i loaded this on linode server, this queries get too slow to work. I have installed the debugbar and it says 400 ms for loading all the queries. Can there be any configuration problem on the server, since its using apache as it was configured before only.

I have too many DB queries on the several pages, say dashboard,leads page.

What should i need to do for optimizing my laravel5.1 app, and how can i serve it easily using ajax.

Please let me know any solutions ,so that the loading request made by ajax take less time to load the other blade template which pulls the data view.



via Chebli Mohamed

is it possible for gulp to have output path outside project

for example i have my laravel project which has this kind of structure

./
--assets
----postcss
------style.css

i want to output that style.css outside app folder(one level above root). Is that possible(i'm running elixir)



via Chebli Mohamed

Laravel 5.1 - Checking if the date expired

i'm doing an ecommerce, i created:

-Session "cart" with all products attributes ( price, id, quantity, category etc)

-CouponController.php

public function postCoupon(Request $request)
    {

        $cart = \Session::get('cart');

        $mytime = Carbon\Carbon::now(); // today

        // i check if code coupon exist into my DB

        $coupon = Coupon::where('code', $request->get('coupon'))->first();

        if (!empty($coupon) && $coupon->expire_date ) {


            // i need check IF coupon exist AND date not expired --> i will put a new price into my session cart products.  

        }

    }

Model Coupon.php

protected $table = 'coupons';

    protected $fillable = [

    'code', // code of coupon
    'price', // price discount
    'expire_date', // expire date of coupon

    ];

MY QUESTION

I would like:

  1. Check with my CouponController if the code coupon is expired or not
  2. If expired return a simply message "Coupon invalid"
  3. If Coupon code exist into my DB and NOT expired, i need create a new variable with price value of coupon , for example "$discount = Coupon->price", so i can pass my discount price to my checkout view.

How can i do this ?

Thank you for yout help! ( i read something about carbon, but i dont undestand fine)



via Chebli Mohamed

Big file upload error - Laravel 5.1

I have an error while uploading file bigger than upload_max_filesize in php.ini I ahve an error FileNotFoundException in MimeTypeGuesser.php line 123: The file "" does not exist

enter image description here

I am trying to resolve this by using this

`ini_set('memory_limit', '128M');
 ini_set('upload_max_filesize', '500M');
 ini_set('post_max_size', '800M');`

But could't solve my problem.



via Chebli Mohamed

lundi 30 mai 2016

Send email in other gmail laravel 5.1

How to setting in mail, if send email for other gmail. because send email to gmail success, but send to other email error. How setting can send all email type.



via Chebli Mohamed

Laravel 5.1 - Blade Count total quantity products

I have a session "Cart" with more one products, each product have more one quantity in my cart session. I would like show in my header menu the total quantity. How can i count and show total quantity with blade ? Or there a is better way?

My header menu show a list dropdown with all products in my session cart like this

principal.blade.php ( it work well)

 @foreach (session()->get('cart') as $item)
  
  
  
@endforeach 

I would like show the total quantity of all my products! thank you for your help!



via Chebli Mohamed

Laravel 5.1 Date Time from today

My javascript client generates a date in the following format:

2016-05-26T07:00:00.000Z

How do I calculate a year from now? I have tried using DateTime::add but had no luck. Any suggestions?

http://ift.tt/1pGLoWa



via Chebli Mohamed

Complicated array to excel in Laravel

I have two tables which I want to join and create an Excel .

event_invoice

columns

id
name
invoice_value
invoice_date

invoice model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    //
     protected $table = 'event_invoice';
     protected $primaryKey = 'Id';

    /*
     * An invoice can has many payments 
     *
     */

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

}

invoiceduedate columns

id
invoice_id
date
amountin

duedatemodel

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class invoiceduedates extends Model
{
     protected $table = 'invoiceduedates';


}

So one invoice can have many duedates

I want to display in excel in this format

| name | invoice_value | invoice_date | due date1  | due amount1 | due date2  | due amount2 | due date3  | due amount3 |
|------|---------------|--------------|------------|-------------|------------|-------------|------------|-------------|
| A    | 5000          | 30-01-2016   | 15-01-2016 | 2500        | 30-01-2016 | 04-11-1906  | null       | null        |
| B    | 8000          | 02-05-2016   | 15-02-2016 | 8000        | null       | null        | null       | null        |
| C    | 10000         | 03-05-2016   | 15-05-2016 | 5000        | 19-05-2016 | 2500        | 19-05-2016 | 2500        |

Any help would be appreciated

Thanks



via Chebli Mohamed

How to use join in Laravel Elocuent?

I have following two tables.

users - id,name,title
posts - id,author

where post.author = user.id

My Post model as follows.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function users()
    {
       return $this->belongsTo('App\User');
    }
}

I use Project::find(1)->users

But it giving following error.

SQLSTATE[42S02]: Base table or view not found.

Can anyone please help ?



via Chebli Mohamed

Laravel 5.1: How to pass HTML Body and Text Body without using view?

I'm trying to send emails in laravel5.1 and found that Mail:Send used view templates like below:

Mail::send(['html.view', 'text.view'], $data, $callback);

Problem is I have my ready to send HTML body and TEXT body are coming from database. How to set html view and text view if content coming from database like below:

$html_body = $row['Html_Body']; // holds html content
$text_body = $row['Text_Body']; // holds text content

Thanks.



via Chebli Mohamed

dimanche 29 mai 2016

Laravel 5.1 DB:select toArray()

I have a large SQL statement that I am executing like so..

$result = DB::select($sql);

I'd like the result to be an array - but at the moment it returns a structure like so, an array with Objects...

Array
(
    [0] => stdClass Object
    (
        [field] => 6
    )
...etc...



via Chebli Mohamed

Laravel 5.1 - Show my session cart

to show in header menu my products of my cart session, I'm passing the session "cart" from my controller to my view, like this:

FrontController:

public function index()
    {
        $cart = \Session::get('cart');

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

Routes.php

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

my layout principal.blade.php ( it work well)

@foreach ($cart as $item)

all items of my session cart

@endforeach

MY QUESTION:

there is a way to pass the cart session directly to all my views?? OR I must always pass the cart Session for each view ? i have about 24 views, i must do each view like my view homepage index.php ??

Thank you for your help!



via Chebli Mohamed

How to compare last 2 elements of an array?

I have an array:

array:8 [▼
  0 => array:1 [▼
    "data" => "789"
  ]
  1 => array:1 [▼
    "data" => "800"
  ]
  2 => array:1 [▼
    "data" => "789"
  ]
  3 => array:1 [▼
    "data" => "787"
  ]
  4 => array:1 [▼
    "data" => "787"
  ]
  5 => array:1 [▼
    "data" => "787"
  ]
  6 => array:1 [▼
    "data" => "787"
  ]
  7 => array:1 [▼
    "data" => "787"
  ]
]

I need to take out the last 2 elements of the array and compare them. I tried using $getLast2 = array_slice($chart_data, -2, 2, true); to get the last 2.

array:2 [▼
  6 => array:1 [▼
    "data" => "787"
  ]
  7 => array:1 [▼
    "data" => "787"
  ]
]

Which then splits it. But Im not sure how to compare these 2 elements within this new array. As the last 2 elements which are now 6 and 7 could change as more data is added. I basically need to tell if the first element is great than, less than or equal to the second element.



via Chebli Mohamed

Laravel5.0/5.1 application deployment error

When I transfer my laravel5.1 application to the server the following error occurs

Internal Server Error.
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, ectlink@gmail.com and inform them of the time the error occurred, 
and anything you might have done that may have caused the error. 
More information about this error may be available in the server error log.

Application Version Apache version: Apache/2.2.31 PHP version: 5.6.14 MySQL version: 5.1.73

System Info Distro Name: CentOS release 6.7 (Final) Kernel Version: 2.6.32-573.18.1.el6.i686 Platform: i686



via Chebli Mohamed

samedi 28 mai 2016

laravel5 did not show php image in controller or route

I use laravel with version 5.1.35, but i found it not show image which write by php raw code. The code in raw php is

header("Content-type: image/png");
$im = @imagecreate(200, 50) or die("create php image rs error");
imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, "Hello world!", $text_color);
imagepng($im);
imagedestroy($im);

output of php is hello world

but in laravel 5.1.35 in route define is

Route::get('png',function(){
//  echo \Image::make(public_path('assets/image/xundu/logo.jpg'))->response('png');
    header("Content-type: image/png");
    $im = @imagecreate(200, 50) or die("create php image rs error");
    imagecolorallocate($im, 255, 255, 255);
    $text_color = imagecolorallocate($im, 0, 0, 255);
    imagestring($im, 5, 0, 0, "Hello world!", $text_color);
    imagepng($im);
    imagedestroy($im);
});

Output of it is php raw code display in laravel



via Chebli Mohamed

Laravel 5.1 application deployment

I have developed an application with Laravel5.1. Now I need hosting suggestion for deploying my application. I know it's a silly question but I want a reliable answer. Before buying a hosting I want to know which hosting service will provide proper environment to run a laravel5.1 application. Php version required >= 5.5.9



via Chebli Mohamed

What model and what events are happening in Laravel 5.1?

How does one determine what model and what events happened ? For example When delete and update model news and events happening and how can it be managed?



via Chebli Mohamed

Is there anyway to code such that I can define or condition in middleware?

I have three roles in my application. I have a condition in which two roles can access same page. For that I write below code.

in below code, sub plan1 and sub plan 2 are roles.

Route::group(['middleware' => ['web', 'auth', 'SubPlan1', 'SubPlan2']], function () {
    Route::get('/Parent-1-Info', '\ContactInfoController@Parent1Info'));
});

if sub plan1, tries to access the page, I get 404 error because i mentioned both middleware in same group.

Is there anyway to code such that I can define or condition in middleware?



via Chebli Mohamed

Laravel 5 Route::group with public variable

I have some code like this:

Route::group(['prefix'=>'dashboard'],function(){        
    Route::get('addnew',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.load')->with($data);
    });
});

But it don't work when i use public variable like this:

Route::group(['prefix'=>'dashboard'],function(){

    $user = DB::table('users')->where('username','=',session('username'))->first();
    $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);

    Route::get('addnew',function(){        
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){        
        return view('layout.load')->with($data);
    });
});

Help me please!



via Chebli Mohamed

getTokenForRequest always returns null in Laravel 5.2.31

I am working on API in Laravel. My route is below.

Route::group(['prefix' => 'api/v1', 'middleware' => 'auth.api'], function () {
    Route::get('/DownloadMedia/{MediaID}', 'MediaController@DownloadMedia');
});

In below file

\vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php

Method: getTokenForRequest() always returns Token value = null

when I started the debugging and printed the value of dd($this->request);

I get below values.

enter image description here

Here is problem is why getTokenForRequest() is always null?

bearerToken() and $this->request->input($this->inputKey) and $this->request->getPassword() all are null

Can you explain why this is null?

My Url is below

http://ift.tt/1TLmdxo



via Chebli Mohamed

How to use instagram api with guzzle 6+ and laravel?

Im trying to convert this url http://ift.tt/1TLcGWX

Into something I can use with guzzle. So far I've got:

$token = "123456789";    
$client = new \GuzzleHttp\Client();
    $res = $client->request('GET', 'http://ift.tt/1PQwoOc', [
        'access_token' => $token
    ]);
    echo $res->getStatusCode();
    // 200
    echo $res->getHeaderLine('content-type');
    // 'application/json; charset=utf8'
    echo $res->getBody();
    // {"type":"User"...'

but I just get an error that reads:

Client error: `GET http://ift.tt/1PQwoOc` resulted in a `400 BAD REQUEST` response:
{"meta": {"error_type": "OAuthParameterException", "code": 400, "error_message": "Missing client_id or access_token URL (truncated...)



via Chebli Mohamed

vendredi 27 mai 2016

laravel 5.1 : how can i get nested relation from model?

I have a question about laravel model relations and use them in eloquent class . my question is this :

I have a model like this :

class TransferFormsContent extends Model
{

 public function transferForm()
    {
        return $this->belongsTo('App\TransfersForms','form_id');
    }
}

and in transferForm i have other side for this relation like this :

  public function transferFormsContent()
{
    return $this->hasMany('App\TransferFormsContent', 'form_id', 'id');
}

also in transferForm i have another relation with employee like this :

class TransfersForms extends Model
{
     public function employee()
        {
            return $this->belongsTo('App\User','employee_id');
        }
}

now if I want get a record from "TransferFormsContent" with its "transferForm " provided its with employee. how can i do this?

i now if i want get "TransferFormsContent" with only "transferForm " i can use from this :

 $row = $this->model
            ->with('transferForm'); 

but how about if i want transferForm also be with its employee?



via Chebli Mohamed

How to get uri address of a nested resources using vue js and laravel

I am having problem fetching the uri of a nested resource when using vue js. See below code.

ReservationController.php

public function index($id)
    {   

        $student = Student::with(['sectionSubjects','sectionSubjects.section', 
                    'sectionSubjects.subject'])->findOrFail($id);

        return $student->sectionSubjects;   

    }

all.js

methods:{

        fetchSubjects: function(){
            var self = this;
            this.$http({
                url: 'http://localhost:8000/reservation/id/student',
                method: 'GET'
            }).then(function (reservations){
                this.$set('reservations', reservations.data);
                console.log('success');

            }, function (response){
                console.log('failed');
            });
        }
    }

The problem here is, getting the value of the id of this url http://localhost:8000/reservation/id/student. Is there a way to get the id of the parameter of the index() method? Also here's my route list http://ift.tt/25q6BYA



via Chebli Mohamed

Redirecting to view files

just wanted to firstly note is that this works fine when I have the redirects within their own retrspective functions. Essentially, I create a Project. Within a Project I can make many types of Documents. Relationships are all set up appropiately.
So within a Project I have links to different documents which can be created. These are like

<li>{!! link_to_route('projects.document.create', 'Some Document',  array($project, 'someDocument')) !!}</li>

The route is like this

Route::get('projects/{projects}/document/{name}', array('as' => 'projects.document.create', 'uses' => 'DocumentController@create'));

And then in my DocumentController I do this

public function create(Project $project, $name)
{
    $this->redirectResult($project, $name);
}

The redirectResult function essentially checks to see if the selected document (in this case someDocument) has been created before (A project can have many documents, but only one of each type). If the document has never been created for the project, it shows the create view for that document. If it has been created before it shows the edit view. This is the function

public function redirectResult(Project $project, $name) {
    $selectedDoc = Document::where('project_id', '=', $project->id)
        ->where('name', '=', $name)
        ->first();

    if(!$selectedDoc) {
        return View::make($name.'.create', compact('project'));
    }
    else {
        return View::make($name . '.edit', compact('project', 'selectedDoc'));
    }
}

Now when I select a document, I end up on a blank page. The url is correct, no errors or anything, simply a blank page. The strange thing is when I do it the old way (which should act the same as the above) it works. The old way is exactly the same as above, but my create function is like this instead

public function create(Project $project, $name)
{
    $selectedDoc = Document::where('project_id', '=', $project->id)
        ->where('name', '=', $name)
        ->first();

    if(!$selectedDoc) {
        return View::make($name.'.create', compact('project'));
    }
    else {
        return View::make($name . '.edit', compact('project', 'selectedDoc'));
    }
}

So the only different is that the view making code is directly within the function, rather than calling a function that has this code. I wanted to put all this repeat code in its own function so I do not have to repeat it for every document controller function.

Is there any reason why my new way takes me to a blank page? Just to rule out the obvious, I do have the folders containing the view files set up correctly. So for the above example within the views folder I have a folder called someDocument and within it I have edit.blade.php.

Any information as to why this might be occuring appreciated.

Thanks



via Chebli Mohamed

Internet not available exception in Laravel 5.2

I was trying to open Sandbox paypal page from my Laravel application and faced below issue

enter image description here

This issue came because internet connection was not available. Like we face 404 issue...for that we have 404 blade in View folder.

Is there any way to handle this exception so that we can show a user friendly page to user that Please check your internet connection



via Chebli Mohamed

Replace words in HTML string by spans with title, except within certain tags

I looked around anywhere but I did not find a decent solution for this.

I have an HTML string:

$html = "<p>This an example string with a <a href="/link/to/example" title="Title to example">link</a> and an <img src="path/to/example-image.jpg" alt="Alt text from example image"></p>"

I have an array:

$glossary = array(
    "example" => "<span class='tooltip'>This is the explanation</span>"
    ...
)

What I try to achieve is to replace the string 'image' in the html string without changing it in the IMG and A elements, basically all the elements in the exclude array:

$excludes = array('img','a',etc)



via Chebli Mohamed

jeudi 26 mai 2016

How to get parameter of create method and acces it to the index method using laravel controllers

I am having problems getting the value of custom create method. What I want is to get the variable $student_id and place it on my findOrFail() in the index method as shown below:

ReservationController.php

public function index()
{

    $student = Student::with(['sectionSubjects','sectionSubjects.section', 
                'sectionSubjects.subject'])->findOrFail(1); //$student_id

    return $student->sectionSubjects;    

}

public function create($id)
{
    $student_id = $id;

    $subjects = Subject::with('sections')->get();

    return view('reservation.form',compact('subjects','student_id'));
}

Here's my route:

Route::resource('student', 'StudentController');
Route::resource('reservation', 'ReservationController', ['except' => ['create','show'] ]);

Route::get('reservation/{id}/create', 
    ['as' => 'reservation.create', 'uses' => 'ReservationController@create'
]);

I have this form.blade.php that when a user click on a student it will be redirected to the custom create method in the ReservationController as seen below:

<div class="list-group ">
@inject('student', 'App\Http\Controllers\StudentController')
    @foreach($student->index() as $s)
        <div class="list-group-item">
            <h4 class="list-group-item-heading">
                  </i>
            </h4>
            <h5>
               ID No.: </i>
            </h5>

           <a href="" class="btn btn-xs btn-primary">Edit Info</a>

           <a href="" 
              class="btn btn-xs btn-danger">
              Enroll
            </a> 

        </div>
    @endforeach

</div>

Now in the index method in the ReservationController, I want to fetch only values that are related to that $student_id. However, I cannot figure out to achieve this. Can anyone suggest ways to solve this?



via Chebli Mohamed

Route is not found -logout

I am trying to click on logout button, but it returns an error:

NotFoundHttpException in RouteCollection.php line 161:

There's no getLogout in Authcontroller, and it worked before, not sure why now it isn't.

AuthController:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

        use AuthenticatesAndRegistersUsers, ThrottlesLogins;
        protected $redirectTo = "dashboard";
        protected $loginPath = 'auth/login';


    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * 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|max:255',
            'email' => 'required|email|max:255|unique:users',
            'username' => 'required|max:20|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

Routes.php:

Route::get('auth/logout', 'Auth\AuthController@getLogout');

view:

  <a href="auth/logout">Logout</a>



via Chebli Mohamed

How to get Form Submission to work properly in Laravel?

enter image description hereI'm working on this simple form and trying to submit it. Basically I created an array of users in my homeController which then renders its data in the home.blade.php file (That part works fine). However when I try to submit the form I get an error that says: Undefined variable: usersArray Can anyone tell me what I'm doing wrong please? thank you so much in advance.

Here's my HomeController which has the values for my usersArray:

public function home()
{
    $usersArray = array();
    $usersArray[0] = "Mike" . " "."Brown" . " " . "3032023245";
    $usersArray[1] = "Michael" . " " . "Smith" . " ". "7204506534";
    $usersArray[2] = "Lauren" . " ". "Barl". " ". "7202314687";

    return view('home', [
        'usersArray' => $usersArray
    ]);
}

Here's my home.blade.php:

{!! Form::open(array('id' => 'activateForm')) !!}

{!! csrf_field() !!}

<div>

<!---Error messages inside of box-->
<div style="padding-left: 135px; width:815px;">

    @if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul class = "login-error-messages" style = "list-style-type:disc;">
            @foreach ($errors->all() as $error)
            <li>{!! $error !!}</li>
            @endforeach
        </ul>
    </div>
    @endif
</div>

<div class="home-rounded-border  center-content">
        <input type = "checkbox" id = "checkAll" />Select All<span style="padding-left: 310px;font-weight: bold;">Email</span><br/>
        @foreach($usersArray as $key => $value)
        <ul>
            <li>
                <input type="checkbox" id="checkboxUser" name="user-name-checkbox ">
                <input type = "email" class="styled-text  rounded" name = "name" id = "customer-name-inputField}}" placeholder=""/><br/><br/>
            </li>
        </ul>
        @endforeach

    <center><input type = "submit" class="sign-in-button"value = "Submit"/></center>

    </br>
    <div id="statusMsg" style="margin: 0px 40px 0px 40px; background-color: #ffffff;"></div>

    <ul><li class="logout"><a href="logout"><span>Logout</span></a></li></ul>

</div>

<br/><br/>
 </div>
 {!! Form::close() !!}



via Chebli Mohamed

Laravel 5.1 - store foreach session in my Database

Hi i'm doing a ecommerce, and i have problem to store my session cart updated in my table CartItems, when user add product my controller put all information in my session "cart"

i created a product_session = category+productID+color+size, so i can difference between other products variations.

My problem is that after updated Session "cart" (it work good) i need update my table "CartItems" with all products of my session cart. I dont why my controller update only the last added product in cart session.

My controller CartController.php

public function add(Product $product, CartSession $CartSession,Request $request)
    {
        $id = $request->get('id');
        $cart  = \Session::get('cart'); // ricevo la var di sessione cart e la salvo su cart



        foreach($cart as $producto){

                $product_exist = $producto->id;
        }

        if(isset($product_exist)) {


                if($product_exist == $product->id 
                    && $producto->color != $request->get('color')    
                    || $producto->size != $request->get('size') ) {


                    $product->quantity = $request->get('qty');
                    $product->size = $request->get('size');
                    $product->color = $request->get('color');
                    $product->category = $request->get('category'); 
                    $cart[$product->category.$product->id.$product->size.$product->color] = $product;
                    \Session::put('cart', $cart);   

                    //return $cart;

                }

                if($product_exist == $product->id 
                    && $producto->color == $request->get('color')    
                    && $producto->size == $request->get('size') ) {


                    $product->quantity = $request->get('qty')+$producto->quantity;
                    $product->size = $request->get('size');
                    $product->color = $request->get('color');
                    $product->category = $request->get('category'); 
                    $cart[$product->category.$product->id.$product->size.$product->color] = $product;
                    \Session::put('cart', $cart);

                } // fine if 
        }else {// fine if isserT, Se non ci sono prodotti già esistenti


                    $product->quantity = $request->get('qty');
                    $product->size = $request->get('size');
                    $product->color = $request->get('color');
                    $product->category = $request->get('category'); 
                    $cart[$product->category.$product->id.$product->size.$product->color] = $product;
                    \Session::put('cart', $cart);   

        }
        //return $cart;
        $subtotal = 0;

        foreach($cart as $producto){
            $subtotal += $producto->quantity * $producto->price;
        }   

        $session_code = Session::getId();
        //$CartSession = new CartSession();

        $session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();

        if (isset($session_exist)) {


                $s = new CartSession;

                $data = array(

                'subtotal' => $subtotal,

                );

                $s->where('session_code', '=', $session_code)->update($data);


        }else {

                $CartSession = new CartSession();
                $CartSession->session_code = $session_code; 
                $CartSession->subtotal = $subtotal; 
                $CartSession->save(); 
        }


        foreach($cart as $producto){
            $this->saveCartItem($producto, $CartSession->id,$cart);
        }

        return redirect()->route('cart-show');


    }

    protected function saveCartItem($producto, $CartSession_id,$cart)
    {

            $session_code = Session::getId();

            $get_items = CartItem::where('session_code', $session_code);

            $deleted=$get_items->delete();

            $get_id = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();


            $CartItem = new CartItem();
            $CartItem->price = $producto->price;
            $CartItem->quantity = $producto->quantity;
            $CartItem->size = $producto->size;
            $CartItem->color = $producto->color;
            $CartItem->category = $producto->category;
            $CartItem->product_session = $producto->category.$producto->id.$producto->size.$producto->color; 
            $CartItem->product_id = $producto->id; 
            $CartItem->session_id = $get_id->id;
            $CartItem->session_code = $session_code; 
            $CartItem->save(); 


    }

the process that i'm doing on method saveCartItem is:

  • Get all items products that have the same session and delete them
  • Store the products of my session $cart ( these new data is updated with all products added, quantity changed, ecc )

Actually my controller delete products that have the same session and store only the last product added and NOT all products in my session cart. enter image description here enter image description here



via Chebli Mohamed

MSSQL guid to string

I'm using Laravel 5.1 on Ubuntu PHP5.6 and the GUID to string conversion is working just fine. However on my development environment in PHP 7 it's pritining out like how it used to when I had to use the old mssql driver that came with php.

So all my string comparisons are failing on 7 for GUID's saved in mysql.

My gut says that some PDO setting that's not being set correctly. The query in question is using the DB class to fetch data through a raw sql. I think Eloquent is rendering correctly, I've not seen this problem before and I've been using it throughout (this is an older code base before I leaned additional tricks I currently use to work with this database)

Any ideas where I can start looking.



via Chebli Mohamed

Don't change slug on update (In Laravel Model)

I have a model called Oglas with which I create rows in table. It creates a unique slug for that row, but whenever I update that row it generates new slug. So when someone shares a post, then edit, that shared post doesn't exists anymore because slug is changed.

Here is code Oglas:

    class Oglas extends Model
    {
        protected $table = "oglasi";
        protected $guarded = ['id'];

        public function uniqueSlug($title) {
            $slug = str_slug($title);
            $exists = Oglas::where('slug', $slug)->count();

            if($exists > 0)
                $slug .= "-" . rand(11111, 99999);

            return $slug;
        }

        public function setNazivAttribute($value) // In table i have "naziv" column
        {
            $this->attributes['slug'] = $this->uniqueSlug($value); // I do not want this to fire if post is edited.
            $this->attributes['naziv'] = $value;
        }



}

To summarize: When creates new post fire that slug creation, when updating (editing) don't fire, don't change slug.



via Chebli Mohamed

Best practice for show data inside Laravel view

What is the best practice, for example to show user data?

  1. Retrieve user in show function inside UserContoller, and pass user variable to the view?

  2. Return view in show function, passing the $user_id, and retrieve the user on the view?

Example 1:

public function show($id)
{
    $user = User::findOrFail($id);
    return view('config.users.show')->withUser($user);
}

Example 2:

public function show($id)
{
    return view('config.users.show')->withId($id);
}



via Chebli Mohamed

Error opening Laravel project after 30 minutes

I am getting errors when reloading the previously opened tab of my Laravel Project on my browser. There is no error on the page, I mean it loads correctly when I opened it half hour ago.

It shows this error.

The error says "Trying to get property of non-object"

4/4 ErrorException
Trying to get property of non-object 
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php)
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php)
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php) 

ADDED: Only suspicious code that might be causing problem on mainheader.blade.php is, I am using . But I am still confuse how I can Redirect this exception. What I thought was, it was due to error in session and token expiration, so I added this code to app/Exception/handler.php

if ($e instanceof \Illuminate\Session\TokenMismatchException) {            
    return redirect('error/403')->withErrors(['token_error' => 'Sorry, your session seems to have expired. Please try again.']);
}

But, that was not solved. Could you please so me the right way?



via Chebli Mohamed

How to set session array and retrive all value then insert into database in laravel 5.1?

I am trying to create a student payment system with laravel 5.1 . I need to keep month and fee in session and insert those to database . Anybody please help!!!



via Chebli Mohamed

Return value not string in php

I have a mail function in php that echoes a response. The browser's developer tool is showing the response as string, but when I capture that response in the front end, with a callback function, it is showing as a json object. So what is printed in the screen is

{"0":"A","1":" ","2":"t","3":"e","4":"m","5":"p","6":"o","7":"r","8":"a","9":"r","10":"y","11":" ","12":"p","13":"a","14":"s","15":"s","16":"w","17":"o","18":"r","19":"d","20":" ","21":"h","22":"a","23":"s","24":" ","25":"b","26":"e","27":"e","28":"n","29":" ","30":"s","31":"e","32":"n","33":"t","34":" ","35":"t","36":"o","37":" ","38":"y","39":"o","40":"u","41":"r","42":" ","43":"e","44":"m","45":"a","46":"i","47":"l"}

I have no idea why? I am using Laravel 5.1 and angularJS for the front end.

This is the code for the function

 if (Mail::send('test-view', ['pass' => $pass], function($message) use ($data)
    {
    $message->to('esolorzano@renovatiocloud.com', 'Tarzan de la Selva')->subject('Password Reset');
    })){
       echo "A temporary password has been sent to your email"; 
    }else {
        echo "There was an error sending the temporary password";
    }



via Chebli Mohamed

rtconner/laravel-likeable sort after number of likes

Using this package http://ift.tt/1t3Gj5g I want to do a sort of the articles after the number of likes. Any help is appreciated. Thank you!



via Chebli Mohamed

mercredi 25 mai 2016

Access variable from include in blade template in php

I have a blade template that includes other blade template. Here is the main template called accountnav.blade.php

@if (count($subaccounts) > 0)
   <ul class="nav navbar-nav">
       @foreach ($subaccounts as $account)
           @include('frontend.template.subaccount', array('p_link' => $account->link))
       @endforeach
   </ul>
@endif

and here is the included template titled subaccount.blade.php

<li >
        @if(count($account->children) == 0 )
            <a href=""></a>
        @else
            <a class="dropdown-toggle" data-toggle="dropdown" href="#" onclick="return false;" aria-expanded="false">
            
                <i class="icon-caret-down"></i>
            </a>
        @endif
    @if (count($account->children) > 0)
        <ul class="dropdown-menu">
            @foreach($account->children as $account)
                 @include('frontend.template.subaccount', array('p_link' => $account->link))
            @endforeach
        </ul>
    @endif
</li>

However, when I tried to access the variable p_link in the subaccount.blade.php, there is an error that says the variable $p_link is not defined.

What is the correct way to pass a variable in an @include and how to access the passed variable?



via Chebli Mohamed

Properly updating composer dependencies

I'm currently using Laravel 5.1.11, but looks like a feature I need is needed from 5.1.14. I haven't used composer for too long, but is there a proper way I should go about upgrading? And are there any caveats I should watch out for in general?

Both my composer.json and composer.lock file have Laravel at 5.1.11 explicitly. Would I increment those to 5.1.14 and then run composer install?



via Chebli Mohamed

Properly updating composer dependencies

I'm currently using Laravel 5.1.11, but looks like a feature I need is needed from 5.1.14. I haven't used composer for too long, but is there a proper way I should go about upgrading? And are there any caveats I should watch out for in general?

Both my composer.json and composer.lock file have Laravel at 5.1.11 explicitly. Would I increment those to 5.1.14 and then run composer install?



via Chebli Mohamed

Slugs with non-english letters

I have been using Laravel's Str::slug function and I realized that it doesn't create a slug at all if the user only submits non-english letters.

I have been Googling this for a while and I'm unable to find a solution.

Did any of you encounter this and found a fix?



via Chebli Mohamed

laravel inject css class to element in blade before render

I have a project in which developers can make blade templates and upload to that CMS, and I want to give admin the ability to add custom css classes to html elements inside that template without touching it.


What I want to achieve is extending blade compiler and read the dom elements and loop through them all and add the custom css classes if set then compile it as normal blade file. how can I get this approach?

Thanks.



via Chebli Mohamed

Laravel migrations on SQL Server use the data type NCHAR, how can I force it to use CHAR instead?

I've created a very simple migration, that creates a table with a FK referencing a column on an existing table. The problem is that the migration creates a NCHAR datatype column, while the referenced column is of CHAR datatype, so the FK can't be created because of different datatypes columns.

Is there any way to enforce Laravel to use CHAR instead of NCHAR?

Thanks!



via Chebli Mohamed

Laravel Output 1 result from hasmany relationship

I have a hasmany relationship on my model and I'm trying to output just the one result, i have a product category which can display only one product image.

I have two tables.

1 = Product
2 = ProductPhotos

I've tried outputting the one photo like

@foreach($products as $product)
<img src="">
@endforeach

I have the following relationship setup in my product model

public function photos()
    {
        return $this->hasMany('App\ProductPhoto', 'product_id');
    }

but this doesnt work.



via Chebli Mohamed

laravel 5.1 only routing to home page, all other routes are coming 404 not found error, after hosting the local working site to the server

I have pushed my laravel 5.1 application to server. In localhost, it works properly. but in server , only the home page is coming, no other routes working. I get 404 not found not found error. jQuery-2.1.4.min.js:4 POST http://mydomainurl/login/validate_login 404 . I feel, it should traverse to http://mydomainurl/applicationName/login/validate_login. I dont know whats happening and where i have to update. Please help.



via Chebli Mohamed

Query in Api Laravel

i want to make Api in there i want to show 2 table in this Api. but i get trouble in there :

this my Api Controller :

public function postDetaillog(Request $request){
        $response = array();
        $validator = Validator::make($request->all(),           
            [
            'id'=> 'required',
            ]
        );
        if ($validator->fails()) 
      {
        $message = $validator->errors()->all();      
        $result['api_status'] = 0;
        $result['api_message'] = implode(', ',$message);      
        $res = response()->json($result);
        $res->send();
        exit;
      }
        $data = DB::table('log_patrols')
        ->where('id', $request->input('id'))
        ->first();

        $site = asset("uploads").'/';
        $result= DB::table('log_patrol_details')
        ->select("*",DB::raw("concat('$site',photo1) as photo1"),DB::raw("concat('$site',photo2) as photo2"),DB::raw("concat('$site',photo3) as photo3"))
        ->where('id', $request->input('id'))
        ->first();

        if(count($result)==0) {
            $response['api_status'] = count($result);
            $response['api_message'] = "No data";
        }else{
            $response['api_status'] = 1;
            $response['api_message'] = "success";
            $response['data'] = $data;
            $response['result'] = $result;
        }
        return response()->json($response);
}

first table this the table second table second table

when ever i try to get the result, the result always get 0 = no data

this the result

have someone give me solution for me ?



via Chebli Mohamed

Obtaining pivot table data

I have a Users Model and within it I have the following relationship

public function group()
{
    return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('user_id', 'group_id');
}

I have also set the inverse within the Group model. When complete, I have a users_user_group table with data like so

+------+-------------------+----------+
| id   |           user_id | group_id |
+------+-------------------+----------+
|  755 |                 1 |        1 |
|  756 |                 1 |        2 |
|  757 |                 1 |        3 |
|  758 |                 1 |        4 |
|  759 |                 1 |        5 |
|  760 |                 1 |        6 |
|  761 |                 1 |        7 |
|  762 |                 1 |        8 |
|  763 |                 1 |        9 |
|  764 |                 1 |       10 |
|  765 |                 2 |       11 |
|  766 |                 2 |        7 |
|  767 |                 2 |       10 |
|  768 |                 3 |       12 |
|  769 |                 3 |       13 |

So I know the data is being inserted properly. Now within one of my controllers, I am trying to get all users who are part of the admin group, which has the group_id of 1. So I am doing $users = User::where('active', '=', true)->get();

foreach ($users as $user) {
    if($user->group()->where('groupName', 'admin')) {
        $groupArray[] = $user;
    }
}

For some reason though, every user is added to this array, where only the admins should be added.

I was just looking for advice as to what I am doing wrong? Do I need to link the groupName to the groupId somehow?

Thanks



via Chebli Mohamed

Using concat in laravel

iam trying to give url to my image, so i try to use concat. but in there i have trouble if the concat just use to 1 column i can make it. but is use 3 column, so i dont now how to do it ?

this is my controller :

$site = asset("uploads").'/';
        $result = DB::table('log_patrol_details')
        ->select("*",DB::raw("concat('$site',photo1) as photo1"))
        ->where('id_log_patrols', $request->input('id_log_patrols'))
        ->orderBy('id', 'desc')
        ->first();
        if(count($result)==0) {
            $response['api_status'] = 0;
            $response['api_message'] = "Belum ada data";
        }else{
            $response['api_status'] = 1;
            $response['api_message'] = "success";
            $response['items'] = $result;
        }
        return response()->json($response);

iam try to add concat to my photo1, photo2, and photo3

image



via Chebli Mohamed

mardi 24 mai 2016

Getting undefined values when adding a table data using vue js and laravel

I have this project that when a user clicks on a button the data should be displayed on a table. However, I am using a table as seen here http://ift.tt/1TkUqS1. What I want is that when a user clicks on the add button on the enrollment form table, it should displayed on the added subjects table without the need of refreshing the page. The problem is that I am using a table and I cannot make use of the v-model to bind the values.

So here's my form.blade.php

Enrollment Form table

<table class="table table-bordered">
  <tr>
    <th>Section</th>
    <th>Subject Code</th>
    <th>Descriptive Title</th>
    <th>Schedule</th>
    <th>No. of Units</th>
    <th>Room</th>
    <th>Action</th>
  </tr>
  <body>
    <input type="hidden" name="student_id" value="">
    @foreach($subjects as $subject)
      @foreach($subject->sections as $section)
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>
          <button 
              v-on:click="addSubject( ,  )" 
              class="btn btn-xs btn-primary">Add
          </button>

          <button class="btn btn-xs btn-info">Edit</button>
        </td>
      </tr>
      @endforeach
    @endforeach
  </body>
</table>

AddedSubjects Table

<table class="table table-bordered">     
    <tr>
      <th>Section Code</th>
      <th>Subject Code</th>
      <th>Descriptive Title</th>
      <th>Schedule</th>
      <th>No. of Units</th>
      <th>Room</th>
      <th>Action</th>
    </tr>

    <body>

    <tr v-for="reservation in reservations">
      <td>@</td>
      <td>@</td>
      <td>@</td>
      <td>@</td>
      <td>@</td>
      <td>@</td>
      <td>
        <button class="btn btn-xs btn-danger">Delete</button>
      </td>
    </tr>

    </body>
</table>

And here's my all.js

new Vue({
el: '#app-layout',

data: {

    reservations: []

},
ready: function(){
    this.fetchSubjects();
},
methods:{

    fetchSubjects: function(){
        this.$http({
            url: 'http://localhost:8000/reservation',
            method: 'GET'
        }).then(function (reservations){
            this.$set('reservations', reservations.data);
            console.log('success');
        }, function (response){
            console.log('failed');
        });
    },

    addSubject: function(section,subject,student_id){
        var self = this;
        this.$http({
            url: 'http://localhost:8000/reservation',   
            data: { sectionSubjectId: section.pivot.id, studentId: student_id },
            method: 'POST'
        }).then(function(response) {
            self.$set('reservations', response.data);   
            console.log(response);
            self.reservations.push(response.data);
        },function (response){
            console.log('failed');
        });
    }
  }
});

Here's my ReservationController

class ReservationController extends Controller
{

public function index()
{
    $student = Student::with(['sectionSubjects','sectionSubjects.section', 'sectionSubjects.subject'])->find(1);

    return $student->sectionSubjects;    

}

public function create($id)
{
    $student_id = $id;

    $subjects = Subject::with('sections')->get();

    return view('reservation.form',compact('subjects','student_id'));
}

public function store(Request $request)
{

    $subject = SectionSubject::findOrFail($request->sectionSubjectId);

    $student = Student::with(['sectionSubjects','sectionSubjects.section', 'sectionSubjects.subject'])->findOrFail($request->studentId);

    $subject->assignStudents($student);

    return $student->sectionSubjects;

   }
}

Can anyone suggets me on how to solve this problem, without the need of refreshing the page.



via Chebli Mohamed

Laravel 5.1 sarav multiauth with socialite

I have used sarav multi auth in my website and it is working fine. But when I install the socialite package (using command composer require laravel/socialite) to implement social media login, my auth stops working. The error I get is

ErrorException in EloquentUserProvider.php line 110: Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\User given, called in C:\xampp\htdocs\xyz\vendor\laravel\framework\src\Illuminate\Auth\Guard.php on line 390 and defined

I dont add any code. as soon as the command line finished installing the socialite package. I start getting this error. Please help guys. I am really stuck in between.



via Chebli Mohamed

Qrcode generate by id in laravel

i have qrcode but in there i have trouble. in my app i want my qrcode can auto generate by id.my code work but the exiting not make qrcode but only show code text. can someone tell me how to fix it ?

so, there is my view :

<div class="col-lg-12 code">
     {!! QrCode::size(250)->generate('<?php echo $row->name?>'); !!}
     <p>Scan for locations.</p>
</div>

and this my controller, :

public function getEdit($id)  {
        $data['row'] = locations::find($id);
        return view('locations_form',$data);
    }

    public function postEditSave($id) {
        $simpan= array();
        $simpan['name']=Request::input('name');
        $simpan['id_cms_companies']=Request::input('id_cms_companies');

        DB::table('locations')->where('id', $id)->update($simpan);
        Session::flash('edit', 'Data berhasil di Edit');
        return Redirect::to('locations');
    }

and this my table : table



via Chebli Mohamed

Review Schedule Task Code In Laravel 5.1

I am writing a code to be scheduled to run occasionally. I want to remove records of users who have their details on the users table but does not have their records in the profiles table as well. I am thinking about removing the by their id, but I am not sure how I can make the match. profiles migration:

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('gender',5);
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); // When a profile is deleted- his corresponding associated id details are deleted as well.
        $table->tinyInteger('age')->unsigned()->nullable();
        $table->string('goals')->nullable();;
        $table->string('activityType')->nullable();
        $table->rememberToken(); // for remember me feature.
    });
}

Users migration:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username',20)->unique(); 
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });

I have started to write the query, yet I am not sure how to proceed.

 public function handle()
    {
    // type the query to get users that have no data in their profiles.

        $empty_profile=App\Profile:::where('id','')->get;
        $user_id=App\User::where('id')
    }

Appreciate your help. Thanks.



via Chebli Mohamed

Fatal error exception in routes.php (works fine in windows, messes up in linux)

I have this project made for my final semester to demonstrate concepts from Advanced OS coursework. upon serving on command line, GUI is visible on browser. However, a functionality cannot be reached on it. Upon hitting it, I see this on the webpage. "

Whoops, looks like something went wrong.
1/1 FatalErrorException in routes.php line 27: Class 'App\Items' not found

" . I am enclosing the code in my routes.php for reference.`

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('postitem', function () {
    return view('postitem');
});
Route::auth();

Route::get('/home', 'HomeController@index');
Route::post('/itemPosted', 'HomeController@postItem');
//Route::post('/itemPosted', 'HomeController@searchItem');
Route::get('searchItem', function () {
    $item = App\Items::all();
    $data = array(
        'items' => $item
        );
    return view('searchItem',$data);
});
Route::get('bidnow', function () {
    return view('bidnow');
});
Route::post('/bidDone', 'HomeController@bidDone');`



via Chebli Mohamed

Get the last value of created_at date with distinct value column

I have the same problem for a lot of days ago, I have a table with a lot of values associated with her sensors in a MongoDB. Then I have to get all this distincts sensors, BUT I have to take the last value, Ex:

value---sensor---created_at
---------------------------
25---1---2016-05-09 16:33:51

68---1---2016-06-09 16:33:51

13---1---2016-07-09 16:33:51

12---3---2016-05-09 16:33:51

22---3---2016-06-09 16:33:51

I need to take the last value of the sensor 1:

13---1---2016-07-09 16:33:51

And the last value of the sensor 2:

22---3---2016-06-09 16:33:51

But I can't TT;

I try to do this:

Value::select('sensor', 'value', 'created_at')->orderBy('created_at', 'DESC')->groupBy('user_sensor_type_id')->get();

But it returns me random values, not the last.

Any ideas?

Thanks a lot!



via Chebli Mohamed

Laravel returning partial Collections

I hope this post finds you all in good health.

I'm facing problem when retrieving data as Collection in Laravel 5.1.

enter image description here

As you can see, I've a collection of 66 array items. At array[15] I'm getting all 25 of my total attributes. (no problem till now)

enter image description here

But from array[16] I'm getting partial data. And I don't know why I'm getting this "...8" [see the red arrow sign in image 2]

I've also tried "Chunking" the data but no use. And I've also checked my database.. Data is available there.



via Chebli Mohamed

lundi 23 mai 2016

"creating default object from empty value" on update laravel 5

I'm new to Laravel and I'm getting this error message "creating default object from empty value". I'm supposed to update a current Facility but I'm not doing any good..Supposedly, when I click the SAVE button(edit_facilities.blade.php), it will update the data in the database but I think I'm doing it wrong..Can someone please help me on how to improve or correct my code..thanks. This is my CONTROLLER:

      <?php
      namespace App\Http\Controllers;

      use Illuminate\Http\Request;

      use App\Http\Requests;

      use App\Facilities;

      use View;

      use Redirect;

      use Alert;

      use Validator;

      use Input;

      use App\Providers\SweetAlertServiceProvider;

      class FacilitiesController extends Controller
      {

      public $restful = true;


      public function update_facilities($id){

        $facility = Facilities::find($id);

        $facility->facility_name = Input::get('facility_name');
        $facility->category      = Input::get('category');
        $facility->save();


        Alert::success('Successfully Updated', 'Congratulations');
        return view('hotelier/facilities');
      }?>

And this is my VIEW for view_facilities.blade.php:

<h2>Hotel Facilities</h2>
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>Facility Name</th>
            <th>Category</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody id="facility_list">
        @foreach($facilities as $facility)
            <tr id="facility">
                <td></td>

                <td></td>

                <td><a href="<?php echo 'edit_facilities/'.$facility->id ?>" value="" class="btn btn-info open-modal">Edit</a>&nbsp;
                <a id="delete<?php echo $facility->id ?>" href="<?php echo 'delete_facilities/'.$facility->id ?>" class="btn btn-danger" onclick="delete_fac(this)" value="<?php echo $facility->facility_name ?>">Delete</a>&nbsp;

            </tr>
        @endforeach

    </tbody>
</table>

And this is for the VIEW of my edit_facilities.blade.php

<div class="container">
<h2>Edit Hotel Facility</h2>
<div class="col-md-4 form-horizontal">
    <form action="/update_facilities/'.$facility->id" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="_token" value="" />
        <label>Facility Name</label>
        <input type="text" class="form-control" value="" name="facility_name" id="facility_name" autocomplete="off"></input>
        <br />
        <label>Category</label>
        <input type="text" class="form-control" value="" name="category" id="category" autocomplete="off"></input>
        <br />
        <button type="submit" class="btn btn-info">Save</button>
    </form>
</div>

And my ROUTES:

Route::post('/update_facilities/{id}', 'FacilitiesController@update_facilities');



via Chebli Mohamed

How to fetch data database in input field name?

Route:

Route::get('listings','ListingsController@getListings');

ListingsController:
public function getListings(){
    $shows = DB::table('listings')->where('id', '1')->first();

    return view('listings.index',compact('shows'));
}

View:
<input type="text" id="searchbar" class="form-control" placeholder="Search for..." name="name">    



via Chebli Mohamed

composer self-update error when deploying on a shared hosting server

I am using Laravel 5.2 and I am attempting to deploy app on a live server. I copied the git repo to the new location and ran composer self-update and received the following error:

[Composer\Downloader\FilesystemException]
Filesystem exception:
Composer update failed: the "/usr/local/bin/composer.phar" file could not be written

How can I update composer?



via Chebli Mohamed

Laravel 5.1 - Store input data in my session

I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table, Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesnt work.

-I think that the principal problem is that $request->get('inputs') doesnt pass to my CartController.php , i tryed to return $request->all() and there is not nothing.

CartController.php

namespace dixard\Http\Controllers;

use Illuminate\Http\Request;

use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;

use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session; 
// i think that all classes are ok

public function add(Product $product, CartSession $CartSession,Request $request)
{
    $id = $request->get('id');
    $cart  = \Session::get('cart'); 

    $product->quantity = $request->get('qty');
    $product->size = $request->get('size');
    $product->color = $request->get('color');
    $cart[$product->id] = $product; 

    \Session::put('cart', $cart); 

    return $request->all(); // here i tryed to get all inputs but it did show me nothing result
    $subtotal = 0;

    foreach($cart as $producto){
        $subtotal += $producto->quantity * $producto->price;
    }   

    $session_code = Session::getId();
    $CartSession = new CartSession();

    $session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();

    if (isset($session_exist)) {


            $s = new CartSession;

            $data = array(

            'subtotal' => $subtotal,

            );

            $s->where('session_code', '=', $session_code)->update($data);


    }else {

            $CartSession = new CartSession();
            $CartSession->session_code = $session_code; 
            $CartSession->subtotal = $subtotal; 
            $CartSession->save(); 
    }

    //return $cart;
    //salveremo tutte le informazioni nel array cart nella posizione slug

    foreach($cart as $producto){
        $this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
    }

    return redirect()->route('cart-show');


}

Routes.php

Route::bind('product', function($id) {
     return dixard\Product::where('id', $id)->first();
    });

     Route::get('cart/add/{product}', [

            'as' => 'cart-add',
            'uses' => 'CartController@add'

            ]);

show.php view

  • Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}

                <input type="hidden" name="_method" value="PUT">
                    <input type="hidden" name="id" value="">

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="p_color">Colore</label>

                                    <select name="color" id="p_size" class="form-control">
                                        @foreach($colors as $color)


                                    <option value=""></option>

                                        @endforeach

                                    </select>

                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="size">Size</label>
                                    <select name="size" id="p_size" class="form-control">
                                        <option value="XS">XS</option>
                                        <option value="S">S</option>
                                        <option value="M">M</option>
                                        <option value="L">L</option>
                                        <option value="XL">XL</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="qty">Quantity</label>
                                    <select name="qty" id="p_qty" class="form-control">
                                        <option value="">1</option>
                                        <option value="">2</option>
                                        <option value="">3</option>
                                    </select>
                                </div>
                            </div>
                        </div>


                    <div class="product-list-actions">
                        <span class="product-price">
                            <span class="amount"></span>



                     <input  type="submit" class="btn btn-lg btn-primary" >
                       ADD PRODUCT
                        </input>
                    </div><!-- /.product-list-actions -->
                    {!! Form::close() !!}

Thank you for your help!



via Chebli Mohamed

How to use hasher::check in custom class to validate credentials for Token based authentication API

I am working on Token based authentication in which user will send Post request from Android to Laravel. Header will have Username and Encrypted Password. I am able to decrypt the password sent from Android to Laravel. Now I have plan Password.

Now the issue is: I need to compare it with AuthPassword. Can somebody advice how can I use hasher::check in my class so that I can check if credentials are correct or not?

I know, we have api_token in User Model, but in my requirement, user can do the Registration/Login from Android also.



via Chebli Mohamed

Laravel 5.1 HttpException in AuthorizesRequests.php line 94

I have the following authorization defined in my controller:

$this->authorize('store', $cart);

In my store method on my cart policy I have the following statement:

public function store(User $user, Cart $cart)
{
    // Check if cart is owned by user 
    if ($user->id != $cart->user_id ) {
       dd($cart);
       return response()->view('errors.404');
    }

    // Some other checks

    return true
}

But I get the following error: HttpException in AuthorizesRequests.php line 94

The error appears to be thrown when trying to evaluate the if statement because when I change comparison operator to == no error is thrown. I've determined this by using dd().

// Check if cart is owned by user
 if ($user->id == $cart->user_id ) {
    dd($cart);  
    return response()->view('errors.404');
 }

Any one have any ideas why this unusual behavior



via Chebli Mohamed

How to allow download just .zip and exe [Laravel 5.1]

How can I allow that user be able just to download zip and exe files?

I am currently use this function:

public function download($id)
    {
        $headers = array(
            'Content-Type: application/x-msdownload',
            'Content-Type: application/zip'
        );

        return response()->download(storage_path() . '/app/' . 'gamers.png', 'gamers.png', $headers);
    }

And this allow me download any file, how can I limit it just on zip and exe?



via Chebli Mohamed

Laravel where statement and pagination

I have an SQL search where I use Eloquent whereRaw, and than paginatate results.

Proplem: the results are paginated and if I navigate to the next page the results will be gone and it will just "SELECT All " bacause laravel's pagination sends only ?page= GET request.

code:

if (Input::has('city')) {
        $query .= ' and city = '.Input::get('city');
    }
    if (Input::has('area')) {
        $query .= ' and area = '.Input::get('area');
    }
    if (Input::has('sub_location')) {
        $query .= ' and sub_location = '.Input::get('sub_location');
    }
    if (Input::has('rent')) {
        $query .= ' and rent = '.Input::get('rent');
    }
    if (Input::has('price_min') && Input::has('price_max')) {
        $query .= ' and price < '.Input::get('price_max').' and price >'.Input::get('price_min');
    }


    $listings = ListingDB::whereRaw($query)->paginate(5);


    return View::make('page.index')->with('title','Home')->with('listings',$listings);

so when I navigate to the next page all the Input is gone because laravel generates pagination only with ?page= GET variable, how can I solve it?

thank you.



via Chebli Mohamed

hosting a laravel 5.1 application in live server

I have installed laravel 5.1 in my local system and developed an application. Now i have to host it in live server. The live server we have is our own and have many applications running in it. I have just placed the laravel folder in a path now(Nothing else). Its not working as expected.( I read in some answers that we have to copy public folder to server's public folder and rest to a folder, is it so? Do i have to install composer and follow laravel installation process there also?) Can anyone please explain what and all i have to do to make it work there? Thank You!



via Chebli Mohamed

Linking pivot table for many to many

I make a call the following call

$users = Helper::returnUsersFromLdap();

This returns all users in my system in the following format

array:64 [▼
  "Some User" => array:1 [▼
    "someone@someone.com" => "Director"
  ]
  "Another User" => array:1 [▼
    "someone@someone.com" => "Assistant"
  ]
  ...
]

I then loop these users and if they are not in my database I add them

foreach($users as $userName => $userData) {

    $user = User::firstOrNew(['userName' => $userName]);

    foreach ($userData as $userEmail => $userDepartment) {
        $user->userEmail = $userEmail;
        $user->active = true;
        $user->save();
    }
}

So that is how I create my users. Now within the above loop, I then make the following call

$userGroups = Helper::returnGroupsFromLdap($userName);

This will return all the groups that user is apart off. I then loop this to get all the unique groups

foreach ($userGroups as $group) {
    if(!array_key_exists($group, $groupsArray)){
        $groupsArray[$group] = true;
    }
}

I then perform another loop to create the groups

foreach($groupsArray as $group => $key){
    if(!empty($group)) {
        $usGroup = Group::firstOrNew(['groupName' => $group]);
        $usGroup->groupName = $group;
        $usGroup->save();
    }
    $user->groups()->sync($groupsArray);
}

The complete code looks like the following

public function updateUsers()
{
    $users = Helper::returnUsersFromLdap();
    $groupsArray[] = array();

    DB::table('users')->update(array('active' => false));
    foreach($users as $userName => $userData) {

        $user = User::firstOrNew(['userName' => $userName]);

        foreach ($userData as $userEmail => $userDepartment) {
            $user->userEmail = $userName;
            $user->active = true;
            $user->save();
        }

        $userGroups = Helper::returnGroupsFromLdap($name);

        foreach ($userGroups as $group) {
            if(!array_key_exists($group, $groupsArray)){
                $groupsArray[$group] = true;
            }
        }

        foreach($groupsArray as $group => $key){
            if(!empty($group)) {
                $usGroup = Group::firstOrNew(['groupName' => $group]);
                $usGroup->groupName = $group;
                $usGroup->save();
            }
            $user->groups()->sync($groupsArray);
        }
    }
}

This produces a unique list of users within my users table, and a unique list of groups within my groups table. I also have a third table called users_user_groups. This is to act as a pivot table so I can store all groups a user is apart off. My User model is like so

class User extends Model
{
    protected $table = 'users';
    protected $guarded = [];

    public function group()
    {
        return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('user_id', 'group_id');
    }
}

And my Group model

class Group extends Model
{
    protected $table = 'user_groups';
    protected $guarded = [];

    public function user()
    {
        return $this->belongsToMany('App\User', 'users_user_groups')->withPivot('user_id', 'group_id');
    }
}

My users_user_groups table contains a user_id and a group_id. With the code I posted above, data is being stored within this table using the sync function. However, the data is like so

+-----+-------------------+----------+
| id  |           user_id | group_id |
+-----+-------------------+----------+
|   1 |                 1 |        0 |
|   2 |                 1 |        1 |
|   3 |                 2 |        0 |
|   4 |                 2 |        1 |
|   5 |                 3 |        0 |
|   6 |                 3 |        1 |
|   7 |                 4 |        0 |
|   8 |                 4 |        1 |
|   9 |                 5 |        0 |

So it does not seem to show what groups a user is apart of, it just seems to repeat itself. Now that I have a unique list of users and a unique list of groups, how can I use the pivot table to show what groups a user is apart off?

Thanks



via Chebli Mohamed

dimanche 22 mai 2016

Use Stripe to post to external API

I'm adding payment to my app using Stripe. My app is divided into two parts, a front-end Angular app (http://ift.tt/1WJWIzJ), and a separate Laravel API. They live on two servers.

I'm using Stripe Checkout embed form and Laravel Cashier. Stripe is supposed to hijack my POST request and send the Credit Card data to their servers, then return a credit card token to me, to which I then post to my server.

Their form action assumes my app's API and ClientSide is all within the same app: <form action="" method="POST">

So, to post the token to my API endpoint, doIt, I added:

<form action="http://ift.tt/1qE1bpR" method="POST">
    <script
            src="http://ift.tt/1doUtf9" class="stripe-button"
            data-key="pk_test_UAgGwte0zwi0vCHVSKjAooqk"
            data-amount="999"
            data-name="Demo Site"
            data-description="Widget"
            data-image="/img/documentation/checkout/marketplace.png"
            data-locale="auto">
    </script>
</form>

Which should go here: $router->post('/doIt', 'Resources\Subscriptions@createSubscription');

And I'm trying to die out this info in the Controller:

public function createSubscription()
{

    $token = Input::get('stripeToken');

    $user = User::find(1);

    dd($token);

    $user->subscription('monthly')->create($token);

    $user->trial_ends_at = Carbon::now()->addDays(14);

    $user->save();
}

When I click the Checkout client button, the request goes as expected to Stripe, but it simply routes me to my API. How can I post the credit card token to my API and route as necessary on my client side? (Like, "payment successful!")


Edit: I'm using Angular, so I was thinking of capturing the hidden CC token field in my form controller, then posting from there. But the hidden field is generated on the fly and therefore doesn't exist.



via Chebli Mohamed

TokenMismatchException for API in Laravel 5.2.31

What Am I trying?

I already have a website and I am trying Token based authentication and below is the start for sample authentication code

I created a controller below is the code.

class AccountController extends \App\Http\Controllers\Controller
{
    public function apilogin($UserData) {
        return json_decode($UserData);
    }
}

My route config is below.

Route::group(['prefix' => 'api/v1'], function () {
    Route::post('/apilogin', 'AccountController@apilogin');
});

Then from the Postman Chrome Extension, I have below info for Headers

Cache-Control →no-cache, private
Connection →close
Content-Type →text/html; charset=UTF-8
Date →Mon, 23 May 2016 05:20:56 GMT
Server →Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.14
Transfer-Encoding →chunked
X-Powered-By →PHP/5.6.14

Body info is like below

{"UserName": "Pankaj"}

When I press Send: I get below Error

TokenMismatchException in VerifyCsrfToken.php line 67:

Am I missing something?



via Chebli Mohamed

Laravel fetch latest record based on created_at datetime field

In my E-Commerce web application, I am trying to implement International Shipping Feature. The relationship is like:

One international shipping zone hasMany Countries and a Country belongsTo a shippig zone.

One international shipping zone hasMany Shipping rate applied and one Shipping Rate belongsTo one Shipping Zone.

Now what I want to trying to do is to fetch the all the shipping rates that are created in descending order. Uptil now, I can fetch it correctly without any issue. Now here comes the twist. If there is one shipping rate having the same shipping rate code in the table, fetch the latest record and ignore the previous record, based on the country that will be selected by the user on the front end.

The code that I have tried:

$shippingCountryId = session()->get('new_shipping_country');
$shippingCountryAmount = session()->get('new_shipping_amount');

if ($shippingCountryId !== null) {
    $shippingAll = ShippingCountry::find($shippingCountryId)
                                    ->zone->rates()
                                    ->latest()->get();
} else {
    $shippingAll = ShippingCountry::where('name', 'India')->first()
                                    ->zone->rates()
                                    ->latest()->get();
}

The above code fetches all the records from the rates table for that shipping zone when the user selects the shipping country, which I don't want. I want only the latest one to be fetched if there is more than one record found with the same code.

Collection methods didn't work for me:

unique(), contains(), search(), filter()

I know I am pretty sure that I must be making some silly mistake, but I cannot find out what mistake and where.

Kindly help me out with this. I am trying to solve this since 2 days, but could not succeed yet.

Any help is highly appreciated. Thank you in advance.



via Chebli Mohamed

Laravel 5.1 - Foreach data in form (Blade)

i have a problem to show colors avaible of my products, i tryed to show them with blade foreach, but it doesnt work. My resource controller:

public function show($id){

        $colors = Color::where('product_id', $id)->orderBy('id', 'asc');

        $product = Product::where('id', $id)->first();

        return view('store.show', compact('product','colors')); 

    }

This is my table color, i added correctly the relations enter image description here Product Model:

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\User;

use dixard\Category;

use dixard\Gender;

use dixard\OrderItem;

use dixard\Color;

class Product extends Model
{

    protected $table = 'products';

    protected $fillable = 

    [
    'name',
    'slug',
    'description',
    'extract',
    'image',
    'visible',
    'price',
    'category_id',
    'gender_id',
    'user_id'

    ];



    // Colleghiamo OGNI prodotto ha un utente
    public function user() {
            return $this->belongsTo('dixard\User');



    }

    // Colleghiamo OGNI prodotto ha una categoria
    public function category() {
            return $this->belongsTo('dixard\Category');



    }

    public function gender() {
            return $this->belongsTo('dixard\Gender');



    }

    // prodotto è contenuto in TANTI order item
    public function OrderItem() {
            return $this->belongsTo('dixard\OrderItem');

    }

    // prodotto è contenuto in TANTI order item
    public function Color() {
            return $this->belongsTo('dixard\Color');

    }

}

Color Model

namespace dixard;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    protected $table = 'colors';


    // gli dico che voglio scrivere questo campi
    protected $fillable = [

    'color',
    'product_id',



    ];
    public $timestamps = false;

    // Ogni color HA tanti prodotti. // Ogni prodotto ha tanti colori
    public function products() {

        return $this->hasMany('dixard\Product');

    }
}

I'm trying to show the color avaible for my product so:

    <label for="p_color">Color</label>


     @foreach($colors as $color)
 <td></td>
     @endforeach

This is only test! I would like show a select option, i tryed to use BLADE but it doesnt work,

-get all colors where product_id = $id work fine.

-get the product where id = $id work fine.

-I think the problem is the code blade(foreach) to show all colors avaible for my product.

how can i resolve it? Thank your help!



via Chebli Mohamed

Can not install laravel

I can not install Laravel in this way:

php composer.phar create-project laravel/laravel blog --prefer-dist ~5.0
php composer.phar create-project laravel/laravel blog --prefer-dist 5.0
php composer.phar create-project laravel/laravel blog --prefer-dist
php composer.phar create-project laravel/laravel blog

Response in console:

Could not find package laravel\laravel with stability stable.

or

Could not find package laravel\laravel with version ~5.0.

I'm trying do this in another way like that:

 php laravel new blog

Project doest not exist after crafting project or I have info in console:

cURL error 7: Failed to connect to 192.241.224.13 port 80: Timed out

What is wrong with this stupid composer ? :(



via Chebli Mohamed

Making a visitor tracker in laravel 5.1

I've currently installed a plugin (http://ift.tt/1oa6jQo)

Wich does the tracking thing, only I want to get unique visitors. I reall don't know how to extract those from this package. Or how I should make one by my own.

I want them to return as a json object per month.

If someone could help me out with this?

I tried it using the tracker_sessions table, but that doesn't work well.

Route::get('admin/api', function(){

        $stats = DB::table('tracker_sessions')
          ->groupBy('created_at')
          ->orderBy('created_at', 'ASC')
          ->get([
            DB::raw('created_at as y'),
            DB::raw('COUNT(*) as b')
          ]);

          return json_encode($stats);
    });

That returns something like this:

[{"y":"2016-05-22 21:17:17","b":1},{"y":"2016-05-22 21:17:27","b":1},{"y":"2016-05-22 21:17:28","b":2},{"y":"2016-05-22 21:17:29","b":1},{"y":"2016-05-22 21:17:31","b":1},{"y":"2016-05-22 21:17:33","b":1},{"y":"2016-05-22 21:18:10","b":1},{"y":"2016-05-22 21:18:11","b":2},{"y":"2016-05-22 21:18:13","b":1}]

Wich is not good at all...

Can someone please help me out?

Thanks!



via Chebli Mohamed

laravel 5.1 route direct to public folder

this is my route to access index.php ....http://localhost/abc/public/ if i write http://localhost/abc/ it does pick public bydefault

i want to write .htaccess file to direct http://localhost/abc call to http://localhost/abc/public/ so my url will not hurt..

in short i want http://localhost/abc/ and by dont even change directory struture of laravel.



via Chebli Mohamed