I have a problem with using Algolia. Working with database but i can't save it in to API Algolia.com. I tried to search through google but i didn't get any results for this problem.
My controller:
public function store(Request $request)
{
$role = new Role;
$role->name = $request->name;
$role->save();
}
My model:
<?php
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use Searchable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
/**
* Get the index name for the model.
*
* #return string
*/
public function searchableAs()
{
return 'roles_index';
}
}
In you env file, make sure you are setting the admin key as the ALGOLIA_SECRET.
By default, Algolia gives you different key:
Search key, which can only perform search (read) operations.
Write key, which can index (write) data.
Admin key, which can do everything. This is the recommended one for Laravel Scout.
Please note that only the search key can be passed to your frontend, if you use Vue InstantSearch for instance.
Please let me know if that solved your issue.
Related
Whenever I create a "user", I have to create a line in different tables (like account).
I know that in the controller I can create the user and account like this:
$user = User::create($user_inputs);
$account = $user->account()->create($account_inputs);
$OtherTables...
Is there a way to do this in the model? Always when someone creates a user from another controller, will the lines be automatically inserted in the other tables. Or is it always necessary to indicate it in the controller every time?
You can use Laravel observer
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver
{
/**
* Handle the user "created" event.
*
* #param \App\User $user
* #return void
*/
public function creating(User $user)
{
$user->account()->create([
// your data
]);
}
}
You can use model events for this. https://laravel.com/docs/9.x/eloquent#events-using-closures
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* #return void
*/
protected static function booted()
{
// This code will be called every time a new user is inserted into the system
static::created(function ($user) {
$user->account()->create([ 'name' => $user->name ])
});
}
}
There are few more events you can use within booted method, the name tells clearly what they do.
creating
created
updating
updated
saving
saved
deleting
deleted
I am trying to do some logic via a custom Console Command I created using Artisan but I am unable to use my model class and query using Eloquent.
When I use MyModel::all() it will return all records in a collection. This is great except the model I am using has too many records to load all of them into memory.
I am trying to use
MyModel::where('id',$currentLoopId)->get();
This returns an empty collection :(
My Console Class is as follows:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\ProcessReferral;
use App\TargetUrl;
use App\Website;
class ProcessReferrals extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'process:referrals';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Process all outstanding records in process_referrals table';
protected $logArray = [];
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$this->info('Start Processing Referrals');
$process_referrals = ProcessReferral::all();
$referral_count = count($process_referrals);
$this->info('Found '.$referral_count.' referral(s) that need processed');
foreach($process_referrals as $referral){
## 1. SEE IF REFERRAL WEBSITE IS ACTIVE AND VERIFIED IN AFFILIATE_WEBSITES. LOAD LAST FORCE UPDATE REFRESH CODES
########################################
$this->info('Processing Referral ID: '.$referral->id);
$this->info('Get Website from Affiliate Website Id: '.$referral->affiliate_website_id);
$websites = Website::where('id','=',$referral->affiliate_website_id)->get();
dd($websites);
... ( more Logic after I get website )
}
}
My Model Class is as follows:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'affiliate_websites';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
...
];
... ( Eloquent Relations )
}
Database Table:
id website_label referrals
------------------------------
1 Google UK 920685
2 Google U.S. 2940884
3 Google Germany 709603
First Dummy Data Record being processed:
id affiliate_website_id
-------------------------
2 3
Output on Terminal
$ php artisan process:referrals
Start Processing Referrals
Found 300 referral(s) that need processed
Processing Referral ID: 2
Get Website from Affiliate Website Id: 3
Website(id->62) is Active.
Illuminate\Database\Eloquent\Collection {#901
#items: []
}
I have tried a handful of different ways to query including DB::select() which returns what I am looking for but I cannot dynamically set the id I am searching for with that convention.
My Model works everywhere else in my application, I think there is some sort of Namespacing issue coming into play but I am at a complete loss as to why it wouldn't work.
Any help would be very appreciated!
As pointed out by #machuga on http://laravel.io/chat
I checked to see if the ID i was passing was an integer
$website = Website::where('id',(int)$referral->affiliate_website_id)->first();
Still had some issues but used ->first() to get a single record instead of ->get() so I dont have to loop over the Website collection
I have problem to my apps this input password hash.
$simpan['password']=Request::input('password');
how make hash in my code?
You have two options
Call make method on Hash facade
Hash::make('string_here')
Or use global helper function bcrypt('string_here')
Example:
//Hash facade example
$simpan['password']= Hash::make(Request::input('password'));
//bcrypt global helper function
$simpan['password']= bcrypt(Request::input('password'));
Resource:
https://laravel.com/docs/5.1/hashing
In Laravel we can handle it a very intelligent and efficient way by using Mutators in Model Class.
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
// Password hassing by default to all new users,
public function setPasswordAttribute($pass)
{
// here you can make any opration as you like
$this->attributes['password'] = Hash::make($pass);
}
}
now you don't have to do manually password hashing every time
just store user in table by create or any other method
$created_user = User::create(request()->all());
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()
I am having an issue with laravel not seeing my tags() method for attaching new tags on a new entry. I keep getting Call to a member function on a non-object when I try to run the method and attach tags to my Tile model. All methods are returning their relations. I followed the same order as the documentation says eloquent.
Controller
$tile = \Tiles\Tile::find($tile_id);
$tile->tags()->attach($tag_array);
Model
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
/**
* The Tile table
* #var string
*/
protected $table = 'tiles';
/**
* Pivot table for tags
* #var string
*/
protected $pivot = 'tag_tile';
/**
* Get the tags associated with the given tile
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tile_id', 'tag_id')->withTimestamps();
}
}
Try it
Model
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tag_id', 'tile_id')->withTimestamps();
}
Thanks for all your help. I figured out the solution. I created a method in my model and pushed each to an array and fed it to the attach method. It works now.