jeudi 30 juin 2016

Multiple pdf creation using vsmoraes/laravel-pdf

I am using vsmoraes/laravel-pdf for pdf creation. For single pdf creation it works fine. But when I am trying to create multiple pdf it shows the error No block-level parent found. Not good. This is what i am doing in my controller code to generate pdf. Need help, thanks.

  <?php namespace App\Http\Controllers;

    use Vsmoraes\Pdf\Pdf;

    class HomeController extends BaseControler
    {


  private $pdf;

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

    public function helloWorld()
    {
        $html = view('pdfs.example1')->render();
        for($i=0; $i<3;$i++){
        return $this->pdf
            ->load($html)
            ->show();
             }
        }
    }



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

google map api drag and drop pin in laravel

I want to add drag and drop google Api. I've made a map the but I do not know how to make it can be a drag and drop. in there i want make my latitude and longitude is auto fill when i drop the pin

here my view :

 <label for="inputIsiBerita"> Latitude:</label>
         <input type="text" class="form-control" required name="latitude">
         <label for="inputIsiBerita"> Longitude</label>
         <input type="text" class="form-control" required name="longitude">

here my script :

<script>
              function initMap() {
                var map = new google.maps.Map(document.getElementById('map'), {
                  center: {lat: -7.0157404, lng: 110.4171283},
                  zoom: 12
                });
                var input = /** @type {!HTMLInputElement} */(
                    document.getElementById('pac-input'));

                var types = document.getElementById('type-selector');
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.bindTo('bounds', map);

                var infowindow = new google.maps.InfoWindow();
                var marker = new google.maps.Marker({
                  map: map,
                  anchorPoint: new google.maps.Point(0, -29)
                });

                autocomplete.addListener('place_changed', function() {
                  infowindow.close();
                  marker.setVisible(false);
                  var place = autocomplete.getPlace();
                  if (!place.geometry) {
                    window.alert("Autocomplete's returned place contains no geometry");
                    return;
                  }

                  // If the place has a geometry, then present it on a map.
                  if (place.geometry.viewport) {
                    map.fitBounds(place.geometry.viewport);
                  } else {
                    map.setCenter(place.geometry.location);
                    map.setZoom(17);  // Why 17? Because it looks good.
                  }
                  marker.setIcon(/** @type {google.maps.Icon} */({
                    url: 'http://ift.tt/1rXG5Bt',
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(35, 35)
                  }));
                  marker.setPosition(place.geometry.location);
                  marker.setVisible(true);

                  var address = '';
                  if (place.address_components) {
                    address = [
                      (place.address_components[0] && place.address_components[0].short_name || ''),
                      (place.address_components[1] && place.address_components[1].short_name || ''),
                      (place.address_components[2] && place.address_components[2].short_name || '')
                    ].join(' ');
                  }

                  var latitude = place.geometry.location.lat();
                  var longitude = place.geometry.location.lng(); 

                  $("input[name=coordinate]").val(address);
                  $("input[name=latitude]").val(latitude);
                  $("input[name=longitude]").val(longitude);

                  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
                  infowindow.open(map, marker);
                });

                // Sets a listener on a radio button to change the filter type on Places
                // Autocomplete.
                function setupClickListener(id, types) {
                  var radioButton = document.getElementById(id);
                  radioButton.addEventListener('click', function() {
                    autocomplete.setTypes(types);
                  });
                }

                setupClickListener('changetype-all', []);
                setupClickListener('changetype-address', ['address']);
                setupClickListener('changetype-establishment', ['establishment']);
                setupClickListener('changetype-geocode', ['geocode']);
              }
            </script>               
            <script src="http://ift.tt/299ixVJ"
        async defer></script>

and when i drag the pin its will auto change the point latitude and longitude



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

Displaying new label on a list item from the database

Written with StackEdit.

Please i have this list of data i want to display from the database but i want to give a label of new to a new data and nothing to an old data how do i achieve this in laravel

FOR EXAMPLE

db item list sample

THE CODE

                    <!-- desktop view -->
                    <div class="large-2 columns show-for-large-only">
                        <span class="new-user-list-label text-center montserrat-font white-text small-text-13">New</span>
                        @if ($user->created_at == Carbon::now())

                        @elseif ($user->updated_at == Carbon::now())
                            <span class="new-user-list-label text-center montserrat-font white-text small-text-13">New</span>
                        @endif
                        <span class="fa-stack fa-2x large-centered">
                            <i class="fa fa-circle fa-stack-2x tq-dark-blue-color"></i>
                            <i class="fa fa-user fa-stack-1x fa-inverse"></i>
                        </span>
                        <input name="" type="checkbox" class="checkbox-size-20">
                    </div>
                    <div class="large-10 columns show-for-large-only">
                        <ul class="no-bullet">
                            <li><h6 class="text-left montserrat-font small-text-15 capitalize"><b>USERNAME | </b> </h6></li>
                            <li><h6 class="text-left montserrat-font small-text-15 lowercase"><b class="uppercase">EMAIL | </b> </h6></li>
                            <li><h6 class="text-left montserrat-font small-text-15"><b>REGISTERED | </b> </h6></li>
                            <li><h6 class="text-left montserrat-font small-text-15"><b>ATTIRES MADE | </b> Attires made</h6></li>
                            <li><a href="#"><h6 class="text-left montserrat-font footer-links small-text-15">More info...</h6></a></li>
                        </ul>
                    </div>
                    <!-- /end desktop view -->



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

Calling eloquent relation multiple times doesn't return data

I'm having this strange behavior in Laravel 5.1 where when I call the relation of an eloquent model more than once within the same code execution, then the second time it doesn't have the data.

class Items extends Eloquent {
    public $table = 'items'

    public function subItems() {
        return $this->hasMany(Item::class, 'items_id');
    }
}

class Item extends Eloquent {
    public $table = 'items_item'
    public $fillable = ['items_id'];
}


$items = Items::create();
Item::create([
    'items_id' => $items->id,
]);
Item::create([
    'items_id' => $items->id,
]);


// works
$first = $items->subItems;
// no data
$second = $items->subItems;
// works
$third = $items->subItems()->get();

Is this normal behavior? Do i have to somehow reset something before calling the relation again?



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

Laravel elixir copy not working on symbolic links

I'm creating a modular Laravel 5.2 app, which consists of a number of proprietary packages loaded on a Laravel installation using composer.

Each of the packages are responsible of managing its own assets (copy to public folder, compress, versioning, etc). To accomplish this, I have a gulpfile that uses elixir for each package, and then, they are loaded on the main gulpfile of the laravel installation.

This is the main gulpfile.js on the laravel installation:

var filesystem = require("fs");
var gulp = require('gulp');
var elixir = require('laravel-elixir');

gulp.task('default', function() {
    runPackagesGulpFiles();
});

function runPackagesGulpFiles() {
    var packagesPath = 'vendor/my-organization/';
    filesystem.readdirSync(packagesPath).forEach(function (file){
        try {
            var gulpFilePath = packagesPath + file + '/resources/assets/gulpfile.js';
            var fileStat = filesystem.statSync(gulpFilePath);
            require('./' + gulpFilePath);
        } catch (error) {
            if (error.message.indexOf('no such file or directory') < 0) {
                console.error(error.stack);
            }
        }
    });
}

All the main gulpfile.js does, is execute the packages gulpfiles if they exist using a require() function.

The following is an example of a package gulpfile:

var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix.copy('vendor/my-organization/store-manager/resources/assets/js/', 'public/assets/js/elixir_components/store-manager/');
    mix.version([
        //Store structure versioning
        'assets/js/elixir_components/store-manager/stores/store.js',
        'assets/js/elixir_components/store-manager/stores/views.js',
        'assets/js/elixir_components/store-manager/stores/models.js',
        'assets/js/elixir_components/store-manager/stores/controllers.js',
        //Store resources versioning
        'assets/js/elixir_components/store-manager/resources/resources.js',
        'assets/js/elixir_components/store-manager/resources/views.js',
        'assets/js/elixir_components/store-manager/resources/models.js',
        'assets/js/elixir_components/store-manager/resources/controllers.js',
        //Store structure resources versioning
        'assets/js/elixir_components/store-manager/structures/structure.js',
        'assets/js/elixir_components/store-manager/structures/views.js',
        'assets/js/elixir_components/store-manager/structures/models.js',
        'assets/js/elixir_components/store-manager/structures/controllers.js',
    ]);
});

In a normal case scenario this works just fine. A normal case scenario being that the packages are loaded using composer.

However, for the development of the packages, I create a symbolic link in the vendor folder that points to the package folder in my local machine.

When I try to execute gulp in the development environment, I get a Cannot find module 'laravel-elixir' error:

[22:27:03] Using gulpfile ~/supermarket-cms/gulpfile.js
[22:27:03] Starting 'default'...
Error: Cannot find module 'laravel-elixir'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/home/vagrant/Code/store-manager/resources/assets/gulpfile.js:1:76)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
[22:27:03] Finished 'default' after 12 ms

Problem that I solved by installing laravel-elixir globally. But after I do so, the gulp task ends and my assets are not being copied.

[21:25:02] Using gulpfile ~/supermarket-cms/gulpfile.js
[21:25:02] Starting 'default'...
[21:25:02] Finished 'default' after 3.78 ms

No error whatsoever appears. Hope someone can help me. Thank you.



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

i have an error in laravel Class 'App\post' not found

my post controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Http\Requests;

use App\post;

class postController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // }

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{


    return view('posts.create'); 

}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
   $post=new post; 
   $post->title =$request->title;
   $post->body =$request->body;

   $post->save();

        dd("Hi");

        return Redirect::to('/')
            ->with('success','You have been successfully subscribe to us.');




  }      

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    //
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

App\HTTP\Controllers;>



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

Get currently created model id in Laravel 5

Laravel 5.2

I have some problem with getting model id:

    public function store(Request $request)
{

    $this->validate($request, [
        'title'   => 'required|max:255',
        'content' => 'required',
    ]);

    $data = $request->all();

    $page = new Page;

    $page->create($data);

    dd($page->id);

    return redirect()->route('admin.pages.index');
}

$page->id return null...

what am I doing wrong?



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

Laravel 5.2 Socialite Retrieve Null Email

i'm new to Laravel and i'm trying to make a social auth. I have seen some tutorials and I've got to retrieve user id, profile pic and name from Facebook. My problem is the email, it comes null.

My current object is this:

User {#195 ▼
  +token: "EAACYY1xBrzcBAO9KZAjZAZAZBQHWhbtZAb9lIXvH9Y6miRUiABImupk3ZCzHRxy2ZBxc9DU8f1ZAcrw0NEVMmy3GOQMSSyrmDTvMPyREvGm4pA1Ok6zI85LxES4Huy2ZCsxIUr2ISbLreLIv1ZACItUUoqqAnvVPyR4s0ZD"
  +id: "989087311199546"
  +nickname: null
  +name: "MyName"
  +email: null
  +avatar: "http://ift.tt/296NWa7"
  +"user": array:2 [▼
    "name" => "MyName"
    "id" => "MyId"
  ]
}

and my controller is:

class FacebookController extends Controller
{
   public function facebook()
    {
        return Socialite::driver('facebook')
            ->scopes(['email'])->redirect();
    }
    public function callback()
    {
        $user = Socialite::with('facebook')->user();

        return dd($user);
        // $user->token;
    }
}



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

In laravel, I am getting the view of current user as a follower of itself instead of followers.

In database i have following structure

id | following_id | followed_id 1 | 3 | 1 2 | 2 | 1

I have user model and it looks like this public function userFollows() { return $this->belongsToMany('Diskourse\Models\User','followers','following_id','followed_id');

}

public function userIsFollowed()
{
    return $this->belongsToMany('Diskourse\Models\User','followers','followed_id','following_id');
}

public function followers()
{
   return $this->userIsFollowed->merge($this->userFollows);
}

And at last view looks like this

            <h4>Followers</h4>

            @if(!$user->followers()->count())

            <p>No followers</p>

            @endif
                @foreach($user->followers() as $follower)

                    @include('user/partials/userblock')

                @endforeach
            </div>
        </div>

If its working it should display user 3 and 2 as a follower of 1. Instead current user profile block is displaying twice. Please Help !!!!



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

Laravel 5.2 : Getting form fields in controller method

I have the following form :

{!! Form::open(['action' => 'PublicController@showProfile','method' => 'post', 'class' => 'form-horizontal']) !!}
{!! Form::token(); !!}
    <input type="text" class="form-control" name="from">
    <span class="input-group-addon"> to </span>
    <input type="text" class="form-control" name="to"> 
    <button type="submit" class="btn blue">Query</button>
{!! Form::close() !!}

In my controller I am getting the form fields like this :

public function showProfile(Request $request)
{
    $to = $request->get("to");
    $from = $request->get("from");
    $giftReceived = App\GiftSent::whereBetween('created_at', [$from, $to])->get();
    dd($from);
    return view('user.profile',compact('giftReceived'));
}

In the above code dd($from) comes null

Am i missing something ?



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

Nginx 404 Not Found error

I recently had a server copied over from the previous host to an AWS server. The server is Ubuntu 14.04 and the project that I am trying to run is a Laravel 5 project. I have installed nginx as the web server, here is the default file in sites available and sites enabled:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root web/project/public;
    index index.php index.html index.htm;

    server_name server_domain_or_IP;

    location / {
            try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME$document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}

I have set cgi.fix_pathinfo = 0; in my php.ini file, as I was instructed to do.

There is a directory called "web" in which the project lives, and inside of the project folder lies the "public" directory.

When I try to go to the server's IP I get a 404 Not Found Error.

Any thoughts as to what may be going wrong?



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

Why laravel store session after the response has been sent to the browser?

The question is clear. as laravel documentation stated :

For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser

I guess it is because of response time saving but im not sure.



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

How to simulate Content-Type header in a test within a Laravel 5 package?

I'm currently building a Laravel package that injects a new method in Illuminate\Http\Request. The method I'm injecting has been completed and is expected to work nicely, but I also want to test it before releasing it.

My test requires me to change the request's Content-Type header, in order for me to see if the test is passing or no. So I have done the following to simulate the request:

use Orchestra\Testbench\TestCase as Orchestra;

abstract class TestCase extends Orchestra
{
    /**
     * Holds the request
     * @var Illuminate\Http\Request
     */
    protected $request;

    /**
     * Setup the test
     */
    public function setUp()
    {
        parent::setUp();

        $this->request = new Request;

        $this->request->headers->set('Content-Type', 'application/x-yaml');
    }
}

Then in my test I use the method I'm injecting into Request with $this->request->myMethod() and it's always returning false since the Content-Type header is not getting set to application/x-yaml.

/** @test */
public function it_should_do_what_i_need_it_to_do()
{
    dd($this->request->myMethod()); // Return type: boolean

    $this->assertTrue($this->request->myMethod()); // It fails!
}

How do I go on simulating the headers in a test in Laravel package development?



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

laravel 5 subdomain redirected to homepage

I have a site that can be access in stage.mysite.com and it has a subdomain profile.stage.mysite.com but it displays the content of stage.mysite.com when I try to access it.

in my server I have configured the hosting.

ServerAdmin webmaster@localhost
ServerName stage.mysite.com
ServerAlias *.stage.mysite.com
DocumentRoot /var/www/http://ift.tt/292wFy4

in my routes.php this is the code.

Route::group(['domain' => 'profile.stage.mysite.com'], function()
{
    Route::get('/', 'FrontendController@profile');
});

this I expect to be called. any ideas?



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

