tim_jespers

Developer at DifferentLab

Experience

10,050

11 Best Reply Awards

  • Member Since 1 Year Ago
  • 64 Lessons Completed
  • 1 Favorite

19th May, 2017

tim_jespers left a reply on Laravel 5.4 Multiple Form Posts On 2nd Form Validation Passes Back To Get Instead Of Post • 2 months ago

@paulsiafiji in my honest opinion this is a little messy using different endpoints for these type of things:

Route::get('testform1', [email protected]');
Route::post('testform1',[email protected]');

Would be a more sane way to define your routes if you ask me.

Regarding your error: it's fairly logical that this errors out because in a nut shell this is what's happening:

  1. visit /testform1, which gives you the view in the testform1 snippet

  2. in the testform1 snippet you state the post should go to action="{{url('testform2')}}" so on form submit a POST tot testform2 will end up in [email protected], this returns a view called 'testform2' (which is missing as code snippet? i assume you meant testform 3 there).

  3. the view testform3 makes a post to /testform3 which ends up in [email protected]' IF validation fails, you're being redirected back to where you came from (/testform2) with all input from the current request

And now for the grand finale :) $formVariable isn't an input present on this request (i suppose you grab it from the input of form 1 to render form 2?) therefore it won't be present anymore and therefore you get a failure ;)

My suggestion:

//web.php
Route::get('testform1', [email protected]');
Route::post('testform1',[email protected]');

Route::get('form2',[email protected]');
Route::post('form2',[email protected]');

Route::get('form3',[email protected]');
Route::post('form3',[email protected]');

//controller

//or show 2 or show 3
public function show1(){
    return view('form1');
}

public function store1(){
    //store formvariables you might need in future in session like so:
    session()->put('formVariable','i-need-this-later');

    //REDIRECT TO NEXT FORM!
    return redirect()->url('form2');
}

public function store2(){
    //grab formVariable from session, it's always there!:
    $formVariable = session()->get('formVariable');
    
    return view('form2')->with(compact('formVariable'));
}

public function store3(){
    //you get the idea i suppose?
}

This way you make sure the variable is always there! if you're done with it, for example after passing validation on form 3 you can remove it from the session with: session()->forget('formVariable');

i hope this helps :)

tim_jespers left a reply on View Composer: How Do I Prevent The Rendering? • 2 months ago

You could throw an exception and handle any actions accordingly? Otherwise check if $view->foo isset before initiating the rendering for instance in the controller?

tim_jespers left a reply on Laravel Server And Mac OS Server Refusing Connection • 2 months ago

A quick note, valet isn't using Apache but Nginx under the hood so that shouldn't be the problem, have you tried a simple "valet uninstall" to get your other sites working again?

I can also imagine that you configured valet to respond to the .app TLD which is also handled by your other servers, in that case i would recommend to either:

  • configure mac server(?) to serve laravel
  • configure valet to serve all your sites

working with multiple servers like apache, nginx etc. on 1 machine is in my opinion overkill and recipe for trouble!

tim_jespers left a reply on What Is The Force Delete Route In Laravel 5.4 • 2 months ago

@masum good to hear this has solved your problem :) Would you mind marking the answer as "best" answer so others that have the same problem can find this solution? Thanks in advance!

tim_jespers left a reply on Session Flash Data • 2 months ago

You i totally forgot you can also redirect with flash in that way, thanks for keeping me sharp!

tim_jespers left a reply on Laravel 5.4 Won't Validate JSON From RAW Data • 2 months ago

First thing i noticed: why intersect? $requestData = $request->get('only_this_key'); or $requestData = $request->input('only_this_key'); are just as easy and more lightweight i suppose.

Silly question perhaps but if you dd($requestData) did you make sure it actually still is Json and not a PHP array which has been magically converted by Laravel for you?

tim_jespers left a reply on Add A New Migration But Without Lossing Data Of The Old Tables • 2 months ago

@cronix 2 minds.. same thoughts :P

tim_jespers left a reply on How To Filter/select On Intermediate (pivot) Table Columns In Laravel (5.4)? • 2 months ago

Ahh my bad, i misunderstood: offcourse you'll need a pivot table in the database, otherwise the info can't be stored if you name it to the convention below laravel will do the magic of finding and filling it:

Tablename: film_person (model names, alphabetical order, singular) columns: film_id, person_id, type

for more info see the general many-to-many docs

If this answers your questions please be so kind to mark the code example as "best answer" so others can benefit from it too in similar situations :)

tim_jespers left a reply on What Is The Force Delete Route In Laravel 5.4 • 2 months ago

This occurs when you try to delete a User-id which doesnt exist, route model binding throws a 404 on that by default docs

tim_jespers left a reply on Session Flash Data • 2 months ago

You're using session()->flash(); Which puts data in the session for the current request only, after that you're redirecting (new request) so the flash is gone. If you want to actually store things in the session use:

session(["key" => "value"); or $request->session()->put('key', 'value');

for more on sessions see the docs

tim_jespers left a reply on How To Filter/select On Intermediate (pivot) Table Columns In Laravel (5.4)? • 2 months ago

@ajck yes the last 3 functions return all films attached to the person model $person.

i updated my first answer because i forgot that the many-to-many can use "save" instead of "attach" with the whole associated model instead of the id which is a little cleaner i think

About the pivot: the where pivot method filters the pivot table records based on the 'type' column (i assumed it's called that way based on your original post).

The actual saving of these columns happens in the helper methods on the Film class, because you're attaching a person to a film not the other way around.

The docs about many to many relationships and pivot tables might be a good read to wrap your head around it a little more:

Updating many to many (see Updating A Record On A Pivot Table)

tim_jespers left a reply on What Is The Force Delete Route In Laravel 5.4 • 2 months ago

The error states that the request method you're using is not allowed for that route, perhaps you're doing a DELETE or GET request? The route should be

Route::delete('users/{user}/delete', [email protected]');

or

Route::get('users/{user}/delete', [email protected]');

tim_jespers left a reply on Subscriber Form • 2 months ago

A quick tip to start of with: please use markdown for code snippets to keep things readible (and use enters):

wrap code lines in a '`' and code blocks in '```' this transforms:

Class Subscribers Extends Eloquent{ protected $table = 'subscribers'; protected $fillable = array('email'); }

into:

Class Subscribers Extends Eloquent{ 
    protected $table = 'subscribers'; 
    protected $fillable = array('email'); 
}

Also you want to create a resource route Route::resource('subscriber', 'SubscribersController');

for more info see: Resource routes / controllers

tim_jespers left a reply on Add A New Migration But Without Lossing Data Of The Old Tables • 2 months ago

Can you share a code snippet of the migration that is causing the problem? My best guess at this point is that your up() function has a Schema::create('existing-table') instead of a Schema::table('existing-table'). If that is the case you simply defines the second migration as a "create table" migration instead of an "alter table" migration which can be resolved easily. for more info read the docs about columns

tim_jespers left a reply on How To Filter/select On Intermediate (pivot) Table Columns In Laravel (5.4)? • 2 months ago

If you are still in the design phase for this project i would suggest some major changes to more or less mimic structure below: note that i also added some readable helper methods on the models which of course are entirely optional

class Film extends Model{
    //return all cast persons for this film
    public function cast(){
        return $this->belongsToMany(App\Person::class)->wherePivot('type', 'cast');
    }
    
    //return all directors for this film
    public function directors(){
        return $this->belongsToMany(App\Film::class)->wherePivot('type','director');
    }

    //return all persons attached to this film
    public function persons(){
        return $this->belongsToMany(App\Film::class);
    }

    //accepts a user model for convenience
    public function addDirector(App\User $user){
        $this->persons()->attach($user->id, ['type' => 'director']);
    }

    //accepts user model for convenience
    public function addCast(App\User $user){
        $this->persons()->attach($user->id, ['type' => 'cast']);
    }
}

class Person extends Model{

    //normal relationship you can use in query builder
    public function films($type = null){
        return $this->belongsToMany(App\Film::class);
    }

    //helper function for convenience
    public function getFilms($type){
        switch($type){
            case 'director': 
                return $this->films()->wherePivot('type','director');
            case 'cast': //returns films with this person in cast
                return $this->films()->wherePivot('type', 'cast');
            default:
                return $this->films;
        }
    }
}

//now you can do things like:

$person = App\Person::find(1);
$anotherPerson = App\Person::find(2);

//when creating a film:
$film = Film::create();

//attach a director can be done like:
$film->addDirector($person);

//adding a cast member is as simple as:
$film->addCast($anotherPerson);

//get films where person is director
$person->getFilms('director');

//get films where person is part of cast
$person->getFilms('cast');

//get all films
$person->getFilms();

//which is the same as:
$person->films;

//and also as:
$person->films()->get();

tim_jespers left a reply on Function Cannot Call Another Function In Same Model • 2 months ago

@Michel414 this ain't a single file. You already got the User.php file (which comes with laravel) all i did was outline the key parts of each model and compress it into a single code block for the sake of simplicity here. You basically want to create a second model called Administration Laravel model documentation here

The lines of code that i wrote below the Administration model are just example usages of the classes above and can be put anywhere to fit your needs. I might suggest that you watch this free course on Laracasts to get you started.

I think that should do :)

tim_jespers left a reply on WhereHas On Multiple Relationships - Laravel 5.4 • 2 months ago

I don't have a stack overflow account so let me put my answer in here.. From reading the story it just looks like you basically want to get all tours (with all the relationships) with bottom line condition: only the tours that the logged in user is part of?

If so it's actually quite simple, assuming you have a relationship called "tours" on your user model like so:

class User extends Model{
    public function tours(){
        return $this->hasMany(App\Tour::class);
    }
}

//i removed the with 'user' part as it is the logged in user, no need to fetch that?
$tours = user()->tours()->where('slug', $slug)->with('image', 'itenary', 'inclusion', 'exclusion')->get();

14th May, 2017

tim_jespers left a reply on Unit Testing My App's Local REST API Calls, But Using The Testing Sqlite DB ... • 2 months ago

Executing http requests via your testcase will run them not over http but from within the test environment :) This is of course whenever you're using the $this object to create the http calls.

Whenever you start using things like guzzle to do the request inside your test this obviously is not going to work :)

The way this works is that $this->getJson (which under the hood becomes a simple $this->get / post etc.) simply creates an HttpKernel and injects the build request into it as if it was an incoming HTTP request :) to find out more simply read the source code from the Concerns\MakesHttpRequests trait. This is where the magic happens :) the behaviour i mentioned happens in the call() method of the trait. This trait is put on the TestCase class by default within Laravel.

tim_jespers left a reply on API Working In Local, But 405 In Production • 2 months ago

So i did some more digging and i think i've found the problem! With valet everything is working, if you're using the latest version of Valet this uses Nginx under the hood.

On your production server you seem te be running Apache, now here comes the problem:

In order to understand PUT/PATCH/DELETE requests Apache needs the 'webdav' module enabled. My guess is that this isn't the case, apache is simply transforming our PATCH/DELETE requests to POST requests for the same endpoint.

POST /replies/{reply} isn't a valid route and therefore we are getting the MethodNotAllowedException (which reveals us that we should use either PATCH or DELETE for this route).

TLDR: enable Apache's webdav module and we should be good to go!

Webdav docs

tim_jespers left a reply on How To Write A Search Box In Navigation • 2 months ago

Hi again, still working on the navigation i see ;) For a searchbox you can go like a thousand ways. There isn't really a generic way to do this. maybe this post can point you in the right direction Search option in Laravel 5

tim_jespers left a reply on How To Find Out The Database Map File In Laravel Project? • 2 months ago

The question that raises here is: how can you mess up a migration file? And what did you do after removing it from the classmap? Delete the migration? Change filename? I'm gonna need a little more context to give a straight answer here ;)

Basically what composer dump-autoload does is regenerate the class map. So if on of your migration files is removed/moved/renamed/deleted it will also update/remove the entry for that migration file.

tim_jespers left a reply on How To Seed Two Different Profiles Tables Using The User.id? • 2 months ago

No a helper isn't necessary your factories can handle this m8! I'm not totally sure how your flag works but let's assume it's the string you mentioned in the opening post (the column called 'role')

//Tenant factory
$factory->define(App\Models\Tenants\Tenant::class, function (Faker\Generator $faker) {

    return [
        'id' => function() { 
                return factory(App\Models\User::class)->create(['role' => 'Tenant'])->id;
        },
    //other stuff here
    ];

//landlord factory
$factory->define(App\Models\Landlords\Landlord::class, function (Faker\Generator $faker) {

    return [
        'id' => function() { 
                return factory(App\Models\User::class)->create(['role' => 'Landlord'])->id;
        },
    //other stuff here
    ];
});

it's fairly simple m8! :)

tim_jespers left a reply on API Working In Local, But 405 In Production • 2 months ago

To be honest it's fairly simple once i understood what was wrong. Open up your chrome debug console and select the tab "network". Do a delete / edit and the request will pop-up there to be inspected and actually it's as clear as day!

Clicking delete on a thread reply makes a DELETE request to fastfrag.co.uk/replies/{id} but gets a 405 in return (method not allowed) same goes for the edit.

You can actually see the laravel response whenever you click that request.

The problem lies in your routes file, or your javascript is connected to the wrong endpoint in your API.

Double check if your routes for /replies/{id} are setup correctly for PATCH & DELETE methods. You should have enough info to work with now :)

13th May, 2017

tim_jespers left a reply on MAMP To VALET (finally) ... Wrong PHP • 2 months ago

You could do a quick phpinfo (); to reveal which .ini file is being used?

Also i dont think valet comes with an own php.ini file as it doesn't actually install php like mamp does ;)

tim_jespers left a reply on How To Seed Two Different Profiles Tables Using The User.id? • 2 months ago

Isnt't it way easier to define factories fro landlords and tenants which create a user inside these factories? From the info you have provided a user should not exist without a landlord/tenant record right?

a quick example would be:

$factory->define(App\Models\Tenants\Tenant::class, function (Faker\Generator $faker) {

    return [
        'id'                 => factory(App\Models\User::class)->create()->id,
    //other stuff here
    ];
});

Now all you have to do is whip up your landlord / tenant factory not the user one :)

tim_jespers left a reply on Create Navigation Menu With Subcategories • 2 months ago

You could actually create a Category model for this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model{
    
    public function subcategories(){
        return $this->hasMany('\App\Category\', 'parent_id');
    }

    public function parent(){
        return $this->belongsTo('\App\Category', 'parent_id');
    }
}

A controller for this is really not necessary, you can actually just make sure that the navbar view always receive a variable called $categories through a simple view composer within your AppServiceProviders register method.

//inside AppServiceProvider register method:

view()->composer('shared.navbar', function($view){
    //get all parent categories with their subcategories
    $categories = \App\Categorie::where('parent_id', 0)->with('subcategories')->get();
    return $view->with(compact('categories'));
});

in your navbar view you can now simply loop through them and do your magic:

@foreach ($categories as $category)
    {* PARENT CATEGORY DISPLAY LOGIC *}
    @foreach ($category->subCategories as $subCategory)
        {* SUBCATEGORY DISPLAY LOGIC *}
    @endforeach
@endforeach 

tim_jespers left a reply on API Working In Local, But 405 In Production • 2 months ago

First of all! ALWAYS ALWAYS ALWAYS remove laravel debugbar from a production environment.. it took me 2 seconds to timetravel to your last login action and copy the credentials to log in.. (not to hack but to save myself some time registering a user :P)

As for your problem, i can't really find out whats wrong? Whats is the exact step that gives you this 405? I can update, delete and create replies? I also created and deleted a thread successfully.. Can you give us some more details about your error and how we can recreate it?

tim_jespers left a reply on TeamSpeak3 Query Framework • 2 months ago

The error says it all.. You are catching a TeamSpeak3_Exception $e, however a Ts3Exception is thrown. You're simply catching the wrong thing so your catch block isn't executed :)

tim_jespers left a reply on SoftDeletes Stopped Working • 2 months ago

From the info you're giving us, we can't verify whether or not its the full soft deleting behaviour that's not working or just the select part.

If you delete a model and check your DB is the deleted_at column set correctly?

If so, it is most likely that you are disabling the global query scopes somewhere in your code. This will affect the SoftDelete behaviour because the way the trait works is by adding a global query scope which appends your query with the WHERE deleted_at IS NULL part.

tim_jespers left a reply on Relationship Seeder Not Saving • 2 months ago

Could the problem be a misformed array? you state:

$players = [ 
    'Arnold Palmer'=>
        [
            'Brockton Country Club', 
            'Blue Hills Country Club'
        ], 
    'Tiger Woods' => 
        [
            //this doesn't look good to me!
            'Sassamon Trace Country Club, Brockton Country Club'
        ], 
    'Fred Couples' => 
        [
            //this doesn't look good to me!
            'Blue Hills Country Club, Sassamon Trace Country Club'
        ]
     ];

In this case Tiger and Fred are not gonna get any valid course responses when doing: $course = Course::where('course_name', 'LIKE', $courseName)->first();

this is of course only if this is the exact array you are using and it's not a copy paste error into your post :)

tim_jespers left a reply on Relationship Seeder Not Saving • 2 months ago

The problem seems to be in your player seeder itself.

Your player array isn't multidimensional: $players = [ ['Arnold Palmer'], ['Tiger Woods'], ['Fred Couples'], ['Jason Day'] ]

so when you do a foreach $players as $player $player[0] (to which you refer to for setting the player name will be null hence it isn't an array but a string. Therefor the full_name column will not be filled correctly.

So when you're trying to get the first player with a full name like $full_name there will be no result and therefore the relationship errors!

foreach($players as $player) {

            $timestampForThisPlayer = $timestamp->addDay()->toDateTimeString();
            Player::insert([
                'created_at' => $timestampForThisPlayer,
                'updated_at' => $timestampForThisPlayer,
                'full_name' =>  $player,
            ]);
        }

should do the trick!

tim_jespers left a reply on Where Are You All From? • 2 months ago

Zoetermeer, The netherlands

tim_jespers left a reply on Cannot Use Object Of Type StdClass As Array • 2 months ago

In Laravel 5.4.21 DB:: query's will return stdObject class objects, not Eloquent models. So in blade $role['name'] should be $role->name as you cannot treat an stdObject as an array (the error is pretty explanatory in this case ;) ) the reason why the first one IS in fact working is only due to the fact that Eloquent models implement ArrayAccess by default which allows you to treat them as if they were a plain array instead of an class object. If they didn't you would get the exact same error on the first query method.

So either: go with the model approach and use array notation in views or go for stdObjects and acces their properties as stated above :).

tim_jespers left a reply on Function Cannot Call Another Function In Same Model • 2 months ago

I suppose we could clean this up in a more understandable way:

First lets define 2 models and a relationship between them, for as far as i can see you got 3 tables: users, administrations and an intermediate table for the relationship between users and administrations. With eloquent we can fairly easy realize this:

class User extends Model{
    public function administrations(){
        return $this->belongsToMany('\App\Administration', 
'core_administrations_has_users', 'userId');
    }

    public function canAccesAdministration($id){
        return in_array($this->administrations->pluck('administrationId')->toArray());
    }

}

class Administration extends Model{
    public function users(){
        return $this->belongsToMany('\App\User', 
 'core_administrations_has_users', 'administrationId';
    }
    
    public static function loginById($administrationId){
        //perform administration login logic
    }

    public static function logout(){
        //perform administration logout logic
    }
}

//retrieve the user after login
$user = Auth::user();

//get administrations attached to user
$administrations = $user->administrations;

//login an administration
if($user->canAccesAdministration($administrationId){
    \App\Administration::loginById($administrationId);
    //return succes outcome
    return true;
}

//if we reach this point user cant access administration
return false;

//for logging out if only unsetting data this can be done static:
\App\Administration::logout();

more info on relationships in eloquent: https://laravel.com/docs/5.4/eloquent-relationships

tim_jespers left a reply on Function Cannot Call Another Function In Same Model • 2 months ago

I suppose we could clean this up in a more understandable way:

First lets define 2 models and a relationship between them, for as far as i can see you got 3 tables: users, administrations and an intermediate table for the relationship between users and administrations. With eloquent we can fairly easy realize this:

class User extends Model{
    public function administrations(){
        return $this->belongsToMany('\App\Administration', 
'core_administrations_has_users', 'userId');
}

class Administration extends Model{
    public function users(){
        return $this->belongsToMany('\App\User', 
 'core_administrations_has_users', 'administrationId';
    }
    
    public function login(){
        //perform administration login logic
    }

    public static function logout(){
        //perform administration logout logic
    }
}

//retrieve the user after login
$user = Auth::user();

//get administrations attached to user
$administrations = $user->administrations;

//login an administration
$administration = $administrations->where('administrationId', $administrationId)->first();

if(!$administration){
    //user is not part of the given administration
    //return redirect or whatever
}

$administration->login();

//for logging out if only unsetting data this can be done static:
\App\Administration::logout();

more info on relationships in eloquent: https://laravel.com/docs/5.4/eloquent-relationships

tim_jespers left a reply on Function Cannot Call Another Function In Same Model • 2 months ago

I suppose we could clean this up in a more understandable way:

First lets define 2 models and a relationship between them, for as far as i can see you got 3 tables: users, administrations and an intermediate table for the relationship between users and administrations. With eloquent we can fairly easy realize this:

class User extends Model{
    public function administrations(){
        return $this->hasMany('\App\Administration', 
'core_administrations_has_users', 'userId');
}

class Administration extends Model{
    public function users(){
        return $this->hasMany('\App\User', 'core_administrations_has_users', 'administrationId';
    }
    
    public function login(){
        //perform administration login
    }

    public function logout(){
        //perform administration logout
    }
}

//retrieve the user after login
$user = Auth::user();

//get administrations attached to user
$administrations = $user->administrations;

//login each administration
$administrations->each(function(\App\Administration $administration){
    $administration->login();
});

//logout each administration
$administrations->each(function(\App\Administration $administration){
    $administration->logout();
});

tim_jespers left a reply on Getting Error On Registration In Laravel 5.4 • 2 months ago

It looks like you're encountering a validation error which isn't handled properly. If validation fails a validation error is thrown by default from the register method

//inside RegistersUsers.php
public function register(Request $request)
    {
    //on validate failure a ValidationException will be thrown to stop the flow
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

    //in your case $user is a RedirectResponse not a user object!
        $this->guard()->login($user);
...

Did you override the validator method on RegisterController.php in any way which causes the validation to malfunction?

By default the validator function should return a \Illuminate\Contracts\Validation\Validator object. If this is not the case that might be the cause of your error.

tim_jespers left a reply on Swapping Mail Service Provider On Runtime Does Not Seem To Work • 2 months ago

Your intended solution is not going to work as is you have to actually update laravels mailer singleton which is bound in the ioc container to get it to work with the appropriate driver with:

//inside your SailthruServiceProvider register method
app()->singleton('mailer', $mailer);

where $mailer is the new instance of the mailer you want to use for that email. otherwise it won't work, see: https://laracasts.com/discuss/channels/general-discussion/maildriver-change-on-runtime-is-being-ignored for more info

tim_jespers left a reply on Laravel And Valet Bizarre Loading Issue • 2 months ago

So i actually reproduced the situation, however both blog.dev & test.dev work out just fine for me.

this is the exact flow i followed:

//create new code dir to test this out without interference
mkdir code

//cd to code dir
cd code

//register the code dir as a valet park
valet park

//double check valet binding to see "code" park entry is there
valet paths

//create blog project inside code dir
laravel new blog

//create test project inside code dir
laravel new test

Running valet v2.0.4 & Osx 10.11.6

  • Did you make sure you did not accidentally create the test project inside the blog project?
  • Does the command "valet paths" give you your code directory path as entry?
  • What happens when you try binding the test project through a valet Link instead of via park?

tim_jespers left a reply on How To Find Out The Database Map File In Laravel Project? • 2 months ago

Simply regenerate the autload file with

composer dump-autoload

from your project root should do the trick i guess? Or are you looking for the actual migration file? In that case its stored in database/migrations by default when creating it through the artisan command!

tim_jespers left a reply on Multiple Relationships Count • 2 months ago

Hi! For the first problem you're facing you can use a hasManyThrough on the Country model:

//country.php
public function students(){
    return $this->hasManyThrough('App\Agency','App\Student');
}

//count students by country:
$studentsCount = $country->students()->count();

//get students for country
$students = $country->students;

tim_jespers left a reply on Setup A Different Table In A Different Database For One Model Only • 2 months ago

This next question makes me wonder what the best approach is? Is this app the only app using the second table? In that case i would perhaps write a migration and simply change te column names to what your code is expecting

Schema::table('table_name', function (Blueprint $table) {
    $table->renameColumn('old_name', 'new_name');
});

If that is no option you can do either one of two things below:

  1. Update your code to use functions
    $someProperty = $object->getFoo();

//in model A class:
public function getFoo(){
    return $this->foo;
}

//in model B
public function getFoo(){
    return $this->bar;
}
  1. use accessors and mutators (more complicated and untransparent)
    $someProperty = $object->foo;

//in your model class:
//for data retrieval:
public function getFooAttribute($value){
    return $this->attributes['bar'];
}

//when saving the model:
public function setFooAttribute($value){
    //set the value of property 'foo' to property 'bar'
    $this->attributes['bar'] = $value;
    unset($this->attributes['foo'];
}

I would prefer writing a migration if you can, otherwise use the first method and only drop to method 2 as a real last resort!

tim_jespers left a reply on Passport Personal Token Unantichated • 2 months ago

I now see an access code in your code sample of the opening post. Is that actually the token that you are using? It looks to me like you grabbed the code from the database column and just pasted it in.. If you are that is your problem. The token stored in the database is an encrypted version of the real token. I just run a create accesstoken command locally and here is what you should get:

$user = \App\User::find(1);
$token = $user->createToken('Token name')->accesToken;

dump($token);

//yields:
/*
 eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjRkOWUyZGMxMTQ5ZTNjOTZhMTYyMzZjYmQ1ZDczZGU1N2E2YjhmMWExMDdiNjU2YWFmN2JmNTVlYTFkZDZlNmQ1NDVjYjkyOTU3MmU1ZmZjIn0.eyJhdWQiOiIxIiwianRpIjoiNGQ5ZTJkYzExNDllM2M5NmExNjIzNmNiZDVkNzNkZTU3YTZiOGYxYTEwN2I2NTZhYWY3YmY1NWVhMWRkNmU2ZDU0NWNiOTI5NTcyZTVmZmMiLCJpYXQiOjE0OTQ2NjYzMjEsIm5iZiI6MTQ5NDY2NjMyMSwiZXhwIjoxNTI2MjAyMzIxLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.lzyk8gOyYPAxxtChS-UsX7uAx72wD4EWqSqhcsnYKpTlQ7HgsJ-LWSa2qsvF2o-bb5MYAm2rAjeIOiW_fVsbz1ksd0KiKVvidfTGSCru19z_edCK6SuaAgfA646M4I9wPYTfV0xoCVvcWtktPcOcIO9YQBBH7A__Y_iDTJjdXsMW17e2qW5Z_KPrKtmHceWaMIuUWanL8Anm5tran_04kJpwJgRhumHrxvINhRYIEjabqo5gvpTw3bptlXhhNQwn2otRkXWCLvXEAFp4DbT2cj_RYtvjyPhgRt6XrhE-lmo4pTnAmFwTlCWrH5SQ_vJmV0pvTPamvduWmz4M_46UIQ5UF6JrPnxE2gXGLNElA9z0A0ygtYhyiw3i2oQk714Wo8Ea-oHZR81H_Bh85JBdy6KM39uLe0fpWz8TLbcWK7amqiYVLGyWgUTbBpRVNc-dP7cHV0_gh3yGKITDhj8rTSw5l91DUHq8Gwjrxxy8ZkisvlC2qdJHMdrWtzt0921Vcl_Vo3Vfmm4-gQNhWMKG5QbZXUbdzJbiR2lrKdJqwszqALYmG2WFRRqqifQQuCw8X0nu1NnI6vVDL3QSC-01x3v9M1h2J0AGWJAlzeUb3KAFC6qmC8s8R6rfQQxrLOwNFlFvE4so-faHByhMPmBUTrlmdJfkVFrictUY8SPi3Cw
*/

//however in database code is stored as:
//4d9e2dc1149e3c96a16236cbd5d73de57a6b8f1a107b656aaf7bf55ea1dd6e6d545cb929572e5ffc

Are you sure you're actually using a valid token?

12th May, 2017

tim_jespers left a reply on Setup A Different Table In A Different Database For One Model Only • 2 months ago

In order to use a different database you'll have to setup a second connection in your config/database.php file.

You can then set the connection property on the model to that connection for it to use the second connection instead of the default one.

Class SpecialModel extends Model {
....
    protected $connection = 'your_second_connection';
....

}

tim_jespers left a reply on Passport Personal Token Unantichated • 2 months ago

This might be a silly question but did you make sure you are using the passport authentication for the given route and not the regular one?

tim_jespers left a reply on [Symfony\Component\Debug\Exception\FatalThrowableError] Parse Error: Syntax Error, Unexpected End Of File • 2 months ago

Did you take a look in the error log to see if it has dumped a stacktrace in there? That could give you some clues?

tim_jespers left a reply on Data Recovery With BelongsTo • 2 months ago

First of all i would recommend some name changes so that the relationship gets the name agence instead of getAgence also by default laravel looks for a column called agence_id (modelname_id) as its foreign key column while your column is called agence therefore you need to specify the foreign key column explicitly:

public function agence(){
        return $this->belongsTo('App\Agence', 'agence');
    }

And for the fetching:

$stock = Occasion::with('agence')->where('agence', $agence)->get();

tim_jespers left a reply on Improve Collection! • 2 months ago

You could inverse the code a bit. First map your collection, returning the function output when it exists, returning null if it doesn't then you can do a more clean reject afterwards to keep only the relevant data?

$someCollection->map(function($value,$attribute){
    return class_exists($this->getClassname($value,$attribute)) ? app($this->getClassName($attribute)) : null;
})->reject($value){return is_null($value);} 

though i'm wondering, you're having this collection but for as well the filter as the map operation you're using the second argument (the key, not the value). So perhaps you could start by getting a collection of only the keys first which makes it even cleaner:

$someCollection->keys()->map(function($attribute){
return class_exists($this->getClassname($attribute)) ? app($this->getClassName($attribute)) : null;
})->reject($value){return is_null($value);} 
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.