mardi 31 mai 2016

sentry throw error on laravel 5.1

I have use Laravel 5.1 with "jenssegers/raven": "^1.4"

When I run composer self-update on server then found error page isn’t working

Error log is:

PHP message: PHP Fatal error:  Uncaught exception 'ErrorException' with message 'preg_match() expects parameter 2 to be string, object given' in /var/www/html/http://ift.tt/1TJ7m48

Kindly help me, how to resolve this issue. I appreciate all response.



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

delete directory using Laravel Storage Facade

I'm trying to delete a directory using Laravel Storage Facade, here's what I tried

Storage::delete('xtestx');

But unfortunately, it does not work, instead it gives me this error.

storage\app\resources\xtestx): Permission denied

any ideas, help, clues, recommendations, suggestions?



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

How to use global prefix for tables in Laravel 5

New in Laravel. Probably a silly question. I had setup database like this:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => 'mydb',
        'username' => 'myusername',
        'password' => 'mypassword',
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => 'admin',
        'strict' => false,
        'engine' => null,
    ],

Notice 'prefix' => 'admin'. This is because I want all tables related to the website's control panel be prefixed with admin, e.g: admin_users, admin_log, etc...

But I'm stuck at the very beginning. I'm trying to create migrations via artisan but it's not creating the tables with the prefix.

php artisan make:migration create_users_table --create=users

I'm expecting that to create a table named admin_users. But it's not.

Am I doing this right?



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

Overriding routes set by packages (Laravel 5.2)

I'm using laravel 5.2 with the sentinel package (rydurham/Sentinel).
This package sets some routes automatically, namely:

Route::get('login', ['as' => 'sentinel.login', 'uses' => 'SessionController@create']);
Route::get('logout', ['as' => 'sentinel.logout', 'uses' => 'SessionController@destroy']);
Route::get('sessions/create', ['as' => 'sentinel.session.create', 'uses' => 'SessionController@create']);
Route::post('sessions/store', ['as' => 'sentinel.session.store', 'uses' => 'SessionController@store']);

In order to add my custom logic, I created a new session controller, and attempted to override the routes doing the following:

Route::get('login', ['as' => 'sentinel.login', 'uses' => 'AuthController@create']);
Route::get('sessions/create', ['as' => 'sentinel.session.create', 'uses' => 'AuthController@create']);
Route::post('sessions/store', ['as' => 'sentinel.session.store', 'uses' => 'AuthController@store']);

The problem laravel's routing seemingly favours the package routes. I could comment out the routes in the package, however this would make updating a pain.
How can I override the routes without modifying the package? Thanks!



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

TokenMismatchException in VerifyCsrfToken.php line 67 using Route::post()

I understand that this is a common issue with Laravel, but my particular run-in with the problem is not through submitting a form. Instead, I am using postman to send data to a URL endpoint to test if data is successfully received.

Here is my routes.php file (related content)

Route::group(['middleware' => 'auth'], function () {
    Route::post('/cart', 'CartController@buildcart');
});

Here is my CartController.php (entire file)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class CartController extends Controller
{
    public function buildcart(){
        echo 'hello';
    }
}

As simple as that is, when I use postman to send random data to the /cart URL, I get

TokenMismatchException in VerifyCsrfToken.php line 67:

Can anyone help me understand why this is failing? I don't see how using



is the solution for this case since the data is coming from an external source.



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

Laravel 5 Simple Comparison Fails

This should be simple but for some reason code in my if block is executing despite the fact that it resolves to false and it's making me very unhappy... My user_id in this case is 2.

$note = Notification::where("user_id",Auth::user()->id)->first();
$wall = $note->pluck('wall');
if($wall != 0)
{
//This code is executing!
}
else{
    array_push($data,"Your First Time!");   
    //This code is not!
}

As you can see, my $wall should be zero so I don't understand why $wall != 0 runs.

enter image description here



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

rename a directory or a file

I'm using Laravel 5.0 Facades Storage

use Illuminate\Support\Facades\Storage;

and I can use it like

Storage::..

In the Laravel 5.0 Docs,there's nothing like rename a file or folder from the storage.

Any help, ideas, clues, suggestions, recommendations on how to rename a file or folder using the Storage?



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

How to validate current, new, and new password confirmation in Laravel 5?

I have created the password route, view and method in UserController@getProfilePassword and UserController@postProfilePassword

At the moment, if I fill out the new_password field, it gets hashed and submitted to the database correctly, then I can login with the new password.

But I need to be able to validate the new_password and new_password_confirm to make sure they're the same and validate the user's current password as well.

How can I do that?

public function getProfilePassword() {
    return view('profile/password', ['user' => Auth::user()]);
}

public function postProfilePassword() {
    $user = Auth::user();

    $user->password = Hash::make(Input::get('new_password'));
    $user->save();
}

And this is the view

<form action="" method="post" enctype="multipart/form-data">
    <div class="form-group">
          <label for="name">Current Password</label>
          <input type="password" name="old_password" class="form-control" id="old_password">
    </div>
    <div class="form-group">
          <label for="name">Password</label>
          <input type="password" name="new_password" class="form-control" id="new_password">
    </div>
    <div class="form-group">
          <label for="name">New Password</label>
          <input type="password" name="new_password_confirm" class="form-control" id="new_password_confirm">
    </div>
    <button type="submit" class="btn btn-primary">Change Password</button>
    <input type="hidden" value="" name="_token">
 </form>



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

How to access Controller in laravel

I have made server.php, my index.php and public is now not the part of url, the problem is: when i set anchor as

**<a class="page-scroll" href="<?php echo url(); ?>/stories">stories</a>**

i expect it to go to stories index() function, but it say, page not found.



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

Laravel 5 and weird bug: curly braces on back

Whenever I go back in history on my Laravel website, the response I see is this:

{}

When I go forward to where I was before that, it shows those braces as well.

The problem doesn't occur if I launch Developer Tools in Chrome with Disable Cache option. The Content-Type of what's returned is indeed application/json. In Firefox there's no such problem.

It happens because one of my Middlewares. I wrote AjaxJson middleware to translate all Ajax requests to JSON response. Weirdly, when I go back in history, Google Chrome makes this request Ajax. It contains this header:

X-Requested-With: XMLHttpRequest

And therefore $request->ajax() returns true.

This is my middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class AjaxJson
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (!$request->ajax()) {
            return $response;
        }

        if (!$response instanceof Response) {
            return $response;
        }

        return response()->json($response->getOriginalContent(), $response->status());
    }
}

What am I doing wrong?



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

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.



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

Access Route Attribute in Service Provider by Rebinding?

Bindings

I'm using bindings in my service provider between interface and implementation:

public function register()
{
    $this->app->bind('MyInterface', MyImplementation::class);
}

Middleware

In my middleware, I add an attribute to the request:

public function handle($request, Closure $next)
{
    $request->attributes->add(['foo' => 'bar]);
    return $next($request);
}

Now, I want to access foo in my service provider

public function register()
{
    $this->app->bind('MyInterface', new MyImplementation($this->request->attributes->get('foo')); // Request is not available
}

The register is called before applying the middleware. I know.

I'm looking for a technique to 'rebind' if the request->attributes->get('foo') is set



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

Error in composer update laravel 5

I'm trying do composer update in CMD but catched this error

could not scan for classes inside database which does not appear to be a file nor a folder

which is not the cause and is not much information about the meeting, which can be?



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

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



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

Real Time Multiple Users Table Editing

I am making an application where I display a table (from mysql db) and there are multiple users who can edit the table. This is a laravel application. What is a good tutorial for this and/or how should I approach this?



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

Laravel Model Factories ID not set

I have a regular User model. The system works fine when I use it. But now I am trying to create unit tests in the PHPUnit that integrated with Laravel.

I have a factory that creates a user:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'id' => $faker->randomNumber(9),
        'email' => $faker->safeEmail,
        'first_name' => $faker->firstNameMale,
        'last_name' => $faker->lastName,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

I changed the User to have integer ID as the primary key but it not defined as auto-increment. So the factory create random number for the ID.

Also I have created the simple test:

public function test_id_is_visible() {
    $user = factory(App\User::class)->create();

    $this->actingAs($user);
    $this->visit('/userprofile');
    $this->see($user->id);
}

That test always fails, but it seems to be OK when I navigate to the page manually.

I have noticed that in the test the $user->id is always 0. Even it can't be 0 in the factory. I checked and Laravel insert the user correctly to the database and it have correct ID, but in the code I always get 0.

What can I do to get the correct value of the ID?

EDIT Now I see that if I changes $user = factory(App\User::class)->create(); to $user = factory(App\User::class)->make(); the user instance holds a correct ID. But why create clears the ID?



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

How to upload picture and store to database in Laravel 5

I need to upload picture and store to database in Laravel 5.

My current code:

Form:

<form method="POST" enctype="multipart/form-data" action="">
    {!! csrf_field() !!}
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="image">Image</label>
        <input type="file" id="image">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
</form>

Controller:

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required|max:100|unique:products',
    ]);

    $input = $request->all();
    Product::create($input);

    return redirect('products');
}

$request->hasFile('image')) returns false.



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

Laravel Read/Write Connection - Specify Explicitly

I am trying to configure master/slave db connection in a handy way. The cleaner way I came across is using read/write hosts separately in database config file.

'mysql' => [
'read' => [
    'host' => '192.168.1.1',
],
'write' => [
    'host' => '196.168.1.2'
],
'driver'    => 'mysql',
'database'  => 'database',
'username'  => 'root',
'password'  => '',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
],

In some cases, I need to read the data from master db (without replication lag). Is there a way to specify this explicitly? Something like we pass connection name to connection() method?



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

Laravel SQL groupBy and sum

I here is my tables relation:

reservations id, date, etc...
reservation_service_info service_info_id, reservation_id
services_info price etc...

I am trying to sum reservation price by day. Here is the code and result:

return $query->selectRaw('DATE(start_time) AS date')
        ->selectRaw("(SELECT price FROM `services_info` inner join `reservation_service_info` on `services_info`.`id` = `reservation_service_info`.`service_info_id` where `reservation_service_info`.`reservation_id` = reservations.id) as price")
        ->orderBy('date', 'ASC')
        ->get('price', 'date')

Result:

[
{
"date": "2016-06-01",
"price": "345.00"
},
{
"date": "2016-06-01",
"price": "90.00"
},
{
"date": "2016-06-01",
"price": "222.00"
},
{
"date": "2016-06-02",
"price": "393.00"
},
{
"date": "2016-06-02",
"price": "142.00"
}
]

When I add groupBy('date') in the query it groups it by dosent SUM(price)

[
{
"date": "2016-06-01",
"price": "345.00"
},
{
"date": "2016-06-02",
"price": "393.00"
}
]



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

Laravel order user by role

I have table users and pivot table role_user, not every user has a role. I need to make a query and get all users, and order them by roles, which join statement should I use then, how would that query look like then? I need some similar query to this, but so that users with that have roles come first and not the ones that don't have roles like now:

$users = DB::table('users')
                     ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
                     ->orderBy('role_id')
                     ->get();



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

Cannot retirieve single column from database. Laravel

I'm trying to retrieve single column from my table grades. For that I have used following code in my controller:

public function verify($id,$sid)
{

$grade=Grade::all('annual')->whereLoose('id',$id);
return $grade;

}

Where, annual is column name. But it is returning empty set of array []. Can anyone help me?



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

How create database and tables from laravel test

I create Unit Tests in project Laravel 5. I need to create a database when I run the test and add a tables in the database. I want create this functional with migration but I have issue with this. I can create migration from terminal by usin php artisan, but I don't know how create database directly from php code, and create tables in this database. Please let me know if you know how to do it, or you saw similar implementation.

Thanks



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

PHP Fatal error: Call to undefined function table() in eval()'d code on line 1 Laravel Artisan Tinker

I'm having a problem with learning Laravel so i decided to follow a tutorial at laracast hoping that i could understand something at the end,

i installed homestead and "SSh"ed into my VM and into "~/Code/Laravel" and tried to work with tinker as they did on the tutorial ,, Tinker works but wont execute any command not even a simple selection like (>>> DB:table('projects')-get()) , but keeps giving me the following error:

PHP Fatal error:  Call to undefined function table() in eval()'d code on line 1

screen shot of the terminal attached i can run simple mathematical operations and echo commands, but noting related to database, although i migrated the table (projects) successfully, and i was planing to seed it through tinker (by seed i mean input some data into it - is that what seed means in the first place? -).

my OS is Ubuntu if it matters!

thank you in advance!



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

Laravel Homestead - I can ping homestead.app but I can't access in homestead.app in browser

Well:

I can access the files in the virtul server through vagrant SSH.

I can ping homestead.app through CMD.

I can ping the IP 192.160.10.10 through CMD.

But i can't access it through the browser.

if i enter 127.0.0.1:2222 in browser i get this:

SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.6
Protocol mismatch.

this is my Homestead.yaml file:

    ---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: C:\projects\PHP
      to: /home/vagrant/Code

sites:
    - map: homsetead.app
      to: /home/vagrant/Code/smr/public
      hhvm: true

databases:
    - laraveldb

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp

and this is the hosts file:

127.0.0.1 activate.adobe.com
192.168.10.10 homestead.app



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

Laravel 5 Eloquent - whereIn on join table

I am trying to create an online directory, where, for example, people can search through the website and find all takeaways that have a specific type. For example:

"Indian",

"Chinese"

etc..

I have 3 tables:

Business

Tags

Business Tags

And my model is as follows:

class Business extends Model
{
    protected $table = 'businesses';

    protected $fillable = [
        'business_name', 'postcode'
    ];

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

The issue is, whenever I come to do the search, and try to do a whereIn the issue is that it takes forever to load, in fact, it doesn't even load. For example:

$business = Business::whereHas('tags', function($tag) use ($request) {

    if($request->get('terms'))
    {
        $tag->whereIn('tags.name', ['chinese']);
    }

})->get();

The issue is that it takes forever. I don't even think this is the best way to do such a thing. Anyone help me with a better solution that doesn't take forever to load the results?



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

Access array of object in php [duplicate]

This question already has an answer here:

array(1) {
    ["categories"]=> array(2) {
        [0]=> array(1) {
            [0]=> object(stdClass)#233 (4) {
                ["categoryid"]=> string(2) "19"
                ["categoryname"]=> string(7) "Science"
                ["authorname"]=> string(7) "avinash"
                ["description"]=> string(7) "Science"
            }
        }
        [1]=> array(1) {
            [0]=> object(stdClass)#234 (4) {
                ["categoryid"]=> string(2) "21"
                ["categoryname"]=> string(20) "Recipies around the " 
                ["authorname"]=> string(7) "Kishore"
                ["description"]=> string(25) "Recipies around the World"
            } 
        }

    }
}

I am trying to access this string using foreach:

<?php  foreach($categories as $category){ ?>
<tr>
<td><?php echo $category->categoryid; ?></td>
<td><?php echo $category->categoryname; ?></td>
</tr>
 <?php  } ?>

Getting error:

Trying to get property of non-object..



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

Is it good to filter data in controller or use sql query in model?

What is the best approach for searching?What will be difference if i filter the all data in controller and get result, and use where query in model and get result ?Please suggest your opinion.



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

Why are the php variables not working with my Javascript/Laravel-5 Google Maps Code?

I'm working on a laravel-5 application which requires me to sync data from a database and display it on google maps. The problem that I'm encountering is that whenever I run the code, it gives me an error that says:

Trying to get property of non-object (View: C:\xampp\htdocs\appl\resources\views\getmap6.blade.php)

The code for my page is as follows:

<!DOCTYPE html>
<html>
<head>                  

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

            function initialize() 
                {
                    var mapProp = {
                                    center:new google.maps.LatLng(51.508742,-0.120850),
                                    zoom:13,
                                    mapTypeId:google.maps.MapTypeId.ROADMAP
                                  };

                    var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
                    var infowindow = null;

                    <?php for($i=1; $i<3; $i++)
                            {
                                $offLinks = App\offerlink::find($i);
                    ?>            

                    var marker=new google.maps.Marker({
                                                position: new google.maps.LatLng(<?php echo $offLinks->lat; ?>,<?php echo $offLinks->lng; ?>),
                                                icon: 'http://ift.tt/1focNmg'
                                             });

                    marker.setMap(map);

                    infowindow = new google.maps.InfoWindow({
                                                                content: "<b>Name: </b>" + "<?php echo $offLinks->name; ?>" + "<br> <b>Address: </b>" + "<?php echo $offLinks->address; ?>",
                                                            });



                    infowindow.open(map,marker);

                                        google.maps.event.addListener(marker, 'click', function() {

                                                                                infowindow.setContent(marker);
                                                                                infowindow.open(map,this);
                                                                              });

                            <?php } ?>  


                    google.maps.event.addListener(marker, 'click', function() {

                                                                                infowindow.setContent(marker);
                                                                                infowindow.open(map,this);
                                                                              });       

                }

                google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>

</html>

This code works on a local server which syncs to a phpMyAdmin database. The other pages don't have any issues when trying to connect to the database. It is only this page that has the issue. I know that the problem lies in the following lines of the code because because without those lines, there are no errors:

position: new google.maps.LatLng(<?php echo $offLinks->lat; ?>,<?php echo $offLinks->lng; ?>),

and

content: "<b>Name: </b>" + "<?php echo $offLinks->name; ?>" + "<br> <b>Address: </b>" + "<?php echo $offLinks->address; ?>",

Clearly, there is something wrong in the way I'm trying to use the php variables. I believe this code was working fine a few days ago.

Thank you for your time and effort.



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

!Auth::attempt won't compare the records in database

The attempt method won't get the right values in my database. It always fail when I input right values. I create a Seeder which insert a values in my database. I hash my password, I'm not sure if hashing that cause why it won't redirect me to home page.

AdminTableSeeder

class AdminTableSeeder extends Seeder
{
public function run()
{
    DB::table('admin')->delete();

    $admin = array(
    array('username' => 'admin',
          'password' => Hash::make('admin'))
    );

    DB::table('admin')->insert($admin);
}
}

AdminController

public function postAdminLogin(Request $request)
{
    $this->validate($request, 
    [
        'username' => 'required|max:20',
        'password' => 'required|min:5',
    ]);

    if(!Auth::attempt($request->only(['username','password']), $request->has('remember')))
    {
        return redirect()->back()->with('info', 'Could not sign in with those details.');
    }

    return redirect()->route('admin')
    ->with('info', 'Successfully logged in');
}

loginadmin.blade.php

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

            <div class = "form-group ">
                <label for = "username" class = "control-label">Username</label>
                <input type = "text" name = "username" class = "form-control">

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

            <div class = "form-group ">
                <label for = "password" class = "control-label">Password</label>
                <input type = "password" name = "password" class = "form-control">

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

            <div class = "checkbox">
                <label>
                    <input type = "checkbox" name = "remember">Remember me</input>
                </label>
            </div>

            <div class = "form-group">
                <button type = "submit" class = "btn btn-default">Login</button>
            </div>

            <input type = "hidden" name = "_token" value = "">

</form>



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

Using regex for validation

I am trying to validate the telephone number using the regix. but it is giving me error:

  $validator=Validator::make($request->all(),[
        'name'=>'required',
        'telephone'=>'regix:^[[0-9]\-\+]{9,15}$|required|unique:telephone',
        'email'=>'unique:telephone',]);

the error is:

Method [validateRegix] does not exist.



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

Laravel 5.0 - Error Call to undefined method Illuminate

I have an error while setting up the code

Call to undefined method Illuminate\Foundation\Application::bindShared()



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

Getting incomplete data from database eloquent Laravel

I am facing very weird response from the eloquent query. It works fine if there are few set of data, but shows garbage if there is a huge set of data.

I haven't seen this type of error and I am very confused that what should I ask.

Here is my code:

$title = Input::get('title');
$movie = $this->where('name', 'like', $title.'%')->get(['id', 'poster', 'name', 'release_date']);
echo "<pre>";
dd($movie->toArray());

Result I am getting (if there is a lot of data)