Query random with Laravel and exclude a specific row

How can I create a query random with laravel and exclude a specific row

I tried this :

return $this->user
            ->get()
            ->random(1)
            ->where('id', '!=', 1);



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

How I can set session variable on click button event before auth laravel

Please help me out. I want to create a session variable when user will click on button then after login that variable i can call on home controller. When I am doing the below coding session is remembering either user is clicking on button or not every time after login it is displaying 1hi.

The function is:

$('#sub').on('click',function(){
        <?php \Session::put('testings', true);  
        ?>
    });

and the controller after login where I want to display is below:

public function home($reset = null){


        // indexed previous documents.
        $this->createResourcIndex();
        $this->title = 'Home';
        $folders = $folderList = [];
        $userLoggedIn = false;
        $sharedFiles = [];
        if(\Auth::check()){
            if(\Session::get('testings'))
            {
                echo \Session::get('testings');
                \Session::forget('testings');
                echo "hi";
            }
            else{
                echo "hello";
            }
            die;
}
}

Please help me out where I am wrong.



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

Empty Object being passed to route

I am trying to work out why an empty object is being passed through my route. I have a user model

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

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

And I have a UserObjectives model

class UserObjectives extends Model
{
    protected $table = 'user_objectives';
    protected $guarded = [];

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

I then have an index controller which displays the default page. The index function gets the logged in User and passes it to the view

public function index()
{
    $loggedInUser = Auth::user()->getFirstName() . ' '  . Auth::user()->getLastName();
    $user = User::where('userName', '=', $loggedInUser)->first();

    if($user) {
        return view('index', compact('user'));
    } else {
        return view('auth.login');
    }
}

I am doing it like the above because I am mapping users from Active Directory. Within my index view, if I do the following I can see the details for the logged in user.



Within the index view, I have a link to a route which I pass the user object

{!! link_to_route('users.userObjectives.index', 'My Info', array($user), array('class' => 'btn btn-info')) !!}

Now within the UserObjectives Controller I have

public function index(User $user)
{
    dd($user);
}

Now for some reason the above displays an empty User Object. If I change it to the following, without User, I get the id of the logged in user.

public function index($user)
{
    dd($user);
}

Why would this function display an empty User Object even though I can see within the view that the User object I am passing does have data?

Thanks



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

GuzzleHttp Client request very slow

i am running a simple http request with guzzle

$client = new Client();
$response = $client->get("http://www.google.com");
return $response->getBody();

this is the result this is what i'm getting

as you can see i'm getting 11300 ms delay

and these are my headers these are my headers

i can't find where is the problem i doubt it's from the code

i've tried

file_get_contents("http://www.google.com");

i got 300ms reponse that's what strange is the problem from guzzle itself? please help i'm lost



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

How to set path to file in Laravel?

I have located file in root directory of Laravel.

From controller I try to get this file like as:

$shipments = json_decode(file_get_contents("Statistics.json"), true);

But I get error.

What correct path to specify for getting file?



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

Database seeders not working laravel 5

My database seeder stopped working at one point. it says its working but nothing happens, no error no nothing. Even when i corrupt the whole seeder file it still gives no error.

This is my table ----------

 Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('naam');
        $table->string('email')->unique();
        $table->string('password');
        $table->integer('level');
        $table->rememberToken();
        $table->timestamps();
    });

My seeder --------

DB::table('users')->insert([
        'naam' => 'test',
        'email'      => 'test@wolters.nl',
        'password'   => Hash::make('wolters'),
        'level' => 1,
        'created_at' => new DateTime(),
        'updated_at' => new DateTime(),
    ]);

Migrations work fine. But when i run php artisan db:seed, no errors and nothing in the database. enter image description here

It worked fine untill this morning.

Any ideas?

Thanks in advance



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

Cannot login with custom authentication connecting to another api

We are working on two laravel projects one for front end laravel and for backend api. I followed tutorials on connecting this two projects but make use of guzzlehttp. However I am getting undefined index password. I already dd the user['data'] in getUsers method and gettign the correct password. Can any one help me on this.

ApiUserProvider

<?php

namespace App\Auth;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Http\Request;

use GuzzleHttp\Client;

class ApiUserProvider implements UserProvider
{

    public function retrieveByCredentials(array $credentials)
    {
        $user = $this->getUserByUsername($credentials['username']);

        return $this->getApiUser($user);
    }

    public function retrieveById($identifier)
    {
        $user = $this->getUserById($identifier);

        return $this->getApiUser($user);
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
        return $user->getAuthPassword() == bcrypt($credentials['password']);
    }

    protected function getApiUser($user)
    {
        if ($user !== null) {
            return new ApiUser($user);
        }
    }

    protected function getUsers()
    {
        $client = new Client(['base_uri' => 'http://ift.tt/294zhj7']);

        $response1 = $client->request('POST', 'oauth/access_token', [
            'form_params' => [
                'client_id' => 'id1',
                'client_secret' => 'secret1',
                'grant_type' => 'password',
                'username' => 'email@yahoo',
                'password' => 'password'
            ]
        ]);


        $location = json_decode($response1->getBody(), true);

        $token = $location['access_token'];

        // Send a request to http://ift.tt/295jtJe
        $response2 = $client->request('GET', 'users/self', [
            'headers' => [
                'Authorization' => 'Bearer '. $token
            ]
        ]);

        $user = json_decode($response2->getBody(), true);
        return $user['data'];
    }

    protected function getUserById($id)
    {
        $user = [];

        if($this->getUsers()['email'] == $id){
            $user['id'] = $id;
        }

        dd($user);
        return $user ?: null;
    }

    protected function getUserByUsername($username)
    {
         $user = [];


        if($this->getUsers()['email']  == $username){
            $user['email'] = $username; 
        }

        return $user ?: null;
    }

    // The methods below need to be defined because of the Authenticatable contract
    // but need no implementation for 'Auth::attempt' to work and can be implemented
    // if you need their functionality
    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }

}

ApiUser

namespace App\Auth;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUser extends GenericUser implements UserContract
{


    public function getAuthIdentifier()
    {
        return $this->attributes['id'];
    }
}

UserController

public function login(Request $request)
{
    $email = $request->email;
    $password = bcrypt($request->password);

    if (Auth::attempt(['username' => $email, 'password' => $password])) {
        return "hello";
    } 
}

error enter image description here



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

mercredi 29 juin 2016

Laravel 5.1 Creating default object from empty value

I am using Laravel 5.1 PHP framework.When I try to update my record,i get the error "ErrorException in AdminController.php line 108: Creating default object from empty value".I have searched in google but i can't find any result to solve my problem.

routes

Route::get('/admin/no', 'AdminController@index');
Route::get('/admin/product/destroy/{id}', 'AdminController@destroy');
Route::get('/admin/new', 'AdminController@newProduct');
Route::post('/admin/product/save', 'AdminController@add');
Route::get('/admin/{id}/edit', 'AdminController@edit');
Route::patch('/admin/product/update/{id}', 'AdminController@update')

AdminController

 public function edit($id)
    {

        $product = Product::find($id);
        return view('admin.edit', compact('product'));

    }

    public function update(Request $request, $id)
    {

        $product = Product::find($id);
        $product->id = Request::input('id');
        $product->name = Request::input('name');
        $product->description = Request::input('description');
        $product->price = Request::input('price');
        $product->imageurl = Request::input('imageurl');


        $product->save();
        //return redirect('/admin/nο');

    }
    enter code here

edit.blade.php

div class="panel panel-info">
        <div class="panel-heading">
            <div class="panel-title">Edit Product</div>
        </div>
        <div class="panel-body" >
            <form action="/admin/product/update/{id}" method="POST"><input type="hidden" name="_method" value="PATCH"> <input type="hidden" name="_token" value="">
    enter code here



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

Using underscore synatx in URI with implicit controller in laravel

I know this:

If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:

public function getAdminProfile() {}

Want to the know about:

If i want to use "underscore" synatx in the URI. Is it possible with implicit controllers.

Like want to use user/admin_profile in the URI. What would controller look like?



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

Maatwebsite/Laravel-Excel what files does it change

which files does the above create and update.

Can anyone tell me the file locations as i have to push this from my local machine to server



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

Relationships returning wrong/null data (Laravel 5.2)

Got a domain table which has a One To Many relationship with domain_hosts_table, server_hosts_table and systems_table. So far so good.

Calling the table data:

$domains = Domain::with('domain_host', 'server_host', 'system')->get();

Domain model :

public function domain_host()
{
    return $this->hasOne('App\DomainHost', 'id');
}

public function server_host()
{
    return $this->hasOne('App\ServerHost', 'id');
}

public function system()
{
    return $this->hasOne('App\System', 'id');
}

DomainHost, ServerHost, System model :

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

Domains table :

enter image description here

So far so good.

Let's take a look at what this particular table returns while being foreached.

enter image description here

The first 2 rows should be the same (basing on their IDs), and all rows after the first 2 are just empty.

(dd of the fetched data, notice the relations being empty at 4th object, 1st object actually has data).

enter image description here



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

Laravel - blade append section

i need to run a js script in a subview, so i have a section with all my scripts and in the subview i try to append my script to the existing scripts.

HTML PAGE:

<html><head></head><body></body>@yield('scripts')</html>

SECTION:

@section('scripts') <!-- my standard scripts --> @stop

SUBVIEW:

@section('scripts') <!-- my new script --> @append

i already try with @parent inside subview @section('scripts') but doesn't work.

thank's



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

CKEditor Saved Data in Database to be displayed in Laravel Excel File

I'm using CKEditor as my comments textarea when inserting data. This saves data in the database as per database

When i try to export the comments, the data is not displayed in order i want to.

This is what i can see now: Excel File

Below are the codes for excel file:

<table class="table table-striped table-bordered">

<thead>
<tr>

    <th>Comments</th>

</tr>
</thead>
@foreach ($data as $row)
<tr>


    <td>

        <?php
        //to fetch data from comments db
                $comments= DB::table('comments')
                ->where('task_id', '=', $row->id)
                ->orderBy('id', 'desc')
                ->take(1)
                ->get();



        foreach($comments as $comment){
            echo $comment->comment;
            }
        ?>

    </td>


</tr>
@endforeach </table> 



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

Can only install one of: iron-io/iron_mq[2.0.0, 1.5.3] -- Laraworker vs ironQueue

I am having a problem while trying to use two wonderful packages iron-io/laraworker and laracollective/iron-queue at same project.

The prior package requires version (max) 1.5.3 of iron-io/iron_mq whereas the later one (v5.2) requires that the minimum version of iron-io/iron_mq has to be 2.0.0

So this is an non-compatible situation.

Any help on this will be appreciated.

P.S.: I don't want to write my own worker libraries - I would prefer it as a vendor package - but if nothing else is possible I can work with http://ift.tt/1pAtkr8.



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

Laravel 5 Many to Many is returning old data

I have been working on a basic Laravel 5 many-to-many demo. For some reason the lookup query is always coming back with fields that no longer exist. I have tried php artisan clear:cache made sure I am using sync to

namespace App;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   public function tags()
  {
    return $this->belongsToMany('App\Tag')->withTimestamps();
  }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{

  protected $fillable = [
    'name'
  ];

  public function posts()
  {
    return $this->belongsToMany('App\Post')->withTimestamps();
  }

}


/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
  $categories = Category::all();

  $tagIds = Tag::lists('id');
  $tagNames = Tag::lists('name');


  return view('posts.create')->withCategories($categories)->withTags($tagNames)->withTagIds($tagIds);
}

enter image description here



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

How do I access request arrays within arrays

I have the following request;

Collection {#278
  #items: array:3 [
    0 => array:2 [
  0 => array:8 [
    "id" => 631
    "name" => "OIL, FILTER O.E.M."
    "partno" => "235-00"
    "oemnumber" => "16099 003"
    "stock" => 0
    "price" => "30"
    "qty" => 1
    "total" => 30
  ]
  1 => array:8 [
    "id" => 23
    "name" => "SPEEDOMETER"
    "partno" => "122-"
    "oemnumber" => "25005 1013"
    "stock" => 0
    "price" => "276"
    "qty" => 1
    "total" => 276
  ]
]
1 => array:2 [
  0 => array:2 [
    "description" => "Oil change"
    "hours" => "1"
  ]
  1 => array:2 [
    "description" => "Tune up"
    "hours" => "2"
  ]
]
2 => array:15 [
  "id" => 1
  "custId" => 9046
  "bikeId" => 5238
  "trans" => "yes"
  "transDetails" => "call cab"
  "policies" => "Yes"
  "locker" => "1"
  "lockerContents" => "stuff"
  "estimate" => "Yes"
  "oldparts" => "Yes"
  "status" => "Pending"
  "created_by" => null
  "created_at" => "2016-05-19 14:40:59"
  "updated_by" => null
  "updated_at" => "2016-06-08 09:06:58"
]
]
}

I am getting this through;

$collection = collect($request->all());

How should I go about accessing the attributes in these arrays? I have tried pluck with no joy. I suspect I could do a loop over them but with no array_expression for the arrays do I need to use the index?



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

Class run every time from ServiceProvider

I have created a package which runs fine. In my service provider I do things like binding of interfaces and setting up config files. I have a class elsewhere in my project that I want to run every time (and not as middleware).

What is the 'clean' way to invoke a class in my ServiceProvider so it runs every time?



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

Laravel queue worker on dokku

I have problem with starting Laravel queue worker on latest Dokku.

I am using default heroku php buildpack. There is my procfile

web: vendor/bin/heroku-php-apache2 public/
worker: php artisan queue:work --daemon

Worker container is starting, but artisan command is not. No errors in log

If i manually enter worker container and start worker - it starts and works fine.

