add all user ids for one product - laravel

For adding to cart customer has to logg in,in cart table I have a column for user_id but in user_id column all of user_id in database add!for example for product1 all user1,user2,user3 ides add not just the one logged in
cart table:
Schema::create('cart', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->char('user_id');
$table->string('session_id');
$table->string('product_name');
$table->string('user_email');
$table->integer('qty');
$table->integer('product_price');
$table->timestamps();
});
addToCart method in controller:
public function addtocart(Request $request){
$data = $request->all();
if (empty($data['user_email'])){
$data['user_email'] = ' ';
}
$user_id = User::get('id');
if (empty($user_id)){
$user_id = Auth::user()->id;
}
$session_id = Session::get('session_id');
if (empty($session_id)){
$session_id = Str::random(40);
Session::put('session_id' , $session_id);
}
DB::table('cart')->insert(['product_id' => $data['product_id'] , 'product_name' => $data['product_name'], 'user_id'=>$user_id,
'product_price' => $data['product_price'], 'qty' => $data['qty'], 'user_email' => $data['user_email'] , 'session_id' => $session_id ]);
return redirect('cart');
}
what is the problem?

You are currently requesting all the user ids by doing $user_id = User::get('id'); so if you want to set user_id as your authenticated user id you need to replace:
$user_id = User::get('id');
if (empty($user_id)){
$user_id = Auth::user()->id;
}
by:
$user_id = Auth::user()->id;
or shorter version:
$user_id = Auth::id();

Related

In Laravel, While updating Product record, it creates new record

CONTROLLER
public function updateproduct(Request $request, $id)
{
if($request->hasfile('images'))
{
foreach($request->file('images') as $file)
{
$name = time().'.'.$file->extension();
if($file->move(public_path().'/files/', $name)){
Image::create([
'images'=>$name,
'product_id'=>$product->id,
]);
}
}
}
$request->validate([
'name'=>'required',
'description'=>'required',
'images'=> 'nullable',
'price'=>'required|numeric',
'quantity'=>'required|numeric',
]);
$product = Product::findOrFail($id);
$product->name=$request->name;
$product->description=$request->description;
$product->price=$request->price;
$product->quantity=$request->quantity;
$product->update();
}
There is products table, images table and product_images table. It works fine while adding new product. But when I update the record, instead of updating data it creates new record.
$product = Product::where('id', $id)->first();
if(is_null($product)) {
$product = new Product();
}
$product->name = $request->input('name');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->quantity = $request->input('quantity');
$product->save();

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

Laravel 6 - validate unique, ignore on two conditions - same user and name. Also $this->id is null on update

