Laravel Eloquent Create - laravel

Hello so I've started using Laravel and it is useful and easy. For now I have a CRUD in which is working. In my AccountController#store the code is:
public function store(Request $request)
{
$input = $request->all();
Accounts::create($un);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
This basically adds a new account in my table. My problem is, I have a password textbox and I can't hash it since this code automatically gets every input in the form. How can I get it one by one? Like username, email and password only so I can hash the password.

You could get the input one by one and then hash the password and save it to the database. But that would require extra code.
You could also add an extra function to your Account model that will take care of this automatically.
Take a look at the example I use to create my management users.
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Hash;
class Management extends Model implements AuthenticatableContract {
use Authenticatable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'Management';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Automatic hash function for the password.
*
* #var array
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
}
Regarding your code, you could do this:
public function store(Request $request)
{
Accounts::create($request->all());
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
Make sure to modify the example model above to your own needs!

You can also do:
public function store(Request $request)
{
$input = $request->all();
Accounts::create([
'username' => $input['username'],
'password' => bcrypt($input['password']),
]);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}

You call Input::all() to get all the attributes passed in, and Input:get('key') to get a specific key.
So you should call:
$account = new Accounts;
$account->username = Input::get('username');
$account->password = Hash::make(Input::get('password'));
//key with a default
$account->password = Input::get('age', 20);
//optional field
if (Input::has('optional')) {
$account->optional = Input::get('optional');
}
//any other fields that account needs
$account->save()

Related

getting error when applied WHERE clause on a model(parent) and then gets its related model(child) data in eloquent

I have a User model which is a parent and Project model which is a child. I created a one-to-many relationship between these two like below.
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function projects(){
return $this->hasMany('App\Project', 'user_id');
}
}
Project Model:
class Project extends Model
{
// Table Name
protected $table = 'projects';
//Primary Key
protected $primaryKey = 'project_id';
// Timestamps
public $timestamps = true;
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
when applying where clause on user model and then getting its related projects:
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::where('email', $request->input('client'))->projects;
}
}
getting error
Exception
Property [projects] does not exist on the Eloquent builder instance.
but when doing
$client = User::find(id)->projects;
above query is giving me results.
Result Expected: i want to get the User model data by WHERE() clause instead of Find() clause and then gets its related projects.
As the Error Says that you dont have property in the Builder
$client = User::where('email', $request->input('client'))->projects;
try this
$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;
here we are getting the user with the specific email and loading the realtion and here you get the relation as object
The source of your issue is that you have not yet retrieved any users. Before calling first() or get() on the query builder, you are limited to functions of the query builder.
Short version: call first() before accessing the projects
$client = User::query()
->where('email', $request->input('client'))
->first()
->projects;
Optional: add with('projects') to eager load the projects. This doesn't add any performance bonus in your case though, as you are only loading a single model.
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::with('projects')->where('id');
}
}
In HomeController this line will retrun collection of array.... In simple words it will return multiple records....
$client = User::where('email', $request->input('client'))->projects;
As you want single record use first (). To retrive single record... It will retrun first matching record...
$client = User::where('email', $request->input('client'))->first()->projects;

Laravel getting information from other table