PS i tried to install shoreman plugin (http://ift.tt/294n4sx). Still same result.



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

laravel 5 subdomain not working in live

I have a site that can be access in stage.mysite.com now I want to have a subdomain for another page and it can be access at profile.stage.mysite.com.

in my server I have configured the hosting.

ServerAdmin webmaster@localhost
ServerName stage.mysite.com
ServerAlias *.stage.mysite.com
DocumentRoot /var/www/http://ift.tt/292wFy4

in my routes.php this is the code.

Route::group(['domain' => 'profile.stage.mysite.com'], function()
{
    Route::get('/', 'FrontendController@profile');
});

but when I tried to access http://ift.tt/295JhbN returns Server not found error. any ideas how to access my static page into subdomain?



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

Want to Filter an array according to value

i have a variable $a='san-serif' and an array Font_list[] now i want only the arrays whose category is 'san-serif' i tried a lot of codes nothing seems working here is my code:-

public function filterFont() {

    $key = $_POST['key'];
    $url = "http://ift.tt/28ONRKg''";
    $result = json_decode(file_get_contents( $url ));
    $font_list = "";
    foreach ( $result->items as $font )
    {
        $font_list[] = [
            'font_name' => $font->family,
            'category' => $font->category,
            'variants' => implode(', ', $font->variants),
            // subsets
            // version
            // files
        ];
    }
    $filter = filter($font_list);

    print_r(array_filter($font_list, $filter));

}

Please help me :-(



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

Laravel unable to load view

Just started learning laravel I tried to create a route for my view but when I load on the web browser it says Sorry, the page you are looking for could not be found. Can any one help me out in codeigniter it was so simple just create a controller and view and we can see on the web broswer I found laravel to be difficult then codigniter is that true?? can anyone define me how is the mvc structure for laravel5 as i found tutorials but they are of old laravel and files and structure are almost change so I got confused any suggestions please

routes.php

Route::get('main', 'Main@index');

Main.php

namespace App\Http\Controller;

use Illuminate\Http\Request;

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


class main extends Contoller {
    public function _construct() {
        $this->middleware('guest');
    }

    public function index() {
        return "Hello World from controller";
    }
}



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

location.href in double quote : Laravel 5.2

My code for select is below

<select id="ddlLanguages" class="form-control">
    @foreach($Languages as $Language) 
        <option onchange="location.href = {!! URL('Tr/' . '/' . $Language->LID) !!}" 
              value="{!! $Language->LanguageID !!}">{!! $Language->Language !!}</option>
    @endforeach
</select>

This produces below html

<select id="ddlLanguages" class="form-control">
    <option onchange="location.href = http://localhost/Learning/public/Translation/1" 
                    value="1">English</option>
    <option onchange="location.href = http://localhost/Learning/public/Translation/2" 
                    value="2">French</option>
</select>

Problem is this part "location.href = http://localhost/Learning/public/Translation/1" I am missing some formatting in the URL.

Can you guide me the correct path?



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

How to call an action to controller without route which resides in a Package

I have an Application running in Laravel 5.2. I have created a custom file upload package. File upload functionality is being handled inside the controller of the pacakge. Now from my original App I want to submit a form which also will have an upload file button. I am trying to post the form such that only the upload file portion can be handled using the package controller action. How I will do this?

Code

class aBc extends Controller{

  Public function store(){  
    // Here other input post data will be save except image upload 1st step

    // Main step where I stucked how I will use my custom package controller action to handle image upload. 
  }
}



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

Laravel 5.2 Model Relationships

im new to Laravel and have a relationship question.

The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1

class News extends Model
{
    protected $table = 'news';
    protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}

class Page extends Model
{
    protected $table = 'pages';
    protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];

    public function pagetype() {
        return $this->belongsTo('App\Models\PageType', 'pagetype_id');
    }
}


class PageType extends Model
{
    protected $table = 'pagetypes';

    public function page() {
      return  $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
    }
}

// now i need   All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news

// First Attempts are

Page::whereHas('pagetype', function ($q) {
            $q->where('component', 'news');
        })->where(['app_id' => 1])->get();

// result is all Pages which has the proper component news. 

This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.

My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.

I cant do any other model since there are many different pagetypes and components aswell.

Thanks so far.



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

How create own class helper in Laravel?

I need to create own class with methods, that I want to call from diverse controllers.

What it should be: Library, Provider or Helper in Laravel?



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

Lavavel 5.2.36 MethodNotAllowedHttpException in RouteCollection.php line 218:

Hi I am fairly new to Laravel and am trying to implement a post request for a simple form. I have been following a YouTube Tutorial series (laravel 5 | Section 3 | Part 4 Routing POST Requests) however at 5:46mins in, there is a notification that this method is only applicable to versions prior to Laravel 5.2.

I have tried to edit the VerifyCsrfToken.php method protected $except = ['api/']; but this makes no difference.

My routes.php code snippet:

Route::post('/form-handler', function(\Illuminate\Http\Request $request){
    if(isset($request['option']) && $request['firstName'])
    {
        if(strlen($request['firstName']) > 0){
            return view('forms.formResults', ['action' => $request['option'], 'name' => $request['firstName']]);
        }
        return redirect()->back();
    }
    return redirect()->back(); // Return user back to the page they came from
})->name('form-handler');

My welcome.blade.php code snippet:

<div class="form-group">
    <form action="" method="post" class="form-control">
        <label for="select-action">Select an option:</label>
        <select id="select-action" name="option">
            <option value="option1">Option1</option>
            <option value="option2">Option2</option>
            <option value="option3">Option3</option>
        </select>
        <input type="text" name="firstName">
        <button type="submit">Submit Details</button>
        <input type="hidden" value="" name="_token"> <!-- Laravel Security Measure, Note name must always be '_token'-->
    </form>
</div>

My full error message:

MethodNotAllowedHttpException in RouteCollection.php line 218:
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array('POST')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 821
at Router->findRoute(object(Request)) in Router.php line 691
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Debugbar.php line 49
at Debugbar->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Debugbar), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 53

Is this method of implementation completely invalid or does it just need a few tweeks?

Preferably I would like to know what the optimal post method is for retrieving form data, while still protecting your site from cross-site request forgeries.

Any fixes or alternate solutions will be much appreciated.

Please feel free to ask for any resources I may have left out.



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

What is the right database system for massive amounts of users?

I'm wondering what database system is the best for a website with a fast growing amount of users. The database would store al kinds of things about a user, including all of their actions.

  • It should be very secure and fast.
  • I would like to implement it in Laravel >5.2.

any suggestions?



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

Laravel 5 error can't create new models

For some reason I get this error. Using my new model logospinner.php. I't is located in a app/models, all the old models are working but not this new one.

FatalErrorException in Handler.php line 25:
Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in /home/vagrant/Code/smr/vendor/compiled.php on line 1817 and defined in /home/vagrant/Code/smr/app/Exceptions/Handler.php:25
Stack trace:
#0 /home/vagrant/Code/smr/vendor/compiled.php(1817): App\Exceptions\Handler->report(Object(Error))
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error))
#2 {main}
thrown

Here is the call in the controller.

use Logospinner;    
public function logospinner() {
       $data = Logospinner::get();
}

And here is the model

<?php namespace App;

class Logospinner extends Eloquent {
    protected $table = 'logospinner';
    protected $guarded = array("id");
    protected $hidden = array();

}



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

Catch exception from guzzle

I'm using laravel and I have setup the abstract class method to get response from the various APIs I'm calling. But if the API url is unreachable then it throws an exception. I know I'm missing something. Any help would be great for me.

$offers = [];
    try {
      $appUrl = parse_url($this->apiUrl);

      // Call Api using Guzzle
      $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

      if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
        $client->setDefaultOption('verify', false);

      $request = $client->get('?' . $appUrl['query']);
      $response = $request->send();
      if ($response->getStatusCode() == 200) {
        $offers = json_decode($response->getBody(), true);
      }
    } catch (ClientErrorResponseException $e) {
      Log::info("Client error :" . $e->getResponse()->getBody(true));
    } catch (ServerErrorResponseException $e) {
      Log::info("Server error" . $e->getResponse()->getBody(true));
    } catch (BadResponseException $e) {
      Log::info("BadResponse error" . $e->getResponse()->getBody(true));
    } catch (\Exception $e) {
      Log::info("Err" . $e->getMessage());
    }

    return $offers;



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

Extend Laravel 5's Response Facade to include further helpers?

I'm trying to allow an user to do something like response()->yaml(['their content']);, but I don't understand how I'd go on injecting my YAML method to the response() (ResponseFactory) facade.

Is there any guide that would explain on how to do this? Or maybe a quick description from someone? This is the first time I'm trying to build a package for Laravel and it will also be open source!

I checked out this question, but unfortunately I don't see its use case and I don't think it focuses on adding an additional method which would be called via response().

Help would be highly appreciated.



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

laravel 5 ajax error request

Hi I was wondering why my Laravel 5 Ajax request doesnt work

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

 $.ajax({
          url: "",
          method: 'post',
          data: {
            name: 'name',
            _token: $("input[name=_token]").val()
          },
          success: function(response) {
            if (response.success == true) {
              // remove error message
              alert('success');
            }
          },
          error: function(xhr) {
              alert('error');
            }
          });

on the Route File I put:

    Route::post('search/store', [
        'uses' => 'SearchController@store',
        'as' => 'groups.store'
    ]);

and on my controller I put:

public function store(Request $request)
    {
        return response()->json(['success' => true]);
    }

then I keep getting error 404 while I simply wants to display the json result from my controller much help appreciated thx

btw heres the full routes.php

    <?php
carbon()->setLocale('id');


