hi i have 3 table 1st is products 2nd is category 3rd is designer
products and category is many to many relationship
product belongsto designer & designer hasMany products
designer belongsto category & category hasMany designers
here is my table
product
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('image');
$table->string('stock');
$table->string('title');
$table->string('slug')->unique();
$table->string('gender');
$table->text('description');
$table->integer('price');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
$table->dateTime('published_at');
});
designers table
Schema::create('designers', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
category table
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('category_product', function (Blueprint $table) {
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('restrict')
->onUpdate('restrict');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')
->onDelete('restrict')
->onUpdate('restrict');
$table->timestamps();
});
adding missing column in products table
Schema::table('products', function (Blueprint $table) {
$table->integer('designer_id')->unsigned();
$table->foreign('designer_id')->references('id')->on('designers')
->onDelete('restrict')
->onUpdate('restrict');
});
adding missing column in designer
Schema::table('designers', function (Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('restrict')
->onUpdate('restrict');
});
here is my controller
public function productpost(Request $request){
$this->validate($request, [
'title' => 'required|max:255',
'description' => 'required',
'price' => 'required',
'image' => 'image|required',
]);
$designer_name = $request->designer;
$designer_slug = str_random(40);
$designer = designer::where('name', $designer_name)->firstOrCreate(
['name' => $designer_name], ['slug' => $designer_slug]
);
$designer->name = $designer_name;
$designer->slug = $designer_slug;
$designer->save();
$designer_id = $designer->id;
$product = new Product;
$product->title = $request->title;
$product->designer_id = $designer_id;
$product->description = $request->description;
$product->price = $request->price;
$product->stock = $request->stock;
$product->gender = $request->gender;
$product_slug = str_random(40);
$product->slug = $product_slug;
$product->user_id = Auth::user()->id;
$product->published_at = Carbon::now()->format('Y-m-d');
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$file->move(public_path().'/images/product/', $name);
$product->image = $name;
$thumb = Image::make(public_path().'/images/product/' . $name)->resize(1200,1800)->save(public_path().'/images/product/thumb/' . $name, 90);
}
$product->save();
$productsearch = product::where('slug', $product_slug)->firstorfail();
$product_id = $productsearch->id;
$categoryname = $request->category;
foreach ($categoryname as $name) {
$category = category::firstOrNew(['name' => $name]);
$category->designer_id = $designer_id;
$category->save();
$category->products()->attach($product_id);
}
return Redirect::back()->with('status', 'Post Success');
missing is product need designerid
designer need category_id
category need product_id
how to solve this on controller thank you
You can't update the designer_id column in that way unless you've added designer_id to the fillable array in your model.
Alternatively, you can use the Eloquent methods by simply doing $product->designer()->associate($designer); instead of $product->designer_id = $designer->id.
If you haven't already, you'll also need to setup a relationship on the Product model.
public function designer() {
return $this->belongsTo(Designer::class, 'designer_id');
}
Related
I want to save the datetime of last interaction of a user with the application inside the user table.
I'm using Laravel 8.
I added a column in users table (last_interaction):
Schema::create('users', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->integer('id', true);
$table->string('firstname');
$table->string('lastname');
$table->string('username', 192);
$table->string('email', 192);
$table->string('password');
$table->string('avatar')->nullable();
$table->string('phone', 192);
$table->integer('role_id');
$table->boolean('statut')->default(1);
$table->datetime('last_interaction'); //The column where to save the datetime of last interaction
$table->timestamps(6);
$table->softDeletes();
});
Is it possible to update the users table with each request done! or should i do it on login only (for Optimisations) ?
You can make new middleware with this command php artisan make:middleware LastInteraction
App\Http\Middleware\LastInteraction.php:
public function handle(Request $request, Closure $next)
{
if (Auth::check()) {
$user = Auth::user();
$user->last_interacted = Carbon::now();
$user->save();
}
return $next($request);
}
This will set a field of last_interacted to the current time given this field exists in your migration. If it doesn't exist create one.
App\Http\Kernel.php
protected $middleware = [
(...)
\App\Http\Middleware\LastInteraction::class,
];
This will register the middleware to be applied globally to each route.
I am making a project in Php Laravel that allows the logged in user to rent a book, but if the logged in user has rented 1 book, I am trying to prevent different book rentals, but what I am doing does not work, where is my mistake?
1-"This is my code where i rent a book" :
public $user_id;
public $kitap_id;
public $AlimTarihi;
public $TeslimTarihi;
public $durum;
public function kirala($kitap_id)
{
if(Auth::check())
{
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi"))
{
session()->flash('message','There is a book you are renting.');
return redirect('/user/dashboard');
}
else
{
$kira = new Kira();
$kira->user_id = Auth::user()->id;
$kira->kitap_id = $kitap_id;
$kira->AlimTarihi = Carbon::now();
$kira->TeslimTarihi = Carbon::now()->addDays(7);
$kira->durum = 'Edilmedi';
$kitaplar = Kitaplar::find($kitap_id);
$kitaplar->kiraliMi = 1;
$kitaplar->save();
$kira->save();
session()->flash('message','book is rented.');
return redirect('/user/dashboard');
}
}
else
{
return redirect()->route('login');
}
}
2- "Rent table" :
Schema::create('kiras', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned()->nullable();
$table->bigInteger('kitap_id')->unsigned()->nullable();
$table->timestamp('AlimTarihi')->nullable();
$table->timestamp('TeslimTarihi')->nullable();
$table->enum('durum',['Edildi','Edilmedi'])->default('Edilmedi');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('kitap_id')->references('id')->on('kitaplars')->onDelete('cascade');
});
3- "Book table" :
Schema::create('kitaplars', function (Blueprint $table) {
$table->id();
$table->string('KitapAdi');
$table->BigInteger('BarkodNo');
$table->BigInteger('SayfaSayisi');
$table->decimal('SatisFiyati')->nullable();
$table->string('image')->nullable();
$table->text('images')->nullable();
$table->bigInteger('kategori_id')->unsigned()->nullable();
$table->bigInteger('yazar_id')->unsigned()->nullable();
$table->boolean('kiraliMi');
$table->timestamps();
$table->foreign('kategori_id')->references('id')->on('kategoris')->onDelete('cascade');
$table->foreign('yazar_id')->references('id')->on('yazarlars')->onDelete('cascade');
});
4- "User table" :
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('lastName')->nullable();
$table->BigInteger('Yasi')->nullable();
$table->string('Adres')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->string('utype')->default('USR')->comment('ADM for Admin and USR for User or Customer');
$table->timestamps();
});
I believe your initial if-check isn't doing what you expect. This line:
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi"))
is an incomplete builder object, so will always return true. I suggest completing the query with something along the lines of:
if(isset(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi")->first()))
or if you have allowed multiples rented out in some previous instance, something like this might work as you wish:
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi")->count())
I am trying to create a new record in one table while updating a specific column in another table. One table is users, the other table is assigned_units.
This is the AssignedUnitController for store
public function store(AssignUnitRequest $request)
{
if ($request->isMethod('POST')) {
$data = $request->all();
//validate data
$validated = $request->validated();
$data['tenant_id'] = $request->get('tenant_id');
$data['prop_id'] = $request->get('prop_id');
$data['unit_id'] = $request->get('unit_id');
$data['billing'] = $request->get('billing');
$datetime = Carbon::createFromFormat('d/m/Y',$data['start_date']);
$data['start_date'] = $datetime;
AssignedUnit::create(
$data
);
if ($validated = $request->validated()) {
Session::flash('success', 'Unit is successfully assigned');
return redirect()->route('admin.tenants.index');
}
else {
return back();
Session::flash('error_message', 'Unit is not assigned');
}
}
}
This is the assigned controller for create
$data['tenant'] = User::findOrFail($id);
$data['properties'] = Property::getAllProperties();
$data['property'] = null;
$data['units'] = [];
$data['unit'] = null;
$data['rentings'] = AppHelper::RENTING_STATUS;
$data['renting'] = 1;
$data['cycles'] = AppHelper::BILLING_CYCLE;
$data['cycle'] = 1;
return view('admin.tenants.assign.form',$data);
I have a request $data['renting'] = $request->get('renting'); which is entered in this form but should be updated on the users table
the users table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->enum('renting',[0,1]);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
How do I update the users table, renting column, from AssignedUnitController
how i can fix this error ?
this is my error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(coachers.article_comments, CONSTRAINT
article_comments_user_id_foreign FOREIGN KEY (user_id) REFERENCES
users (id)) (SQL: insert into article_comments (name, email,
description, article_id, user_id, updated_at, created_at)
values (aaaaa, aaa#gmail.com, hhhhhhsssshhshsh, 1, 0, 2019-10-17
08:12:17, 2019-10-17 08:12:17))
public function commentArticle($user_id, $article_id, Request $request)
{
if (!$user_id == 0) {
$register = $request->validate([
'description' => 'required|min:5',
]);
$commentarticle = new articleComment();
$commentarticle->description = $request->input('description');
$commentarticle->user_id = $user_id;
$commentarticle->article_id = $article_id;
$commentarticle->name = 'name';
$commentarticle->email = 'email';
$commentarticle->submit = 0;
$commentarticle->save();
return $request;
}
else if ($user_id == 0) {
$register = $request->validate([
'description' => 'required|min:5',
'name' => 'required|min:3',
'email' => 'required|min:5|max:150|email',
]);
$comment = new articleComment();
$comment->name = $request->input('name');
$comment->email = $request->input('email');
$comment->description = $request->input('description');
$comment->article_id = $article_id;
$comment->user_id = 0;
$comment->save();
return $comment;
}
}
and my api :
Route::post('comment-article/{user_id}/{article_id}', 'ArticleController#commentArticle');
and my table
public function up()
{
Schema::create('article_comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id')->unique()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('article_id')->unique()->nullable();
$table->foreign('article_id')->references('id')->on('articles');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('submit')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
remove unique() method from user_id and article_id column and rerun migration again..
public function up()
{
Schema::create('article_comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('article_id')->nullable();
$table->foreign('article_id')->references('id')->on('articles');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('submit')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
if user_id is not there then user_id set a null not a (zero)0
$comment->user_id = NULL;
It looks like there is no user with id == 0 in your users table. And since there is a foreign key constraint the operation fails.
I have a table like this:
Schema::create('partners', function (Blueprint $table) {
$table->increments('id');
$table->binary('image');
$table->string('name');
$table->string('link');
$table->timestamps();
});
Then, after validation, I need to add data from forms, defined as this:
{{Form::file('image')}} I tried this way:
public function newPartner(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'link' => 'required'
]);
if ($validator->fails()) {
return redirect('partners/create')->withErrors($validator);
}
Partner::create($request->all());
return redirect('/');
}
But it doesn't fill the binary field with the uploaded image.
How can I achieve this?
Thank you for helping me.