I have the following tables user table, post table and profile table. the post belongs to a user and the profile belongs to a user. I also have a forum were people can post I want the users username to show instead of their name. But The username is in the profiles table and I don't know how to get it.
here is my code
class Post extends Model
{
//
public function users(){
return $this->belongsToMany('App\User','posted_by');
}
class Profile extends Model
{
//
public function users(){
return $this->belongsTo('App\User','whos_profile');
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname','lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile(){
return $this->hasOne('App\Profile');
}
public function post(){
return $this->hasMany('App\Post');
}
}`enter code here`
You can get it as follows
$user = User::find($id);
if($user->profile){
echo $user->profile->username;
}
You should try this:
$rsltUsers = User::with(['profile','post'])->where('id',$id)->get();
foreach($rsltUsers as $rsltUsers){
dd($user->profile->username);
}

Do something before saving model to database in Laravel 5.1

How can I do something such as modify some data fields or more validate before writing data to database in Laravel 5.1 model ?
It's document about that problem is hard to use in real application: http://laravel.com/docs/5.1/eloquent#events
My code is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;
class Atoken extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'atoken';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'token',
'user_id',
'role',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
];
public static function newToken($userId, $role){
# Remove all token assoiciate with input user;
Atoken::where('user_id', $userId)->delete();
$params = [
'user_id' => $userId,
'role' => $role,
];
Atoken::insert($params);
$item = Atoken::where('user_id', $userId)->first();
return $item->token;
}
protected static function boot(){
static::creating(function ($model) {
$model->token = 'sometoken';
});
}
}
In this case, I always got error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))
How can I fix it?
class Lunch extends Eloquent
{
protected static function boot()
{
static::creating(function ($model) {
$model->topping = 'Butter';
return $model->validate();
});
}
protected function validate()
{
// Obviously do real validation here :)
return rand(0, 1) ? true : false;
}
public static function newToken($userId, $role)
{
static::where('user_id', $userId)->delete();
return static::create([
'user_id' => $userId,
'role' => $role,
])->token;
}
}
I would recommend to go into EventServiceProvider, and register event listeners
public function boot(DispatcherContract $events)
{
parent::boot($events);
// Register Event Listeners
\App\Product::updating(function ($product) {
$product->onUpdating();
});
...
then create function onUpdating within the model. You also can choose from saving, saved, creating, created, updating, updated..
This documentation has more:
https://laravel.com/docs/5.1/eloquent#events

Eloquent ORM all() not returning anything

Shoot me down if I this is a silly question, but I am really struggling to get this all() function working for me. It is returning empty list for me. Any help will be highly appreciated. I have got 2 rows in the newsletters table
Model looks like this -
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Newsletters extends Eloquent {
//use UserTrait, RemindableTrait;
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'newsletters';
/**
* The attributes excluded from the model's JSON form.
*
* #var array */
protected $guarded = array('newsletterId');
protected $fillable = array('name', 'subject','from_email','from_name');
public static $rules = array(
'name' => 'required|min:5',
'subject' => 'required|min:5',
'from_email' => 'required|email',
'from_name' => 'required'
);
}
My call in the controller is like this -
<?php
class newslettersController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//$newsletters = Newsletters::paginate(3);
$newsletters = Newsletters::all();
echo $newsletters;exit();
return View::make('newsletters.index', compact('newsletters'));
}
Any value - even 0000-00-00 00:00:00 - in the deleted_at column tells Laravel that the item has been deleted. Change your default value for that column to NULL or new items will be flagged as deleted on creation.
The $table->softDeletes() Schema function does this automatically if you use it in a migration.
As soon as you use the SoftDeletingTrait a global scope will be applied to every query with your model so all records where deleted_at is not NULL will be ignored.
Illuminate\Database\Eloquent\SoftDeletingScope:
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->whereNull($model->getQualifiedDeletedAtColumn()); // <<-- this
$this->extend($builder);
}
Change the default of your deleted_at column to NULL and update the existing records to be NULL as well.
If you are sure newsletters is the correct table name as #Ray said.
Try this:
$newsLetters = DB::table('newsletters')->get();

Logging in a user?

I'm having trouble with logging users in, everything appears to be in the right place, I get no errors in the log, but users fail to log in, I am using the correct credentials that are in my database.
Please note I have a different set up to the normal one:
My table is called test_users
My model sits in a separate namespace called Test
Here's my code:
In config>auth I have set:
'model' => '\Test\User',
'table' => 'test_users',
Here is how I call the Auth:
public function logIn()
{
$input = Input::all();
$credentials = array('email' => $input['email'], 'password' => $input['password']);
$input['remember-me'] = isset($input['remember-me']) ? true : false;
if(Auth::attempt($credentials, $input['remember-me']))
{
$this->output['message'] = 'ok';
}
else
{
$this->output['message'] = 'fail';
}
return $this->output;
}
Here's my model:
<?php namespace Test;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Eloquent;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'test_users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Auth::attempt checks for a hashed password. It appears you might be trying to set them with plaintext. Try setting your passwords with Hash::make('password') if you aren't already.

Resources