Route::get('/', function () {
    return view('welcome');
});
    Route::post('search/SearchController','SearchController@postMapSearchResult');
    Route::get('/getRequest', function(){
            if(Request::ajax()){
                return 'getRequest has loaded';
            }
        });


Route::group(['middleware' => ['web']], function () {

    // Backend Area
        Route::controller('login','Backend\LoginController');

        Route::get('admin-cp' , function(){
            return redirect('login');
        });

        if(request()->segment(1) == webarq()->backendUrl)
        {
            include __DIR__.'/backendRoutes.php';
        }
    //

    // Frontend Area

        Route::get('account/confirmation/{token}', 'Auth\AuthController@activateUser')->name('user.activate');
        Route::controller('faq','FaqController');
        Route::controller('blog','BlogController');
        Route::controller('social','SocialController');
        Route::controller('account','AccountController');
        Route::controller('iklan','IklanController');
        Route::controller('search','SearchController');
        Route::controller('/','HomeController');


        Route::post('search/store', [
            'uses' => 'SearchController@store',
            'as' => 'groups.store'
        ]);


});



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

Delete files with wildcard in Laravel

Is there a way which allows you to delete files with a wildcard in Laravel 5.2.

For example:

File::delete('foo/bar.*');



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

Laravel 5.2 module routes not working

I am fresher in Laravel.I created a modules his project,follow this tutorial this link is below:

http://ift.tt/2920puz

Now I am facing a problem,how to hit the module controller into URL.

Actually I am not sure that module name should be mention or not into URL.



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

mardi 28 juin 2016

Issue with updating one to one model in Laravel 5.2

Tables are

User Table:

 id
 name
 email
 etc.

Profile Table:

 user_id
 role
 address
 city
 state
 etc.

On tinker i do:

 $user = $this->$user->with('Profile')->find(3);

Output is:

 App\User {#756
 id: 3,
 name: "Alejandra Kerluke Jr.",
 email: "balistreri.laurel@example.com",
 deleted_at: null,
 created_at: "2016-06-23 05:12:03",
 updated_at: "2016-06-29 11:05:45",
 Profile: App\Profile {#768
   user_id: 3,
   role: "",
   address: """
     50111 Wendy Row Apt. 732\n
     Kingburgh, OR 42164-7189
     """,
   city: "Manteland",
   state: "Vermont",
   country: "Belgium",
   phone: "1-226-766-4182 x5574",
   fax: "1-507-985-3523 x708",
   zip: 48446,
   status: 0,
   deleted_at: null,
   created_at: "2016-06-23 05:12:03",
   updated_at: "2016-06-23 05:12:03",
 },

}

Now i did:

>>> $user->name="YYYYYY"
>>> $user->email='abc@example.com'
>>> $user->profile->role = 'XXXXX'
>>> $user->push();

This throws the error:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `profiles` set `role` = inspector, `update

d_at= 2016-06-29 11:29:30 whereid` is null)'

I don't know what's wrong with this peace of code. I am new to Laravel and any kind of help will be appreciated.



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

Why i need to update $PATH every time i restart computer for laravel command?

I had followed the solution given here for "laravel command not found problem". BUT every time i restart my computer, i have to follow the same steps to work. It's annoying, any permanent solution to this?



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

Moving an image up in CSS

So, for the past hour I've being trying to move this image using the css property position. My problem is every time I move it using top or bottom it doesn't work correctly. Here's a screenshot of it before using said properties and after. Below you can find my html & css. Lastly, this position has to be absolute or the image completely disappears.

HTML

<section class="row posts">
    <div class="col-md-6 col-md-offset-3">
        <header><h3>What others have to say...</h3></header>
        @foreach($posts as $post)
            <article class="post" data-postid="">
                <p></p>
                <div class="info">
                    Posted by  on 
                </div>
                <div class="interaction">
                    <a href="#" class="like heart"></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
                    <a href="#" class="like">Dislike</a>
                    @if(Auth::user() == $post->user)
                        |
                        <a href="#" class="edit">Edit</a> |
                        <a href="">Delete</a>
                    @endif
                </div>
            </article>
        @endforeach
    </div>
</section>

CSS

.heart{
    background: url('http://localhost:8079/uncaughterror/public/src/img/web_heart_animation.png');
    background-position: left;
    background-repeat: no-repeat;
    height: 50px; width: 50px;
    cursor: pointer;
    position: absolute;
    left: 12px;
    bottom: 5px; //This or 'top' is what causes my entire problem
    background-size:1450px;
}

.heart:hover {
    background-position: right;
}



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

Laravel 5 - query builder AND

i have a mysql query and i want to pass them to laravel but i don't know how to use AND in laravel.

Mysql:

SELECT * FROM `items_sizes` left join `items` on `items_sizes`.`id_item` = `items`.`id` left join `budget__items` on `items_sizes`.`id` = `budget__items`.`id_itemSize` and `budget__items`.`id_budget` = 1 where `items`.`active` = 1 and `budget__items`.`id_budget` is null order by `items_sizes`.`updated_at` asc

Laravel:

$itemsSizes = ItemsSize::leftJoin('items', 'items_sizes.id_item', '=','items.id')
        ->leftJoin('budget__items','items_sizes.id', '=', 'budget__items.id_itemSize')
        ->*AND*('budget__items.id_budget', '=', $id)
        ->where('items.active', '=', 1)
        ->whereNull('budget__items.id_budget')
        ->orderBy('items_sizes.updated_at', 'asc')

Thank's



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

Custom validation message for json request payload

I'm using Laravel 5.2 and I'm submitting a json payload for my store and update controller methods. E.g.:

{
    "comments": "asdf",
    "materialId": "57719e5a907751.22478980",
    "orderData": {
        "advertiser_name": "123",
        "color": null,
        "email": "",
        "issue_date": "016-06-22",
        "name": "",
        "order_number": "123",
        "phone": "",
    },
    "uploadData": [
        {
            "clickthrough": "",
            "name": ""
        },
        {
            "clickthrough": null,
            "name": "Screen Shot 2016-06-24 at 3.46.59 PM.png"
        }
    ]
}

I have a Form Request Validation class defined. I've defined the rules I want to use and the custom error messages I'd like to use:

class MaterialUploadRequest extends Request
{

    public function rules()
    {
        return [
            'orderData.name' => 'required',
            'orderData.email' => 'required|email',
            'orderData.advertiser_name' => 'required',
            'orderData.issue_date' => 'required|date',
            'uploadData.*.name' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'orderData.name.require' => 'You must provide a name.',
            'orderData.email.require' => 'You must provide an email.',
            'orderData.email.email' => 'The email you provide must be a valid email.',
            'orderData.advertiser_name.require' => 'You must specify an advertiser name.',
            'orderData.issue_date.require' => 'You must specify an issue date.',
            'orderData.issue_date.date' => 'The issue date you specify must be a valid date.',
            'uploadData.*.name' => 'You must upload at least one file.',
        ];
    }
}

The validation rules work fine, but the custom messages are never applied. Using the payload below, the error I get for the orderData.name value being missing is still:

"The uploadData.0.name field is required."

Instead of the custom message:

"You must provide a name."

Seeing the 0 in the error message returned makes me think that the logic to look for the custom message is assuming that orderData.name is an array in dot notation instead of a javascript object. That said, I'm not sure exactly how to get this to work.

Any ideas?



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

Laravel 5.2 composer update

When I try to run a composer command like composer update it will throw an error.

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files


  [RuntimeException]                                                           
  Could not scan for classes inside "tests/TestCase.php" which does not appear to be a file nor a folder                                                  


update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--with-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]...

I try to require a package Image

http://ift.tt/1qIKPb0

I'm using Laravel 5.2 on OSX 10.11.5 with PHP 5.6.


composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "paynl/sdk": "^1.1",
        "barryvdh/laravel-dompdf": "0.6.*",
        "milon/barcode": "^5.2"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "symfony/css-selector": "2.8.*|3.0.*",
        "symfony/dom-crawler": "2.8.*|3.0.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "Veluwade\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}



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