I have the following rule so far.
$rules['name'] = [
'required',
'string',
'min:3',
'max:255',
Rule::unique('user_templates', 'name')->ignore($this->id),
];
Users can create records, but all his records must have a unique name (other users can have records with the same name). How can I do this? Also, $this->id on update is always null. What am I doing wrong?
Controller
public function update(UserTemplatesRequest $request, $slug)
{
try {
$model = UserTemplates::where('slug', XSS::clean($slug))
->firstOrFail();
} catch (ModelNotFoundException $err) {
return redirect()->action('UserTemplatesController#index');
}
$data = $request->validated();
if ($model->updateTemplate(XSS::clean($data, ['file']), $request)) {
$message = "There was an error, please try again";
$action = 'index';
$id = '';
} else {
$message = "Category Updated";
$action = 'edit';
$id = $model->id;
}
return redirect()->action("CategoriesController#{$action}", [$id])
->with('message', $message);
}
According to your Rule you can try and use a where clause to narrow it down to one user and not whole project like:
Rule::unique('user_templates', 'name')->where(function (Builder $query) {
return $query->where(
'user_id', '=', $this->user()->id;
})
user_id is the column inside your user_templates table that works as a foreign key with your users table.
About $this->id it should be $this->user()->id to retrieve your user id

How to insert many tags using foreign key?

[submit function][1]error message while insertingfunction for inserting tagserror while inserting into database many tags using foreign key .I am getting problem in array , it is unable to insert many tags
public function uploadSubmit(UploadRequest $request)
{
$product = new Product();
$product->name = $request['name'];
$product->save();
//$product = Product::create($request->all());
foreach ($request->photos as $photo) {
$filename = $photo->store('photos');
ProductsPhoto::create([
'product_id' => $product->id,
'filename' => $filename
]);
}
$tags = array();
$tags = array($request['tagname[]']);
foreach ($tags as $tag) {
ProductTag::create([
'tag_id' => $product->id,
'tagname' => $tag,
]);
}
$message = 'Upload successful!';
return redirect('/upload')->with('msg' , $message);
}
[Environment & details:[][2]][sql error 3]
Ok - so after learning a bit more about your current setup I think you would benefit from re-structuring it to the following:
Model Product to have tags() relationship method:
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable');
}
Add intermediate table taggable:
php artisan make:migration create_taggables_table --create=taggables
class CreateTaggablesTable extends Migration
{
public function up()
{
Schema::create('taggables', function (Blueprint $table) {
$table->unsignedInteger('tag_id');
$table->unsignedInteger('taggable_id');
$table->string('taggable_type');
});
}
public function down()
{
Schema::dropIfExists('taggables');
}
}
Update your controller to add new tags, then associate them with product:
public function uploadSubmit(UploadRequest $request)
{
$product = new Product;
$product->name = $request->name;
$product->save();
$photos = collect($request->photos)->map(function($photo) use ($product) {
return [
'product_id' => $product->id,
'filename' => $photo->store('photos')
];
})->toArray();
ProductsPhoto::insert($photos);
$tagsInUse = Tag::whereIn('name', $request->tagname);
if (count($request->tagname) > $tagsInUse->count()) {
$newTags = collect($request->tagname)->diff($tagsInUse->pluck('name')->values())->map(function (string $tag) {
return ['name' => $tag];
});
Tag::insert($newTags->toArray());
$tagIds = Tag::whereIn('name', $request->tagname)->pluck('id')->values();
} else {
$tagIds = $tagsInUse->pluck('id')->values();
}
$product->tags()->attach($tagIds);
return redirect('/upload')->with('msg' , 'Upload successful!');
}
And here's a test for this setup:
public function test()
{
factory(Tag::class)->create(['name' => 'one']);
factory(Tag::class)->create(['name' => 'two']);
factory(Tag::class)->create(['name' => 'three']);
$this->assertEquals(
['one', 'two', 'three'],
Tag::all()->pluck('name')->toArray()
);
$requestTags = new Collection(['one', 'three', 'four', 'five']);
$inUse = Tag::whereIn('name', $requestTags)->pluck('name')->values();
$newTags = collect($requestTags)->diff($inUse)->map(function(string $tag) {
return ['name' => $tag];
});
Tag::insert($newTags->toArray());
$this->assertEquals(
['one', 'two', 'three', 'four', 'five'],
Tag::all()->pluck('name')->toArray()
);
$product = factory(Product::class)->create(['name' => 'Bike']);
$this->assertEmpty($product->tags);
$tagIds = Tag::whereIn('name', $requestTags)->pluck('id')->values();
$product->tags()->attach($tagIds);
$this->assertEquals(
['one', 'three', 'four', 'five'],
$product->fresh('tags')->tags->pluck('name')->toArray()
);
}
Reference: https://laravel.com/docs/5.6/eloquent-relationships#many-to-many-polymorphic-relations

Attach user id to a post (Laravel 5.3)

in my app I want to attach a logged in user id to a post, below is my controller :
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input);
$journal->user_id = Auth::id();
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
I tried the above controller it gave error : SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert intojournal(title,abstract,file,id_edition,journalslug,updated_at,created_at) values (Rancang bangun website Jurnal Online jurusan Teknik Informatika Universitas Palangkaraya, ddd, test3.pdf, 1, rancang-bangun-website-jurnal-online-jurusan-teknik-informatika-universitas-palangkaraya, 2016-11-15 03:43:34, 2016-11-15 03:43:34))
I don't understand what I did wrong, if someone can help that would be great. Thanks.
You're trying to create a Journal without specifying the user_id when it's created.
I'd suggest the following:
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input + ['user_id' => Auth::id()]);
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
Also, don't forget to have user_id set as mass assignable in the Journal class.
The error says you should pass user_id too. You can do this with adding user ID to an $input:
$input = $request->all();
$input['user_id'] = auth()->user()->id;

Resources