mardi 29 mars 2016

Laravel 5.2 eager loading no working

Heres what i am doing.

$question = ForumQuestion::where('link',$ques)->with('answers')->first();
$answers = $question->answers;
$answers->load('user');
//return $answers;
return view('forum.question', compact('question','answers'));

the $answers->load('user'); eager loads corresponding user of the answer.

public function user()
    {
        if ($this->user_type == 'student') {
            return $this->belongsTo(Student::class, 'user_id');
        }else{
            return $this->belongsTo(Teacher::class, 'user_id');
        }
    }

But problem is $this->user_type gets some kind of static. If my first answer has user_type = 'teacher' then in every query it assumes as it is teacher even though it changes some time to student. Why it is static? If I don't eager load it works well.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/22XDveG
via IFTTT

Upload image to database in laravel 5 using eloquent ORM?

I have one form which contains one file upload.

Form Id is "upload_form"

<input type="file" id="image" name="image"/>

Using javascript onclick function and ajax to pass the image to the controller.

Ajax fn:

$.ajax({
url: 'UploadImage',
data:new FormData($("#upload_form")[0]),
type: "post",
dataType:"JSON",
async:false,

success: function (data) {

console.log(data);

      }
});
}

Routes:

Routes::post('UploadImage','UploadController@Upload');

UploadController:

public function Upload()
{
 $file = Input::file('image');
 $tmpFilePath = '/temp/uploads/';
 $tmpFileName = time() . '-' . $file->getClientOriginalName();
 $path = $tmpFilePath.$tmpFileName;
 $data_file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
 // Error for move() and getClientOriginalName() functions.

}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/21QOh40
via IFTTT

pagination totoal does not return 0 if there is no record in laravel 5

I have error in pagination total.

Actually I'm getting the results but the problem is when there is no records then it throws the following error: Undefined index: inactive_users (View: /home/vagrant/Code/krankontroll/resources/views/customer/inactive.blade.php)

If I don't have any records for inactive_users array I'm getting the above error where actually it should give "No of records 0".

My controller page code is:

$customers = Customer::getCustomerPaginated(Session::get('search'),     $data['sortorder'], $data['sortby']); 
$data['customers'] = Customer::getCustomerByStatus($customers, (Input::get('page'))?Input::get('page'):1);

And my model page code is:

public static function getCustomerByStatus($customers, $pageStart=1) 
{
    $customer_status = array();
    $customer_result = array();
    $newcustomers=array();
    foreach($customers as $customer){
        $customer_status[$customer->status][] = $customer;
        if($customer->status<>2)            
        $customer_status[3][] = $customer;
        $newcustomers[] = $customer;        
    }
    $customer_result = $customer_status;
    $perPage = 10;

    // Start displaying items from this number;
    $offSet = ($pageStart * $perPage) - $perPage;

    //Slice the collection to get the items to display in current page
    $currentPageSearchResults = $customers->slice($offSet, $perPage, true)->all();
    $collection = new Collection($currentPageSearchResults);

    // Get only the items you need using array_slice
    $pagination['all'] = new LengthAwarePaginator($collection, count($newcustomers), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));

    foreach($customer_status as $status=>$customer_state)
    {
        $itemsForCurrentPage = new Collection(array_slice($customer_state, $offSet, $perPage, true));
        if($status==0)
            $label='active_users';
        else if($status==1)
            $label='inactive_users';
        else if($status==3)
            $label='nonyearly_users';
        else
            $label='yearly_users';
            $pagination[$label] = new LengthAwarePaginator($itemsForCurrentPage, count($customer_state), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }
    var_dump($pagination);
    exit;
    return $pagination;
}

Can anyone help me???



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Uz8iNL
via IFTTT

How to properly reference the path with newly installed packages using npm in Laravel?

I've installed ReactJS and Babel using npm in my laravel project. They are found in "node_modules" folder created by npm itself. But the problem is my react code doesn't seem to work if I import using this code:

<script src="node_modules/react/react.js"></script>
<script src="node_modules/react-dom/dist/react-dom.js"></script>
<script src="node_modules/babel-core/lib/api/browser.js"></script>

Is the format of the path correct? because if I just import using this type of code for all my imports required for ReactJS:

<script src="http://ift.tt/1KXYNNU"></script>

It seems to work if I just use the internet for getting the packages.

My react code is here:

<div id="myapp"></div>
<!-- JavaScripts -->
<script type="text/babel">
    var BuckyComponent = React.createClass({
        render: function()  {
            return(
                <h2>{this.props.user} likes to eat {this.props.food}</h2>
            );
        }
    });

    React.render(
        <div>
            <BuckyComponent user="Arth" food="Bacon"/>
            <BuckyComponent user="Arth" food="Pork"/>
            <BuckyComponent user="Arth" food="Chicken"/>
        </div>,
        document.getElementById('myapp')
    );
</script>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1SiX35M
via IFTTT

is php dying now ? with evolution of js and node

i think many people write code in php for now , with evolution in Web technologies specially js , how this will effect on php world and developers? does the beginner or nope should learn php or leave it ? i'm aware with latest modification in php7 and latest php frameworks .

i mean by this questions the experts who saw many evolution . show your point of view ,please .



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1pH22G8
via IFTTT

Laravel CORS headers not shown if user is not auth'ed

So I'm trying to create an API using Laravel, everything was going well until it came to that point where I have to connect it with Angular on another subdomain. I'm using JWT token-based auth which works fine.

I have created a CORS middleware like this:

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Max-Age', '10000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    }
}

Added in Kernel.php and created Route group like this:

Route::group(['middleware' => 'cors'], function () {
    Route::group(['prefix' => 'api/v1'], function() {
        Route::get('/test', 'MemberController@test');
    });  
});

I'm trying to create a call that checks if user is authenticated and returns that to angular app so the app knows what to show.

I trued like this:

public function test()
{
    if(Auth::check()){
        echo "logged in";
    } else {
        echo "nuno";
    }
}

But that returns the page without CORS headers, but if I remove "else" statement and only leave "if auth" it will return the page with headers.

Also, another problem I have is that JWT returns 400 if the token is invalid or not supplied.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1SsZ4yR
via IFTTT

How to read JsonResponse in php

How to get id from here

JsonResponse {#457 ▼
  #data: "{"bill":{"id":11,"invoice_no":"9m36r9_1459170388239"}}"
  #callback: null
}

I am getting this output from this laravel code

return Response::json($response);

I tried json_decode but not worked here, a blank output is coming.

Thanks for any help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1oiGej7
via IFTTT