Laravel 5 "The page isn't redirecting properly" What is the reason for this route?

I got "The page isn't redirecting properly" problem when I use Route::controller('/', 'DashboardController'); In routs.php file. If I using Route::get('/', 'DashboardController@getIndex'); I don't have this problem.In my AuthController.php I use protected $redirectTo = '/'; for redirect. My Question is why I got this error?

routs.php

enter image description here

Route::group(['middleware' => 'auth'], function () {
Route::group(['prefix' => 'products'], function () {
        Route::controller('category', 'Products\ProductsCategoryController');
        Route::controller('manufacturer', 'Products\ProductsManufacturerController');
        Route::controller('/', 'Products\ProductsController');
    });

    Route::group(['prefix' => 'customer'], function () {
        Route::controller('category', 'Customer\CustomerCategoryController');
        Route::controller('/', 'Customer\CustomerController');
    });

    Route::group(['prefix' => 'reports'], function () {
        Route::controller('/', 'Reports\ReportsController');
    });

    Route::controller('/', 'DashboardController');
});

Route::auth();

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



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

Laravel: Admins can see/edit/delete everything, but Authors can only their own

My app has two roles: admin & author (by the way, there are tables: roles, permissions, permission_role, role_user, there are Eloquent models Role.php, Permission.php... in model User.php there is a method called hasRole that checks whether the user has some role... and finally, in AuthServiceProvider.php there is:

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    foreach ($this->getPermissions() as $permission) {
        $gate->define($permission->name, function($user) use ($permission) {
            return $user->hasRole($permission->roles); 
        });
    }
}

protected function getPermissions()
{
    return Permission::with('roles')->get();
}

Anyway, I've created two roles: admin & author.

  • Admins should be able to see/edit/delete all articles. Also, admins should be able to create and edit/delete all registered users.
  • Author should be able to see/edit/delete only his own articles. Also, author should be able to edit only his own profile.

I'm not sure which is the best way to create this. Would it be a good idea to create the following permissions:

  • manage_users
  • edit_profile
  • manage_articles
  • edit_published_articles
  • delete_published_articles

and then admin role would have all of these permissions, while author would have only: edit_profile, edit_published_articles, delete_published_articles...

Then, in UsersController.php in each method I would check the permissions:

public function index()
{
    if (Auth::user()->can('edit_profile')) {
        if (Auth::user()->can('manage_users')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
    }
    return redirect('backend');
}

public function create(User $user)
{
    if (Auth::user()->can('manage_users')) {
        $roles = Role::lists('label', 'name');
        return view('backend.users.form', compact('user', 'roles'));
    }
    return redirect('backend');
}

public function store(Requests\StoreUserRequest $request)
{
    if (Auth::user()->can('manage_users')) {
        $user = new User($request->only('name', 'email', 'password'));
        $user->save();

        $roleName = $request->input('role');
        $user->assignRole($roleName);

        session()->flash('status', 'User has been created.');
        return redirect(route('backend.users.index'));
    }
    return redirect('backend');
}

public function edit($id)
{
    if (Auth::user()->can('edit_profile')) {

        if (Auth::user()->can('manage_users')) { 
            $user = User::findOrFail($id);
            $roles = Role::lists('label', 'name');
            foreach ($user->roles as $role) {
                $roleName = $role->name;
            }
            return view('backend.users.form', compact('user', 'roles', 'roleName'));
        }

        $user = User::findOrFail($id);
        if ($user->id == Auth::user()->id) {  
            $roles = Role::lists('label', 'name');
            foreach ($user->roles as $role) {
                $roleName = $role->name;
            }
            return view('backend.users.form', compact('user', 'roles', 'roleName'));
        }
    }
    return redirect('backend');
}
// ... and so on...

BUT, I'm quite sure that this is not the best way. Maybe I do not need to have the permissions at all - instead of checking permissions in controller methods it would be better to ask whether the user has a specific role (if (Auth::user()->hasRole('admin'))), for example instead of:

public function index()
{
    if (Auth::user()->can('edit_profile')) {
        if (Auth::user()->can('manage_users')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
    }
    return redirect('backend');
}

we would say:

public function index()
{
    if (Auth::user()->hasRole('admin')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
}

... or maybe this isn't the good way too? How would you do? Is it enough just to check in controller methods, or maybe there should be some Middleware involved?


Since this is a long post, to summarize:

I've created two roles: admin & author and:

  • Admins should be able to see/edit/delete all articles. Also, admins should be able to create and edit/delete all registered users.
  • Author should be able to see/edit/delete only his own articles. Also, author should be able to edit only his own profile.

How would you do this?



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

Laravel 5 Queue jobs are taking 400ms to run

I have implemented a Laravel 5.0 Queue (with a DB driver) in order to speed up the redirection speed on my website.

I wanted to speed up a process that takes about 400 ms.

However after implementing this Queue, it's still taking like 350-400ms.

Queue::push(function($job) use ($data)
{
    TestQueue::myFunc($data);

    $job->delete();
});

Am I doing anything wrong? Please let me know what else to provide in order for you to help me.



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

PHP - Illegal offset type, after is_array and is_object

I have this method:

public function setVariable($variable, $value = null)
{
    $variables = json_decode($this->variables);

    if(is_array($variable) || is_object($variable))
        foreach($variable as $key => $value)
            if(in_array($key, $this->variableNames))
                $variables[$key] = $value;
    else
        $variables[$variable] = $value;

    $this->variables = json_encode($variables);
    $this->save();
}

But, if I call the method like this:

setVariable(['test' => 'test', 'bla' => 'bla'])

It return this error:

ErrorException in User.php line 60:
Illegal offset type

Line 60 is this line:

$variables[$variable] = $value;

But, why it return the error? I check if $variable is array or object, But it continues return this error. Why?



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

Not able to save my data to database in laravel 5.2

I know this is very stupid question i'm asking about laravel. but seriously i'm little tired why my only three columns ( 'browser_version' , 'browser_major_version' , 'browser_plugins_installed' ) data are not storing in my database. and others are storing perfectly. may be i'm doing something wrong but what?? can any one help me with please. below is my database schema file and browser store method and database screenshot. please Note - issues is only that three column is not storing in database even i hardcoded that data in proper type.. still :(

Schema::create('browsers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('browser_name')->nullable();
            $table->float('browser_version')->nullable();
            $table->integer('browser_major_version')->nullable();
            $table->string('browser_engine')->nullable();
            $table->float('browser_engine_version')->nullable();
            $table->text('browser_plugins_installed')->nullable();
            $table->string('browser_language')->nullable();
            $table->timestamps();
        });

 $browser = $this->browser->create([
            'browser_name' => $browser_name,
            'browser_version' => 50.00,
            'browser_major_version' => 51
            'browser_engine' => $browser_engine,
            'browser_engine_version' => $browser_engine_version,
            'browser_plugins_installed' => $browser_plugin_installed,
            'browser_language' => $browser_language
        ]);

$ownerModel->browsers()->save($browser);

enter image description here

i tried a lot.. but i don't know what the exact issue is :(



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

laravel check if no returned records

I am trying to run a stored procedure, if it matches then it returns the information. If it doesn't match, then nothing is returned.

When nothing returns, I get this error: SQLSTATE[IMSSP]: The active result for the query contains no fields.

How can I catch this error and throw a 403 instead of this error? I tried adding SET NOCOUNT ON ;, it didn't help. or count($response), I keep getting this error.

What else can I put in place?



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

How to create stored procedure laravel

Hi I've been looking around for some kind of how to guide for stored procedures in Laravel but can't find any so far. My issue is basically I have a huge list of parameters that I need to send to the stored procedure called InsertNewApplicant but I'm not sure how to build the query.

This is all I have so far, I'm not sure where I chose which database to send it to or how to make the connection to that database.

Any help would be greatly appreciated

 $result = DB::select('call InsertNewApplicant(?????????????????????????)',
                    array($firstName, $middleName, $addressLine_1, $addressLine_2, $postCode, $landline, $mobile, $email,
                    $DOB, $maritalStatus, $industry, $occupation, $jobTitle, $selfEmployed, $selfAssessment, $workHome,
                    $ownTransport, $companyVehicle, $paySubs, $otherIncome, $printForms, $marketingUs, $marketingOther,
                    $agreedTNCs, $TNCVersion, $CampaignSource));



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

Laravel 5.2 user management through RESTful API (looking for an alternative to Route::auth())

I would think this question has been asked 1,000 times, but I actually haven't been able to find it anywhere (at least not for Laravel 5.2). I'm trying to implement user admin functionality through a RESTful API (I'm not talking about OAuth2, I already got that up and running). Basically, I need all the stuff Route::auth() does through a web interface, but I want to do it without the web interface and without the redirects that Route::auth() returns.

It seems like I can send POST requests to the underlying routes of Route::auth() (register, login, logout, password...) and it properly validates the POST and acts, but there's no useful data returned and it always redirects to / as the response. For example, if I register a new user, it creates the account correctly and redirects to /, but there's no "success" message. If I try to register a new user with an email address that's already in the user table, it does the exact same thing (redirects to / with no other response) and I don't get any sort of response to tell my app that the user already exists.

Is there something I'm missing or do I need to re-write all of these routes and auth methods for proper API functionality?



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

laravel5.2 + local DB running in docker container

I have a question about using local db with Laravel. I'm running postgresql in docker container. When I ran migrations via artisan, all tables was created correctly (I can see them in pgAdmin). The problem is next: When I try to fetch data from DB Laravel says

SQLSTATE[08006] [7] FATAL: password authentication failed for user "pgsql_user_name"

in .env file i have next config:

DB_CONNECTION=pgsql DB_HOST=127.0.0.1
DB_PORT=5432 
DB_DATABASE=test_db 
DB_USERNAME=pgsql_user_name 
DB_PASSWORD=pgsql_pass



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

larval TokenMismatchException in VerifyCsrfToken.php

I am using larval 5

this is my html

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <h3>This is a test page </h3>
    <form method="POST" action="./apartment/sayLove2">
        <input name="id" value="1" type="text"/>
        <input name="team" value="roma" type="text"/>
        <input name="bestPlayerInTheWorld" value="TOTTI" type="text"/>
        <input  value="Send" type="submit" />
    </form>
</body>
</html>

this is my route

Route::post("/apartment/sayLove2", 'ApartmentController@sayLove2');

This is my controller

<?php
namespace App\Http\Controllers;



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


class ApartmentController extends Controller
{
    public function sayLove2(Request $request)
    {
        $id = $request->input('id');
        echo $id;
        eixt;
        $team = $request->input('team');
        $bestPlayerInTheWorld = $request->input('bsetPlayerInTheWorld');
         return view('sayLove', ['id' => $id, $team => $team]);
    }


}
?>

I am getting this error when click submit form

TokenMismatchException in VerifyCsrfToken.php line 67:
in VerifyCsrfToken.php line 67
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54
at require_once('/Applications/XAMPP/xamppfiles/htdocs/ULTest/public/index.php') in server.php line 21



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

Object not being passed to controller

I am struggling with something I am pretty sure I am doing incorrectly. I have a Departments model which has the following route

Route::resource('departments', 'DepartmentsController', ['except' => ['show', 'edit', 'create', 'delete', 'update', 'destroy']]);

It uses active directory to update the database, no user input is involved. I have now come to the point where a department can have many objectives. So I have created a DepartmentObjectives model and set the relationships. I then done the following in my routes file

Route::model('departmentObjectives', 'DepartmentObjectives');
Route::bind('departmentObjectives', function($value, $route) {
    return App\DepartmentObjectives::whereId($value)->first();
});
Route::resource('departmentObjectives', 'DepartmentObjectivesController', ['except' => ['show', 'store', 'delete', 'destroy']]);

Now on the index file for departments, I have the following

@foreach($departments as $department)
    <tr>
        <td>  </td>
        <td>  </td>
        <td>{!! link_to_route('departmentObjectives.create', 'Get Objectives', array($department->id), array('class' => 'btn btn-info')) !!}</td>
    </tr>
@endforeach

But within the DepartmentObjectives Controller, if I do the following it outputs an empty Department object

public function create(Department $department)
{
    dd($department);
    return view('departments.objectives', compact('department'));
}

What is the best way to link the department objective to the department?

Thanks



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

Laravel 5 localization lang file with special characters makes trans function return b appended to string

I have lang file for French, and strings with special characters are making problem. For example I have array 'success' with message:

'formResult'    => 'Le formulaire a été transmis avec succès.',

In my controller, when I type

dd(trans('pages/message.success.formResult'));

I get this printed on the screen:

b"Le formulaire a été transmis avec succès."

notice the 'b' letter appended at the beginning.

This is causing problems when trying to send message to blade, nothing is sent:

return redirect('/contact')->with('success', trans('pages/message.success.formResult'));

please note that this works:

return redirect('/recruite')->with('success', 'Le formulaire a été transmis avec succès.');

and problem is in return from trans function.

If string has no special characters, trans func works ok.

Also if I use "Lang::get" instead of trans function, problem is the same.



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

How to correctly setup the eloquent relationships for pivot tables in Laravel 5.2

I have three tables in a db which are as follows (not all of the columns but minimised for clarity):

admins (id, community_id, email, password, level)
community (community_id, community_name)
community_results (community_result_id, community_session_id)
community_sessions (community_session_id, community_id)

I have setup the associated models and within my admin controller I have the following code that simply grabs all the results in the database into a laravel collection (and this works fine). The admin table contains two types of admin user - one is the 'superuser' that has access to every single row in the db, and the other type is a 'community admin' and will only have access to their community results (defined by the level column in the admins table).

When logged into the admin as a 'community admin' I want to only get results for their community (admins.community_id is the foreign key in this instance that relates this admin to a community).

e.g John Doe is a 'community admin' for the 'ACME Community' and belongs to the community_id 5, when logged in he will only get 'community results' for all of the 'community sessions' that relate to that particular community (community_id is the foreign key in the community_sessions table).

So i'd need to find a way to create a modified version of the results() relation within the CommunitySession.php model but rather than query EVERY row only retrieve those of one or more community_session_id's - alternatively is there way using the Community.php model to create a relation to basically pull in results using the relation like the following...

$community = Community::find(5);
$community->results; // pull results for this community using a relation

Can anyone suggest the best way to do this? Thanks in advance

class AdminResultController extends Controller
{
   public function index()
   {
      // if logged in as the 'superuser' admin get ALL results
      if (Auth::guard('admin')->user()->level == 1) 
      {
         $results = CommunityResult::all();
      } else {
        // logged in as 'standard' admin get only their community results
        $results = new CommunityResult;
        // how do I get collection of results for this community only
      }
   }
}

// CommunityResult.php (model)

class CommunityResult extends Model
{
  public $primaryKey = 'community_result_id';

  public function session()
  {
    return $this->hasOne('App\CommunitySession', 'community_session_id', 'community_session_id');
  }
}

// CommunitySession.php (model)

class CommunitySession extends Model
{
  public $primaryKey = 'community_session_id';

  public function community()
  {
    return $this->belongsTo('App\Community', 'community_id');
  }

  public function results()
  {
    return $this->hasMany('App\CommunityResult', 'community_session_id');
  }  
}

// Community.php (model)

class Community extends Model
{
  public $table = 'community';
  public $primaryKey = 'community_id';

  public function sessions()
  {
    return $this->hasMany('App\CommunitySession', 'community_id');
  }
}



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