array:2847 [
  0 => array:4 [
    "id" => 12
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "The Arrival of a Train"
    "release_date" => "1896-01-01"
  ]
  1 => array:4 [
    "id" => 13
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "The Photographical Congress Arrives in Lyon"
    "release_date" => "1895-06-12"
  ]
  2 => array:4 [
    "id" => 14
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "Tables Turned on the Gardener"
    "release_date" => "1970-01-01"
  ]
  .
  .
  .
  .
  623 => array:4 [
    "id" => 2206
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "The Outlaw Deputy"
    "release_date" => "1911-11-04"
  ]
  624 => array:4 [
    "id" => 2212
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "The Passions of an Egyptian Princess"
    "release_date" => "1970-01-01"
  ]
  625 => array:4 [ …4]
  626 => array:4 [ …4]
  627 => array:4 [ …4]
  628 => array:4 [ …4]
  629 => array:4 [ …4]
  630 => array:4 [ …4]
  631 => array:4 [ …4]
  632 => array:4 [ …4]
  633 => array:4 [ …4] // I don't know why I am getting this result set

And I am getting proper result when there are only few set of data

array:4 [
  0 => array:4 [
    "id" => 4538
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "Titanic: Echoes of Titanic"
    "release_date" => "1970-01-01"
  ]
  1 => array:4 [
    "id" => 4540
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "Titanic: End of an Era"
    "release_date" => "1970-01-01"
  ]
  2 => array:4 [
    "id" => 4545
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "Titanic: The Mystery & the Legacy"
    "release_date" => "1970-01-01"
  ]
  3 => array:4 [
    "id" => 4548
    "poster" => "http://ift.tt/1sIjNGG"
    "name" => "Titanic: Titanic Remembered"
    "release_date" => "1970-01-01"
  ]
]

Can someone please help me to solve this.

Thanks,



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

Laravel gives me Object not found! The requested URL was not found on this server. 404 error

I have created one controller file as per below and routes for it. i want to display Hello World message on my website by entering this url.http://localhost/mylaravel/mycontroller But is's show me 404 error. 1. Controller File: namespace App\Http\Controllers; class MyController extends BaseController { public function loadview() { echo "Hello World"; } }

  1. Routes file: Route::get('/', function () { return view('welcome'); });

    Route::get('mycontroller','MyController@loadview');



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

Laravel route ADMIN returns 404

I can't seem to access route admin. Every other route name I checked so far works fine, except this one. IE, the script runs fine if I change it to admins.

For testing purposes I even placed the route at the top:

enter image description here

But all I get is 404:

Not Found

The requested URL /admin was not found on this server.

Apache/2.4.17 (Win64) OpenSSL/1.0.2h PHP/5.6.16 Server at dev.example.com Port 80

Since it works on the PROD server just fine, I assume it's a local issue ( maybe even Windows? ).

Any idea what could be wrong?

By the way, there are no admin folders that could mess things up:

enter image description here

and nothing in the .htaccess file:

Options +FollowSymLinks
RewriteEngine On

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



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

Laravel 5 : Setting limitations on uploaded files without changing php.ini?

I learned it is required to modify the values in php.ini in order to set the limitation for uploading files. However, I'm in a situation where I can't touch php.ini.

Let me explain the problem briefly.

<input type="file" name="thumbnail" accept="image/*">

I'm trying to get the thumbnail and get it in a controller.

if($this->request->hasFile('thumbnail')){
    $file = $this->request->file('thumbnail');
    //Other tasks
}

If the file size is over a certain point, I'd like to prevent it and show a warning. However, apparently, if the uploaded file is over the limit, request->hasFile() returns false even though it's actually true. (I saw that by dd())

It's probably impossible to catch this type of error by hasFile(), since it simply doesn't catch it.

Any advice would be appreciated.



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

Error: Using undefined validator "validate_strength" and Error: Using undefined validator "validate_confirmation"

I have used Jquery Form validator in my laravel application. But validation on password and password confirmation is not working. Console through the following error:-

jquery.form-validator.js:1276 Uncaught Error: Using undefined validator "validate_strength". Maybe you have forgotten to load the module that "validate_strength" belongs to?

and

jquery.form-validator.js:1276 Uncaught Error: Using undefined validator "validate_confirmation". Maybe you have forgotten to load the module that "validate_confirmation" belongs to?

Following is my HTML Code from view-source

.....
<div class="form-group row required">
    <label for="password_confirmation" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
        <input placeholder="Enter Password" class="form-control" data-validation="strength" data-validation-strength="2" name="password_confirmation" type="password" value="" id="password_confirmation">
        <span style="color: #c9302c"></span>
     </div>
 </div>
 <div class="form-group row required">
     <label for="password" class="col-sm-2 control-label">Confirm Password</label>
     <div class="col-sm-10">
         <input placeholder="Re-enter Pasword" class="form-control" data-validation="confirmation" name="password" type="password" value="" id="password">
         <span style="color: #c9302c"></span>
      </div>
 </div>
 .....

and my js code

(function($, window) {
window.applyValidation = function(validateOnBlur, forms, messagePosition, xtraModule) {
    if( !forms )
        forms = 'form';
    $.validate({
        modules : 'security',
        form : forms,
        language : {
            requiredFields: 'Required Fields'
        },
        validateOnBlur : validateOnBlur,
        lang : 'en',
        onValidate : function($f) {
            var $callbackInput = $('#callback');
        },
        onModulesLoaded : function() {
            var optionalConfig = {
              fontSize: '12pt',
              padding: '4px',
              bad : 'Very bad',
              weak : 'Weak',
              good : 'Good',
              strong : 'Strong'
            };

            $('input[name="password_confirmation"]').displayPasswordStrength(optionalConfig);
        }
    });
};
window.applyValidation(true, '#candidate-signup', 'top');
})(jQuery, window);



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

Making unique field validation while updating

I am trying to validate for the unique record While editing but it always displays the field must be unique. basically i need to ignore the value of that id. id is the primary key.

$validator=Validator::make($request->all(),[
'name'=>'required',
'telephone'=>'required|unique:telephone',
'email'=>'unique:telephone',
'altemail'=>'unique:telephone',
'image'=>'image',

]);

if($validator->fails()){
return redirect('/telephone/addview')
    ->withErrors($validator);   
     }



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

lundi 30 mai 2016

Laravel - What to write in view to get current prefix

Basically what I wan't to do is to automatically change de prefix so I only have one view. The links could look something like this.





I use Laravel 5.2

This is the controllers i use:

//Controllers for states
Route::group(array('prefix' => 'california', "namespace" => 'Test' ), function() {    
    Route::get("/all", "CalifornaPositionController@all");
    Route::get('/search',['uses' => 'CalifornaPositionController@getSearch','as' => 'search']);
    Route::get('/show/{id}', 'CalifornaPositionController@show');

});
Route::group(array('prefix' => 'florida', "namespace" => 'Test' ), function() {    
    Route::get("/all", "FloridadPositionController@all");
    Route::get('/search',['uses' => 'FloridadPositionController@getSearch','as' => 'search']);
    Route::get('/show/{id}', 'FloridadPositionController@show');

});
Route::group(array('prefix' => 'arkansas', "namespace" => 'Test' ), function() {    
    Route::get("/all", "ArkansasPositionController@all");
    Route::get('/search',['uses' => 'ArkansasPositionController@getSearch','as' => 'search']);
    Route::get('/show/{id}', 'ArkansasPositionController@show');

});



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

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.



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

laravel 5.2 eloquent orderby on relationship result count

i have two tables website_link and website_links_type, website_link is related website_links_type with hasmany relationship.

$this->website_links->where('id',1)->Paginate(10);

and realtionship

 public function broken()
{
    return $this->hasMany('App\Website_links_type')->where('status_code','!=',"200");

}

now i want to get result from website_link table but Orderby that result on count of broken relationship result.



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

Laravel 5 Bleeding From Protected $Hidden

In my App/User I have the following:

protected $hidden = ['name', 'password', 'email', 'remember_token','created_at', 'updated_at','api_token','gmail_id','Personal'];

My understanding was that this was used to prevent sensitive information stored in the database as part of the model from leaking out into the view.

But it doesn't seem to be working?

When I query the users table from a many-to-many relationship, and print_r() my variable, I get to see all the data from the given row in the Users table, including the hidden columns.

What am I doing wrong?

In the controller : $achievements = User::where('id', Auth::user()->id)->first()->achievements()->orderBy('Time', 'desc')->take(1)->get();

In the view:



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

Using serial number iwith paginate

I am trying to retreive serial number in the blade template with variable i.

    <?php $i=0;?>
    @foreach ($lists as $li)
    <tr><td><?php $i++;?></td><td></td><td>
    </td><td></td>
    @endforeach
    {!! $lists->render() !!}

but i am using paginate in controller:

$lists=telephone::orderBy('name')->simplePaginate(10);

so, until the first page the serial number is ok. but for the second page. i starts from 1 again.



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

Laravel validator only displaying message after reloading

I am trying to validate the image using validator

    $validator=Validator::make($request->all(),[
        'image'=>'image',
        ]);

if($validator->fails()){
    return redirect('/pop/add')
        ->withErrors($validator);   
         }

But when i add the file except the image it is displaying MethodNotFound Exception instead of the error message and when i reload the page it then displays the validation error message.

The view looks like:

    <form method="POST" action="" role="form" enctype="multipart/form-data">
{!! csrf_field() !!}
<label>Upload your photo:</label><input type="file" name="image" ><br>

and the route:

Route::get('/pop/addview','popcontroller@addview');
Route::post('/pop/add','popcontroller@addnow');



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

Where are logs located?

I'm debugging a JSON endpoint and need to view internal server errors. However, my app/storage/logs dir is empty and it seems there are no other directories dedicated to logs in the project. I've tried googling the subject to no avail.

How can I enable logging, if it's not already enabled and view the logs?



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

How to sort this eloquent collection?

I am currently working on a beer application with checkins. A user checkin represents a beer he/she has drank. I am now dealing with checkins of the currently logged in user and also the checkins of their friends which I have set up through a friendship table.

I am grabbing a collection of user friends and an instance of the currently logged in user and I am adding them together like so:

// merge the currently logged in user with their friends
$users = $users->add($user);

I now have a collection of the logged in user and their friends and ultimately want to display some sort of timeline with their checkins. My main issue is that whenever I want to use something like this:

@foreach($users as $user)
     @foreach($user->checkins as $checkin)
         // my code
     @endforeach
 @endforeach

I get all users checkins but I am getting the output chunked/grouped per user. Preferably I would just like to sort them on age and not per user so I can create an actual timeline. Now I am getting a block of all of user 1's checkins followed by a block of user 2's checkins, etc.

How can I prevent this behaviour and simply show the latest checkin down to the oldest one?



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

Laravel 5.1 DB:select toArray()

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

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

For example

$result = DB::select('select * from users');

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::__set_state(array(
        'id' => 1,
        'first_name' => 'Pavel',
        'created_at' => '2015-02-23 05:46:33',
    )),
    1 => stdClass::__set_state(array(
        'id' => 2,
        'first_name' => 'Eugene',
        'created_at' => '2016-02-23 05:46:34',
    )),
...etc...

)



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

Laravel Notifications system, reserved method?

I am building a simple notifications system in laravel for my users.

I created the notifications table and I'm linking it to user model using:

public function notifications(){
    return $this->hasMany('App\Notification','user_id');
}

When I call this, it returns null, even when there are notifications.. Now, if I change it to this:

public function the_notifications(){
    return $this->hasMany('App\Notification','user_id');
}

It works fine.

What's going on?



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

Eloquent relationships query building method returns empty

I have a one-to-many relationship, which works perfectly when using the relationship as a property on a query, but when i try to use it as a method it always return empty.

User Model

public function reports()
{
    return $this->hasMany('App\Report', Report::COL_USER_ID, self::COL_ID);
}

Report Model

public function user()
{
    return $this->hasOne('App\User', User::COL_ID, self::COL_USER_ID);
}

This Works

$reports = User::find($id)->reports;

This Doesn't and i need something like this

$reports = User::find($id)->reports()->orderBy(Report::COL_CREATED_AT, self::ORDER_BY_DESC);

According to the eloquent doc, "since all relationships also serve as query builders, you can add further constraints", so that should totally be retrieving the proper data, am I missing something? Thanks in advance for any help



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

Displaying array data within table

I am trying to display some data within a table. I have the following headers

<thead>
    <tr>
        <th>Lead ID</th>
        <th>Category</th>
        <th>Client Name</th>
        <th>Quote ID</th>
        <th>Amount</th>
        <th>Amount Tax</th>
        <th>Amount inc Tax</th>
        <th>Cost</th>
        <th>Cost Tax</th>
        <th>Cost inc Tax</th>
    </tr>
</thead>

In terms of the data I am passing my view, it looks like the following

[6] => Array
(

    [leadData] => Array
        (
            [LeadID] => 1266283
            [Client] => Test Client
            [Category] => Lead
        )
    [quoteDataIssued] => Array
        (
            [QuoteID] => Q12459
            [Amount] => 1500.00
            [AmountTax] => 300.00
            [AmountIncludingTax] => 1800.00
            [EstimatedCost] => 0.00
            [EstimatedCostTax] => 0.00
            [EstimatedCostIncludingTax] => 0.00
        )

    [quoteDataIssued] => Array
        (
            [QuoteID] => Q12458
            [Amount] => 0.00
            [AmountTax] => 0.00
            [AmountIncludingTax] => 0.00
            [EstimatedCost] => 0.00
            [EstimatedCostTax] => 0.00
            [EstimatedCostIncludingTax] => 0.00
        )

)

The code I am currently using to display this data is like so

@foreach($forecastArray as $array)
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
@endforeach

Now the problem with the above code is that it can only handle one quote. In the data example I have shown, you can see that this one has 2 quotes. If there are more than one quote, then the additional quotes should display on the next tr.

Is there any way this can be achieved? I was thinking about a foreach within the tr to loop the number of quoteDataIssued, but would this require an inner table? (cant do a nested tr)

Thanks



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

Is there a initalSetup() function or something likje that in laravel?

I have developed an app in Laravel (and i used this plugin to add roles/permissions http://ift.tt/1dURk13)

I need to create some basic data for my app in Laravel only the first time the app is used (a few roles and permissions), this data shouldnt be created every time.

I couldnt find a function or event which i could use. Im trying to avoid doing:

if(role is not created)
    create it
else
    do nothing



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

SQL error in Laravel when moving project between machines

I just moved my laravel project from one machine to another. What I didn was: -Create a new Laravel Homestead machine. -Copy all files from my laravel app's folder

The website serves ok from my new machine but any database dependant operation fails because the tables aren't created in my new server. The error is the following:

QueryException in Connection.php line 673: SQLSTATE[42S02]: Base table or view not found:

The migrations are present in my new machine but I cant do a

php artisan migrate

or a

php artisan migrate:refresh

since both return

[Symfony\Component\Debug\Exception\FatalErrorException]
Cannot declare class CreateUsersTable, because the name is already in use

I've spent so much time here I don't know what to do.



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

Laravel 5.2 insert an array at once and update if exists

I'm trying to insert an array at once and i also want to update if exists. But i get this error.

$jobs = array();

//Iterate over the extracted links and display their URLs
foreach ($links as $link){

        $data = get_job_info($link);

        $jobs[] = [
            'title' => $data['title'],
            'full_desc' => $data['desc'],
            'to_date' => $data['date'],
            'ad_type' => 'fb'
        ];

    }
}

DB::table('customer_position')->insert($jobs);



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

Laravel 5.2/Dingo API resource link in the response

I'm trying to use Dingo API to implement RESTful backend APIs for our webapp. Best practices say that response payload should contain links to the returned resource objects. It can be in the form of _link or href. I don't see a way to include this in the response without handcrafting resource URL. I would like to have the response something like...

[
 { 
  'person': "Joe",
  '_link': 'http://ift.tt/1U7xa9S'
 },
 {
  'person': "Pat",
  '_link': 'http://ift.tt/1smJjBo'
 }
]

Is there a way I can include a resource link in the response?



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

Laravel get model optional with or separately?

I have:

ItemRepo

class ItemRepo {
    ...

    public function findByNameAndDate($name, Carbon $date, $with = null) {
        $item = Item::where('name', $name)->where(DB::raw('DATE(created_at)'), $date->toDateString());
        if($with) {
            $item->with($with);
        }
        return $item->first();
    }
}

Which is called from:

ItemController

...
use App\Repos\ItemRepo;
...

class ItemController extends Controller
{
    protected $repo;

    function __construct() {
        $this->repo = new ItemRepo();
    }

    public function show($day, $month, $year, $name) {
        $date = Carbon::createFromDate($year, $month, $day);
        $item = $this->repo->findByNameAndDate($name, $date, 'likes');
        return $item;
    }
}

You see I have an optional $with parameter for when I want to bring back any relationships, in this case I wanted all the likes for an item.

Is this the right way to do it? or would it be better to simply get the Item model, then pass that model to a LikeRepo that e.g. has a function called countLikes or getLikes. However in that case you are doing two queries and not a single larger one (which is why I am unsure of which is the best way to go).



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

Laravel 5 macros with javascript

The situation - i wont make macros for Form, that include html and javascript. According to the http://ift.tt/1sWYVMt i made provider and include the macros file

    Form::macro('multiple_select', function($name, $list = array(), $selected = null, $options = array())
{
    $select =  Form::select($name, $list, $selected, $options);
    $button = '<button type="button" class="btn button_add_multi_item">
            <i class="fa fa-fw fa-plus"></i>
        </button>';
    $select = $select . $button;
    $select .= '<script type="text/javascript" src="' . @asset('assets/js/macros/multiple_select.js') . '"></script>';
    return $select;

});

This element include select and + element. By clicking on this element there should generate hidden input and span with selected option from the select. This is done by javascript in multiple_select.js file. The problem is - that jquery library file included in layout at the bottom of the page, and i got the error

Uncaught ReferenceError: $ is not defined

If i wrote in main layout -

        @yield('macros_scripts')
</body>

And in macros file

$select .= '@section("macros_scripts")<script type="text/javascript" src="' . @asset('assets/js/macros/multiple_select.js') . '"></script>@endsection';
    return $select;

then php generate string

@section("macros_scripts")@endsection

It doesn't handled by the blade template engine. So only 1 thing i can do - it's include jquery in the top of layout. But i beleave that there is other, correct way to include js in macros. Any tips, helps?



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

Correct way to load translated data Laravel 5.2

I am building my first multilingual Laravel website.

For the translations i am using this package: laravel-localization.

In my database i have the columns set up like this:

  • title (english title)
  • title_nl (dutch title)
  • title_fr (french title)

I have read the laravel documentation on Localization and set up my error messages this way. But now i'm confused on how to correctly show the different languages for my views.

Should i do something like this:

@if( LaravelLocalization::getCurrentLocale() == 'nl')
<p></p>

@elseif(LaravelLocalization::getCurrentLocale() == 'fr' )
 <p></p>

@else
  <p></p>
 @endif

This seems extremely messy and not the correct way to handle this, because expanding this would be a nightmare.

Or do i need to use the build in localization functions for this like so:



Or does that defeat the purpose of the package i am using?



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

Bypass "mass assignement" laravel

I have hundreds of fields in my table and I dont want to write all the field in the$fillablearray. Is there any way tobypass $fillable process` ?

class MyClass extends Eloquent {

protected $fillable = array('firstField', 'secondField',.......);

}



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

Base table or view not found: 1146 Table in laravel

i was create one model file and try to fetch the table data using model. every time it's show below error

"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_student.students' doesn't exist (SQL: select * from students)"

controller file. it's look like to the following

namespace project1\Http\Controllers;
use Illuminate\Http\Request;
use project1\Student;
use project1\Http\Requests;
class StudentController extends Controller
{


public function index() 
{

    $students = Student::all();
    return view('student_form',compact('students'));

}
}



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

Laravel - Getting error when incrementing table field value

I am updating number of views count when user reloads the page and I have written this code:

public function index()
{
    $ProjectIdx = str_slug(Request::segment(2), "-"); // Getting page id
    if(ctype_digit($ProjectIdx)) {
        DB::table('project')
            ->where('ProjectIdx', $ProjectIdx)
            ->increment('NumViews');
    }
}

but when the count is greater than 99 I am getting this error:

QueryException in Connection.php line 651:

SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 (SQL: update `project` set `NumViews` = `NumViews` + 1 where `ProjectIdx` = 511)

Table structure:

Name        Type
----------  -------
ProjectIdx  int(11)
NumViews    int(11)

Any Idea?

Thanks.



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

Transactions doesn't work on some tests

I'm working with Laravel 5.2 and phpunit and i'm writing some test for my application. until now i got no problem, and today i encounter something weird and I can't find a way to handle it.

Some of my test file doesn't use transactions although the others does.

i use use DatabaseTransactions; in my TestCase class with is extended in every test file i got.

Most of my test works without any troubles but some of them does not.

Here is one which works withotut any troubles :

class V2LikeTest extends TestCase {

        protected $appToken;
        protected $headers;    

        public function setUp() {
            parent::setUp();
            $this->generateTopic(1);

        }

        /** LIKE TOPICS */
        /** @test */
        public function it_likes_a_topic() {
            $job = new ToggleLikeJob(Topic::first());
            $job->handle();

            $topic = Topic::first();
            $this->assertTrue($topic->present()->isLiked);
            $this->assertEquals(1, $topic->nb_likes);
        }
    }

and this one with troubles:

class V2TopicTest extends TestCase {

    private $appToken;
    private $headers;

    public function setUp() {
        parent::setUp();
        $this->generateCompany(1);

    }

    /** @test */
    public function it_create_a_topic() {
        $new_topic_request = new Request([
            'content' => str_random(100),
            'type' => Topic::TYPE_FEED_TEXT
        ]);
        $job = new CreateFeedTopicJob($new_topic_request->all());
        $job->handle();

        $this->assertCount(1, Topic::all());
    }

}

It's been a while now that i'm looking for the solution but not able to find it. Did someone already meet this troubles?

edit: GenerateTopic function use generateCompany just in case ;)



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

Soft Deleting through relationships laravel 5

I want to soft delete a row and the rows of another table which references this model, but keep getting mysql foreign key constraint error, which i presume is due to the fact that the foreign key still exists and the row just has an updated deleted_at column

User Migration:

public function up()
{
    Schema::create(self::TABLE_NAME, function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->nullable();
        $table->string('name')->nullable();
        $table->string('email')->nullable();
        $table->string('img_url')->nullable();
        $table->string('location')->nullable();
        $table->string('bio')->nullable();
        $table->string('following_user_ids')->nullable();
        $table->string('following_channel_ids')->nullable();
        $table->string('follower_ids')->nullable();
        $table->string('social_id')->unique();
        $table->string('role')->default(3);
        $table->string('password')->nullable();
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });
}

Report Migration:

public function up()
{
    Schema::create(self::TABLE_NAME, function (Blueprint $table) {
        $table->increments('id');
        $table->string('location')->nullable();
        $table->string('channel_ids')->nullable();
        $table->unsignedInteger('user_id');
        $table->string('url')->unique();
        $table->string('title');
        $table->string('video_name')->nullable();
        $table->string('description');
        $table->double('lat')->nullable();
        $table->double('lng')->nullable();
        $table->string('comments')->nullable();
        $table->integer('like_status')->default(0);
        $table->string('liker_ids')->nullable();
        $table->string('thumb_url_small')->nullable();
        $table->string('thumb_url')->nullable();
        $table->string('thumb_url_large')->nullable();
        $table->integer('view_count')->default(0);
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::table(self::TABLE_NAME, function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on(CreateUsersTable::TABLE_NAME);
    });
}

User Model

public static function boot()
{
    parent::boot();

    static::deleting(function($user)
    {
        $user->reports()->delete();
    });
}

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

public function reports()
{
    return $this->hasMany('App\Report', Report::COL_USER_ID, self::COL_ID);
}

Report Model

public function user()
{
    return $this->hasOne('App\User', User::COL_ID, self::COL_USER_ID);
}

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

Deleting user

 public static function deleteUser($id)
{
    // Added this because Model static::deleting/deleted had no effect
    // this soft deletes the report, but i fail to delete user on key constraint error at delete user
    try {
        // delete users reports if they exist
        $reports = Report::where(Report::COL_USER_ID, $id)->get();

        if (isset($reports)) {
            foreach ($reports as $report) {
                DeleteReportController::deleteReport($report->id);
            }
        }
    } catch (\Exception $ignored) {
    }

    try {
        User::where(Report::COL_ID, $id)->delete();
    } catch (\Exception $e) {
        throw new ModelNotFoundException('Could not delete user. ' . $e->getMessage(), 404);
    }
}



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

Class not loading on Hosting but works on localhost - Laravel 5

I have a Laravel 5 project running perfectly on localhost. I uploaded the project to a webhost and suddenly i get an error on a simple class.

This is the error:

FatalThrowableError in HomeController.php line 20:
Fatal error: Class 'App\Blogpost' not found

The Homecontroller code is this:

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Blogpost;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $blogposts = Blogpost::latest()->take(6)->get();

        return view('pages/start', compact('blogposts'));
    }
}

This code is pretty basic and works fine on localhost so i assume that the problem is located elsewhere, but i'm not sure where to begin searching?

For testing purposes i put all the code from Homecontroller in comments and than i just get an error on something else so the problem is situated elsewhere.

My localhost runs on MAMP with a Apache Server with PHP7 . Hosting also runs on Linux + Apache + PHP7 .

I have uploaded other laravel projects to the same server with the same configuration without any problems.

this is the link if that helps: http://dev.mayan-co.com



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

dimanche 29 mai 2016

building search function in laravel 5

I have this view to search for name or telephone no.

<form method="POST" action="">
 {!! csrf_field() !!}
<input type="text" name="search" placeholder="Name or Telephone no.">
<input type="submit" class="btn-btn-default" value="search">

The route redirecting to this controller:

 public function search(Request $request)
  {
        $name=$request->get('search');
        $search=telephone::where('name','like',$name)
                            ->paginate(5);

        return view('telephone.searchview',['search'=>$search]);
}

which then supposed to show this view:

<thead style='background-color:silver'><tr><td>S.N.</td><td>Name</td><td>Telephone No.</td><td>Mobile No.</td><td>Options</td></tr></thead>
@foreach ($search as $li)
<tr><td></td><td></td><td></td><td></td>
<td>here</td></tr></table>
@endforeach
{!! $search->render() !!}

i got the error: TokenMismatch



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

How to make a notification like email in PHP Laravel?

I am using laravel 5.0 and datatables 1.9. I want to have a notification system like in email on my dashboard page like in the image below. It shows the number of the new data inserted. And I want when I click dashboard, the row of new data is get highlight or the font is bold, and the number in the dashboard become "0" or disappear. Do you know how to do it? thanks.



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

Action refuses to return the boolean value

I have the standard destroy action:

public function destroy($id)
{
    return Quiz::find($id)->delete();
}

Which is accessed by the following AJAX call:

// The CSRF token is included automatically!
$.ajax({
    url: /quiz/10,
    type: 'POST',
    data: {_method: 'DELETE'},
    success: function(response){
        if(response){
            // do stuff..
        }
    }
});

The problem

When the AJAX call is made, chrome console shows the following error:

enter image description here

Strange thing is, that everything works if I remove the return, but I need the status code to be returned. Can somebody explain why is this happening? Or, at least, how to debug this problem?



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

Laravel Function Not Updating Database

I am calling the function below

 function makeanote($type,$id){
$note = Notification::where("user_id",Auth::user()->id)->get();
if ($type == "user"){
if($id > $note->pluck("users") ){
$note->users = $id;
$note->save();  
return;
}   
}
return;
           }

Like so: makeanote($type,$id). The calling $type is "user" and the calling $id is "31".

In the database for my current user, the $note value at the users column is currently zero (0).

Therefore I would expect it to update to 31, but it is staying at zero. Am I using pluck() incorrectly?

Thank you.



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

Digital Ocean for Laravel 5.2

Up to now I have only used fully managed web hosting services like godaddy etc.

I would like to transition to digital ocean for improved performance and control.

Using digital ocean for hosting. I'm looking for the best current method of deploying laravel 5.2 web apps, maintaining the app using GIT and maintaining/updating/patching the digital ocean cloud server.

I think from what I've read the best option is to use the laravel forge service which would build the server environment including services like MYSQL and the new letsencrypt secure certificates.

So my requirements are-

Push app deployment linked to GIT.
MYSQL
PHP 7
laravel homestead
Mail server like mailgun
letsencrypt 
Nginx and LEMP on UNIX distribution appropriate for laravel
Composer
Firewall

Is laravel forge capable of automatically updating required security patches, upgrades for PHP and MySQL etc?

Or do you need to maintain the environment after the deployment?



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

Is it possible to use new line break in a language files?

I've tried to use <br />, \n\r, &#13;&#10; to start new line but all these symbols do not work, because Laravel escapes messages.

I wonder is there any way to start new line in a message?

// resources/lang/en

return [
    'some_message' => 'Some text &#13;&#10; New line here'
];

I understand I could extend Translator class or write my own helper, but I'm looking for more elegant solution.



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

JSON endpoints alongside regular actions in controllers

I have a QuizzesController which implements all of the standard restful actions: create, store, edit, etc. And I also have additional presentQuestion and answerQuestion:

public function presentQuestion 
{
    // . . .
    return response()->json($question);
}

public function answerQuestion($quiz_id)
{
    // . . .        
    $this->handleAnsweredQuestion($question_id);
}

Is it a good practice to mix the JSON endpoints with regular php actions in controllers, or can this design cause any unexpected problems in the future?



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

Whats the better approach in managing large repeating csv data in laravel?

I am adding a function to our existing Laravel application managing financial transaction related data. Each week we are getting the data in csv files using the below given predefined format. I am wondering which approach I should use to load that data into the database

  1. Should I load the csv data straight into a single table using same fields in the csv format? or;
  2. Should I split the table into originators, and destination?

e.g. csv format: transaction_id, date, Originator, origin_id, currency, amount, destination, destination_id,

This is especially important considering that in the end of the day, users will need to search for entities and their associations using an ID number or entity name

If it helps, we get millions of records in each csv file often with same individuals and entities repeating on either side of the transaction.

Thanks in advance :)



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

How to display data returned from ajax response as a view in laravel

everyone I'm new to Ajax, and want to return a partial view in laravel in response of an ajax call, so when I click on a link to display the data in a modal it does not work and saying trying to get property of none object. any help. this is my code:

<tr>
        <td style="border-right: 1px solid #ddd;"><?php echo $i;?></td>
         <td></td>
         <td></td>
         <td></td>
        <td> &nbsp; </td>
        <td></td>
         <td></td>
        <td></td>
        <td><span>$</span> </td>
        <td><span>$</span><?php echo $sale->quantity*$sale->unit_price;?> </td>
    <td>
       <a href="#bill" class="btn btn-xs btn-green mr-5" type="button" tabindex="0" data-toggle="modal" data-target="#reportModal" onclick="load_modal_data('','/sales/bill','billContent')">
                                            <i class="fa fa-pencil"> Bill</i></a>
                                        <a href="/purchase/item" class="btn btn-xs btn-green mr-5"><i class="fa fa-search"> View</i></a>
                                        <a href="#" class="btn btn-xs btn-lightred"><i class="fa fa-remove"> Del</i></a>
                                    </td>
                                </tr>

the Js and Ajax:

function load_modal_data(identity, route,target_tag)
{

    $.ajax({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
        url: route,
        type:'post',
        data:{ id: identity},
        success:function(result){
            console.log(result)
            $('#'+target_tag).html(result);
        }
    })
}

the controller:

public function bill()
{
    $id = Input::get('identity');
    $sales = DB::table('sales')
        ->join('brands','brands.bid','=','sales.brand_id')
        ->join('units','units.unit_id','=','sales.unit_id')
        ->join('categories','categories.cat_id', '=','sales.category_id')
        ->join('customers','customers.cid','=','sales.c_id')
        ->select('sales.*','brands.brand_name','categories.category_name','customers.fname','customers.lname','units.unit_name')
        ->where('sales.sale_id',$id)->first();
    $returnHTML = view('partials.item-bill')->with('sales',$sales)->render();
    return response()->json(array('success'=>true, 'html'=>$returnHTML));
}

Note: I'm using Laravel 5.2



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

Laravel Download from S3 To Local

I am trying to download a file that I stored on S3 to my local Laravel installation to manipulate it. Would appreciate some help.

I have the config data set up correctly because I am able to upload it without any trouble. I am saving it in S3 with following pattern "user->id / media->id.mp3" --> note the fact that I am not just dumping files on S3, I am saving them in directories.

After successfully uploading the file to S3 I update the save path in my DB to show "user->id / media->id.mp3", not some long public url (is that wrong)?

When I later go back to try and download the file I am getting a FileNotFoundException at S3. I'm doing this.

$audio = Storage::disk('s3')->get($media->location);

The weird thing is that in the exception it shows the resource that it cannot fetch but when I place that same url in a browser it displays the file without any trouble at all. Why can't the file system get the file?

I have tried to do a "has" check before the "get" and the has check comes up false.

Do I need to save the full public URL in the database for this to work? I tried that and it didn't help. I feel like I am missing something very simple and it is making me crazy!!



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

Laravel migrations: create referenced table before making a reference to it

Here is my migration method:

public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('item_type_id')->unsigned();
        $table->integer('character_class');
        $table->integer('character_race');
        $table->integer('required_level');
        $table->integer('quality');
        $table->integer('durability');
        $table->integer('buy_price');
        $table->integer('sell_price');
        $table->timestamps();
    });

    Schema::table('items', function($table) {
        $table->foreign('item_type_id')->references('id')->on('item_types')->onDelete('cascade');
    });
}

The problem is that migration for the item_types table is after items migration. So there is no item_types table while creating items table, then migration will fail at creating foreign key. Is there a way to delay foreign constraints and run them after table creations? Or I have to separate the foreign constraints to another migration?! Thanks.



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

Store uploaded images with Laravel 5

I'm trying to upload, convert and store an image in Laravel using Image Magick.

Inside App\Http\Controllers\ArticleController:

$image = $this->storeMainImage($request->file('thumbnail'));

The function:

private function storeMainImage($file) {
  $folder = 'uploads/images/'; <--- ?????
  $code = uniqid();
  $thumb_code = $folder . 'thumb_' . $code . '.jpg';
  $image_code = $folder . $code . '.jpg';
  if(@is_array(getimagesize($file))){
    exec('convert '.$file.'  -thumbnail 225x225^ -gravity center -extent 225x225  -compress JPEG -quality 70  -background fill white  -layers flatten  -strip  -unsharp 0.5x0.5+0.5+0.008  '.$thumb_code);
    exec('convert '.$file.'  -compress JPEG -quality 70  -background fill white  -layers flatten  -strip  -unsharp 0.5x0.5+0.5+0.008  '.$image_code);
    return $image_code;
  } else {
    return false;
  }
}

I don't get any errors with this, but I have no idea if it's actually uploading the file and where abouts it's storing it.



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

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



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

samedi 28 mai 2016

Laravel 5 Get size from all files inside a directory

Im trying to make a simple file manager in laravel, really I just want to see all the files from 'files' folder, and using laravel Storage I managed to get the name from all the files inside the folder, but i want to get more data like the size of each file.

Controller:

public function showFiles() {
    $files =  Storage::disk('publicfiles')->files();
    return view('files')->with('files', $files);
}

View:

@foreach($files as $file)
    <tr>
        <td></td>
        <td></td>
        <td class="actions-hover actions-fade">
            <a href=""><i class="fa fa-download"></i></a>
        </td>
    </tr>
@endforeach

Getting this .

As I said I want to get the size, but how could I do that, I tought about processing that in the view but I don't really want to do that.

That being said, I actually know how to do it like this:

@foreach($files as $file)
    <tr>
        <td></td>
        <td>
        <?php
        $size = Storage::disk('publicfiles')->size($file);
        echo $size;
        ?>

        </td>
        <td class="actions-hover actions-fade">
            <a href=""><i class="fa fa-download"></i></a>
        </td>
    </tr>
@endforeach

But I think it is not right to do that in the view right?



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

No supported encrypter found issue

When i post my form on my laravel (5.2) i get this when it has to return some value to the former page.

MY CONTROLLER

class WsRegisterController extends Controller{

public function register()
{
    $wsregistration = Input::all();
    $wsUserName = Input::get('name');
    $wsUserEmail = Input::get('email');
    $wsUserPassword = Input::get('password');

    /* Check if user is a bot */

    $wsrules = [
    // 'g-recaptcha-response' => 'required|recaptcha', capthcha
    'name'   => 'required|min:2|max:32',
    'email'  => 'required|email',
    'password' => 'required|alpha_num|min:8'
    ];

    $wsvalidator = Validator::make($wsregistration, $wsrules);

    if ($wsvalidator->passes()) {

        /* Check if the email address exits */

        $wsUser_count = User::where('email', '=', $wsUserEmail)->count();

        // return $wsUser_count; exit;

        if ( $wsUser_count > 1 ) {

            return Redirect::to('/test')->with(array('error_msg' => 'This email address exist, please use another email address.'));

        }
     }
   }
  }

So i tried stackoverflowing it with this link but it is still not working

CONFIG/APP.PHP FILE

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('o/tPhyhKmuLoJMWXZeV8b10OFoCT62z6WKuC3HO5Jbw='),// env('9TSL9BsEjZyoM9BjX9du0XaLnCDi4m4Z'),

'cipher' => 'AES-128-CBC',//'AES-256-CBC',

.ENV FILE

APP_KEY=base64:o/tPhyhKmuLoJMWXZeV8b10OFoCT62z6WKuC3HO5Jbw=
APP_URL=http://localhost

I even did this artisan command to generate new key php artisan key:generate please what did i do wrong @everyone.

No supported encrypter found error snapshot



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

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



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

angular laravel handle token expiracy

So, I'm using angularJs and laravel with tymon-JWTAuth and sattelite.

Everything so good so far but I wanted to match the sessionStorage token to expire the session on the laravel side.

How is this achievable since sessionStorage cant set Expiracy.

And if possible, how can I redirect to login if a $http request has the error 401 token_expired ?

Best regards,

Filipe



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

Laravel 5 eloquent custom with relationship

i have in my eloquent model the record id of an api served data, i wold like to load this data using the with method to prevent multiple api request, is there any way to create a custom with method?



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

Multiple dynamic url redirect in Laravel

I have looked at many similar questions bu they don't approach the real problem. I would like to redirect a user to a certain url just after login depending on a condition about the user.

I know this can be archieved with a middleware so I have tried this in app\Http\Middleware\RedirectIfAuthenticated.php

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::User()->check()) {
            $redirect = '/client';
            if (Auth::user()->hasRole('admin')){
                $redirect = '/admin';
            }
            return redirect($redirect);
        }
        return $next($request);
    }
}

I realise now this will not work just after login. I'd like to redirect a user depending whether he/she is an admin or a client. I know I could use: protected $redirectPath = '/url/to/redirect'; but I have multiple pages to redirect to.

What is the best way to do this?



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

Eager-loading only some of the properties

I have two models: Question and Answer. A question has-many answers. To eager-load a question's answers, one must write it like this:

$question->load('answers');

However, all of the answers' properties are loaded this way. The following code, while illustrating what I want to achieve, does not work:

$quesiton->load('answers')->select('id', 'body')

So, how can I eager-load questions' answers with only their respective id, and body properties?



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

Sort by average value of an one to many related table column

I have 2 models; Post and Rating

The Rating model contains an amount column which specifies how high something has been rated. This is based on 5 star rating so the amount can be a value from 1-5

The Post model has a one to many relation with the rating model and function called Ratings that returns the hasMany.

I'd like to get the 5 latest posts based on the average rating. For the average rating I've created a function that can be seen below

Note: the plural(Ratings) returns the hasMany relation where as the singular(Rating) returns a value which is the average rating

public function Rating(){
    return floor($this->Ratings()->avg('rating'));
}

Is it possible to retrieve posts ordered by the avg rating using the Eloquent QueryBuilder?

Currently I'm retrieving all posts and then using the sortBy method on the collection object in order get the ones with the highest average rating. The way I'm doing this can be seen below.

$posts = Post::all();

$posts = $posts->sortByDesc(function ($post, $key) {
    return $post->Rating();
});

Now if I'd only want to show 5 I still have to retrieve and sort everything which doesn't seem very resource friendly(In my eyes. I don't have any proof of this or say it is true).

So my question is the following: Is this doable using Eloquent instead of sorting the FULL collection.

Sub question: Will doing this with Eloquent instead of sorting the collection have any impact on efficiency?



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