PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to populate a field in a laravel model even if the field it's not in the form request

 November 16, 2022     laravel, laravel-6, model, php     No comments   

Issue

sorry for the messy title.

So, I have a basic User model and I'm trying to register a new user, the thing is one of my field in the users table is a 'screen_name' that I would like to be filed automatically with the the first 'word' from the name attribute.

How can I do that?

I've tried

public function setScreenNameAttribute($value){
   return 'MyFirstName';
}

But as I understand, the set***Attribute will only be fired if I have this field in my form request, but I don't want the user to fill this field I want the model to do that by it's own.


Solution

Model

public function setScreenNameAttribute($value)
    {
        $this->attributes['screen_name'] = strtolower(strtok($value, ' ')); // First name from the full name as screen name
    }

Controller

$user->screen_name = 'John Smith'; // your request value goes here - $request->full_name; 

You don't need to have a field for that in the form.

Hope this helps.

Let me know if doesn't work.


Updated / Anohter solution.

protected $attributes = array(
  'screen_name' => 'Your name' // Any values
);

public function __construct(array $attributes = array())
{
    $this->setRawAttributes(array(
      'screen_name' => strtolower(strtok($attributes->first_name, ' '));
    ), true);
    parent::__construct($attributes);
}


Answered By - Kaushik Thakkar
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing