How to call function as auto increment in laravel - laravel-9

I'm trying to call my function as auto increment value in laravel, but i dont know how to do it.
The function i'm trying to use is
public function generateRandomString()
{
$pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
return $pass;
}
and the column im trying to call the function are 'No_Resi'
public function up()
{
Schema::create('order', function (Blueprint $table) {
$table->increments('No_Resi');
$table->string('Nama_Lengkap',100);
$table->text('Alamat_Pengambilan',100);
$table->text('Alamat_Tujuan',100);
$table->integer('No_Telepon_Pengirim');
$table->integer('No_Telepon_Penerima');
$table->enum('Jenis Barang',['Makanan','Dokumen','Barang Pecah Belah','Pakaian',
'Obat-Obatan','Buku','Lainnya']);
});
}
so the output should be something like this
No_Resi
Nama_lengkap
1B45CY
someone
9K0L7T
nobody

Related

(laravel ) checkbox toggle is not working. And Changing text do not working either.What's wrong with mycode?

I am new to laravel and creating todo list.
I try to toggle checkbox.
BUt in checked method(the bottom of PostController), I can't even change text in the first place.
What's wrong with checked method?
I expect a problem in web.php.
I'm using laravel8.
thankyou for your help!
What's wrong with checked method?
(((PostController.php)))
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Http\Requests\PostRequest;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->get();
return view('index')
->with(['posts' => $posts]);
}
public function show(Post $post)
{
return view('posts.show')
->with(['post' => $post]);
}
public function checked(Post $post)
{
// $post->is_done = !$post->is_done;
$post->title = 'hogehoge';
$post->save();
return redirect()
->route('posts.index');
}
}
(((web.php)))
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('/', [PostController::class, 'index'])
->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])
->name('posts.show')
->where('post', '[0-9]+');
Route::patch('/posts/{post}/checked', [PostController::class, 'checked'])
->name('posts.checked')
->where('post', '[0-9]+');
(((post table column)))
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('is_done')->default(false);
$table->timestamps(); // created_at, updated_at
});
}

How to get the default $id from another table using laravel model relationship?

I am facing the problem whereby I don't know the syntax of letting the id of my property model equals to property_id value in property_doc table.
In PropertyDoc model
public function property()
{
return $this->belongsTo(Properties::class, 'property_id');
}
In Properties model
public function property_id()
{
return $this->hasMany(PropertyDoc::class, 'property_id');
}
In PropertyController
public function StoreInfoProperty(Request $request)
{
$propertyInfo = new PropertyDoc;
$propertyInfo->property_id = $property_id;
}
I am stuck at retrieving the default id value in properties database to be equal to the property_id in property_docs database. Thank you.
You should change the naming of the relationship, see my example below:
In Properties model
public function propertyDocs()
{
return $this->hasMany(PropertyDoc::class, 'property_id', 'id');
}
In PropertyDoc model
public function property()
{
return $this->belongsTo(Properties::class, 'property_id', 'id');
}
In controller
public function StoreInfoProperty(Request $request)
{
$propertyDoc = PropertyDoc::with(['property'])->where('...logic here');
$property_id = $propertyDoc->property->id;
}
hope can help you and happy coding !

Convert local scope to global scope or query by parent attribute

I want to retrieve all comments which belong to active posts.
I have a local scope on my Posts model looking like this.
public function scopePublic($query) {
return $query->whereHas('post', function ($q) {
$q->where('is_public', true);
});
}
Which works fine, but breaks with PHP message: PHP Fatal error: Allowed memory size of X bytes exhausted as soon as I want to convert it to a global scope like this:
static::addGlobalScope('is_public', function (Builder $builder) {
return $builder->whereHas('post', function ($q) {
$q->where('is_public', true);
});
});
My end goal is for all comment queries only to show public comments, unless I specifically ask not to.
I've been through quite a few solutions. I've tried joining the post on the comments, and I tried adding a sub-select to no luck.
$builder->addSelect(['is_public' => Post::select('is_private')
->whereColumn('id', 'comment.post_id')->limit(1)
]);
$builder->join('posts','posts.id','=','comments.post_id')
->where('comments.is_private', false);
Make a new class PublicScope
use Illuminate\Database\Eloquent\Scope;
class CommentPublicScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->whereHas('post', function ($q) {
$q->where('is_public', true);
});
}
}
Then you can add the global scope
Class Comment extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new CommentPublicScope);
}
}

Laravel login error

I'm quite a newbie in laravel. I looked up a video tutorial to set up registration and login. Registration works perfectly, but I'm having trouble with login. At first it worked perfectly, but then I noticed, that that doesnt matter with which user do I log in, it's always the same user, who is logen in. But now, out of nowhere, i can't even log in, it throws an error:
"Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given"
I think that I know where the mistake is, but I do not think that my skills are that advanced to solve it.
Here is my UserController code:
public function login()
{
return View::make('user.login', array('title'=>'Login'));
}
public function userlogin()
{
$validate = Validator::make(Input::all(), array('UserName'=>'required|alpha_num',
'Password'=>'required'));
if($validate->fails()){
return Redirect::back()->withErrors($validate)->withInput(Input::get());
}
else{
$checkuser=UserModel::login(input::all());
if($checkuser[0]){
Auth::login(User::find(1));
return Redirect::to('users');
}
else{
return Redirect::back()->withErrors(array('loginerror'=>$checkuser[1]))
->withInput(Input::get());
}
}
}
here is my UserModel code:
public static function login($values){
$pickPassword=DB::table('users')->where('name', '=', $values['UserName'])->pluck('password');
if(!$pickPassword){
return array(false, "User not found!");
}
else{
$checkPassword=Hash::check($values['Password'],$pickPassword);
if($checkPassword){return array(true);}
else {return array(false, "Wrong password");}
}
}
Here is my user table:
public function up()
{
Schema::create('users', function($table)
{
// Autoincrement+INT+primary key (Laravel requires)
$table->increments('id');
$table->string('name', 100); // VARCHAR 100
$table->string('email'); // VARCHAR 255
$table->string('password', 60); // VARCHAR 60
$table->text('about'); // TEXT 64K
// Integer + unsigned 4Bytes
$table->integer('favorite')->unsigned();
$table->timestamps(); // timestamps (Laravel requires)
$table->rememberToken();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
I think the problem is somewhere UserController with Auth::login, but not really sure, it worked perfectly a while ago...
Auth::login(User::find(1));
with this line, you are doing a login for the first user all the time
in this block:
else{
$checkuser=UserModel::login(input::all());
if($checkuser[0]){
Auth::login(User::find(1));
return Redirect::to('users');
you need to pass the arguments given from your login form to auth. For example:
if (Auth::attempt(array('email' => $email, 'password' => $password)))
This is what you are actually doing, login a user manually:
http://laravel.com/docs/4.2/security#manually
SIDENOTE:
The laravel documentation on Authentication is amazing, go check it out!

I use setState in Yii but i also get Property "CWebUser.depId" is not defined

i want to return the value dep_id from table user to use it so setState is supposed to return it like (Yii::app()->user->depId) but when i use it i get -- "CWebUser.depId" is not defined. i searched and i dont know what to do and i need a quick answer this is my
example:
private $_id;
//private $_dep_id;
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->setState('depId',$user->dep_id);
$this->username=$user->username;
$this->setState('lastLogin', date("m/d/y g:i A", strtotime($user->last_login_time)));
$user->saveAttributes(array('last_login_time'=>date("Y-m-d H:i:s", time())));
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
public function getId()
{
return $this->_id;
}
and then i get this
Property "CWebUser.depId" is not defined.
what is the problem here ?!
You have to be authenticated user to use that variable on above scenario because it is restricted for authenticated users.