I try to show image from product_galleries table with related to products table but I got this error. In my products table have 'id' field and in products galleries have 'products_id' field. I already try to google it but still don't get the answer to solve my problem
Thank you
Here is my home.blade.php
<div class="row">
#php $incrementProduct = 0 #endphp
#forelse ($products as $product)
<div
class="col-6 col-md-4 col-lg-3"
data-aos="fade-up"
data-aos-delay="{{ $incrementProduct+=100 }}" >
<a href="{{ route('detail', $product->slug) }}" class="component-products d-block">
<div class="products-thumbnail">
<div
class="products-image"
style="
#if($product->galleries)
background-image: url('{{ Storage::url($product->galleries->first()->photos) }}')
#else
background-color: #eee"
#endif
>
</div>
</div>
<div class="products-text">{{ $product->name }}</div>
<div class="products-price">{{ $product->price }}</div>
</a>
</div>
#empty
<div class="col-12 text-center py-5" data-aos="fade-up"
data-aos-delay="100">
No Product Found
</div>
#endforelse
</div>
My HomeController.php
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$categories = Category::take(6)->get();
$products = Product::with(['galleries'])->take(8)->get();
return view('pages.home', [
'categories' => $categories,
'products' => $products
]);
}
}
My Product.php Model
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'name', 'users_id', 'categories_id', 'price', 'description', 'slug'
];
protected $hidden = [
];
public function galleries() {
return $this->hasMany(ProductGallery::class, 'products_id', 'id');
}
public function user() {
return $this->hasOne(User::class, 'id', 'users_id');
}
public function category() {
return $this->belongsTo(Category::class, 'categories_id', 'id');
}
}
My ProductGallery.php Model
class ProductGallery extends Model
{
protected $fillable = [
'photos', 'products_id'
];
protected $hidden = [
];
public function product() {
return $this->belongsTo(Product::class, 'products_id', 'id');
}
}
Related
Can someone tell me what to do in this error.
The error is in this line. 'posts' => $author->posts->load('category', 'author')
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->posts->load('category', 'author'),
]);
});
this is my controller
class PostController extends Controller
{
public function index()
{
return view('frontend.posts', [
"title" => "All Posts",
// "posts" => Post::all()
"posts" => Post::latest()->get()
]);
}
public function show(Post $post)
{
return view('frontend.post', [
"title" => "Single Post",
"post" => $post
]);
}
}
this is my models
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $with = ['category', 'author'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(User::class, 'user_id');
}
}
and this is my user models
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
public function post(){
return $this->hasMany(Post::class);
}
}
I have this previous error to "foreach() argument must be of type array|object, null given".
I want to display blog posts from certain users.
This is the code from posts.blade.php.
#foreach ($posts as $post)
<div class="p-t-32">
<h4 class="p-b-15">
<a href="/posts/{{ $post->slug }}"
class="ltext-108 cl2 hov-cl1 trans-04">
{{ $post->title }}
</a>
</h4>
<p class="stext-117 cl6">
{{ $post->excerpt }}
</p>
<div class="flex-w flex-sb-m p-t-18">
<span class="flex-w flex-m stext-111 cl2 p-r-30 m-tb-10">
<span>
<span class="cl4">By</span> <a class="stext-111 cl2 hov-cl1 trans-04" href="/authors/{{ $post->author->username }}">{{ $post->author->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
<a class="stext-111 cl2 hov-cl1 trans-04" href="/categories/{{ $post->category->slug }}">{{ $post->category->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
8 Comments
</span>
</span>
<a href="/posts/{{ $post->slug }}" class="stext-101 cl2 hov-cl1 trans-04 m-tb-10">
Continue Reading
<i class="fa fa-long-arrow-right m-l-9"></i>
</a>
</div>
</div>
#endforeach
The name of the relationship in User is post but in your controller you used posts.
The following should probably work:
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->load('post.category'),
]);
});
//Genre Model//
class Genre extends Model
{
use HasFactory;
protected $table = 'genres';
protected $fillable = [
'name', 'slug', 'status', 'popular',
];
/**
* Get all of the licenses for the user.
*/
public function beat()
{
return $this->hasMany(Beat::class);
}
public function license()
{
return $this->hasManyThrough(license::class, Beat::class);
}
}
//Beat Model//
class Beat extends Model
{
use HasFactory;
protected $table = 'beats';
protected $fillable = [
'genre_id',
'name',
'slug',
'image',
'status',
'new',
'trending',
'meta_title',
'meta_keywords',
];
public function license()
{
return $this->hasMany(License::class,'beat_id', 'id');
}
public function genre()
{
return $this->belongsTo(Genre::class, 'genre_id', 'id');
}
}
//License//
{
use HasFactory;
protected $table = 'licenses';
protected $primaryKey = 'id';
protected $fillable = [
'beat_id',
'license_name',
'beat_name',
'genre',
'bpm',
'key',
'tag_1',
'tag_2',
'time',
'price',
'status',
'popular',
'wav',
'trackout',
'unlimited',
'exclusive',
'image',
'audio',
];
public function beat()
{
return $this->belongsTo(Beat::class, 'id');
}
}
//LicenseController//
public function show($id)
{
$license = License::find($id);
return view('admin.license.show')->with('license', $license,);
}
// Show.blade.php//
#extends('layouts.admin')
#section('content')
<div class="container">
#foreach($licenses->chunk(4) as $license)
<div class="card">
<div class="card-body">
#foreach($licenses as $license)
<div class="">
<img src="{{ asset('assets/uploads/licenses/img/'.$license->image) }}"
alt="image here">
<p>{{ $license->id }}</p>
<p>{{ $license->beat_id }}</p>
<p>{{ $license->beat_name }}</p>
</div>
#endforeach
</div>
</div>`enter code here`
#endforeach
</div>
#endsection
Anytime i try to use #foreach to call {{ $license->beat->id }}, it give me errors like this Error:
Method name must be a string
http://127.0.0.1:8000/licenses/1
Your organization is a bit strange, as I'd expect to see this method called something more like BeatController::showLicenses(). But setting that aside, you should be using route model binding to automate a lot of this stuff. This is what your controller method should look like:
public function show(Beat $beat)
{
return view('admin.license.show')->with('licenses', $beat->licenses);
}
If you define your route with a parameter called beat instead of id, something like this:
Route::get('/admin/license/{beat}', [LicenseController::class, 'show']);
The type hint in the method signature will signal the routing engine to automatically do the database lookup for you. As a bonus, it also handles 404 errors in case in invalid ID is passed.
To get all the licenses related to a single beat, if you have the beat id in the $id variable, you can do the query like this:
License::where('beat_id', $id)->get();
So, your controller function could look like this:
//LicenseController//
public function show($id)
{
$licenses = License::where('beat_id', $id)->get();
return view('admin.license.show')->with('licenses', $licenses);
}
Then in the view you can loop over the licences collection to show each one:
// Show.blade.php//
#extends('layouts.admin')
#section('content')
<div class="container">
#foreach($licenses as $license)
<div class="card">
<div class="card-body">
<div class="">
<img src="{{ asset('assets/uploads/licenses/img/'.$license->image) }}" alt="image here">
<p>License Id: {{ $license->id }}</p>
<p>License Name: {{ $license->license_name }}</p>
<p>License Beat Id: {{ $license->beat_id }}</p>
</div>
</div>
</div>
#endforeach
</div>
#endsection
I am getting this error when I try to submit the selected option using Laravel Livewire.
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'team_id' cannot be null (SQL: insert into projects (user_id, name, description, team_id, updated_at, created_at) values (1, Sammy Mwangangi, qdqwfdweqfc wqdqwfdwqdqwdwq, ?, 2021-06-24 13:39:14, 2021-06-24 13:39:14))
App\Models\Project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'team_id',
];
// protected $guarded = [];
public function tasks(){
return $this->hasMany(Task::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function team(){
return $this->belongsTo(Team::class);
}
}
App\Http\Livewire\Project.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Project;
use App\Models\Team;
use Livewire\WithPagination;
use Illuminate\Support\Str;
use Auth;
class Projects extends Component
{
use WithPagination;
public $name;
public $description;
public $team_id;
public $projectId = null;
public $showModalForm = false;
public function showCreateProjectModal()
{
$this->showModalForm = true;
}
public function updatedShowModalForm()
{
$this->reset();
}
public function storeProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
$project =new Project();
$project->user_id = auth()->user()->id;
$project->name = $this->name;
$project->description = $this->description;
$project->team_id = $this->team_id;
$project->save();
$this->reset();
session()->flash('flash.banner', 'Project created Successfully');
}
public function showEditProjectModal($id)
{
$this->reset();
$this->showModalForm = true;
$this->projectId = $id;
$this->loadEditForm();
}
public function loadEditForm()
{
$project = Project::findOrFail($this->projectId);
$this->name = $project->name;
$this->description = $project->description;
}
public function updateProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
Project::find($this->projectId)->update([
'name' => $this->name,
'description' => $this->description
]);
$this->reset();
session()->flash('flash.banner', 'Project Updated Successfully');
}
public function deleteProject($id)
{
$project = Project::find($id);
$project->delete();
session()->flash('flash.banner', 'Project Deleted Successfully');
}
public function render()
{
return view('livewire.projects', [
'projects' => Project::orderBy('created_at', 'DESC')->paginate(5),
'teams' => Team::all()
]);
}
}
projects.blade.php
<div class="flex flex-wrap mb-6">
<label for="team" class="block text-gray-700 dark:text-white text-sm font-bold mb-2">
{{ __('Team') }}:
</label>
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id" name="team_id">
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
<p class="mt-2 text-sm text-gray-500">
Select the team/department your project is associated with.
</p>
#error('team_id')
<p class="text-red-500 text-xs italic mt-4">
{{ $message }}
</p>
#enderror
</div>
What am I missing? I haven't done much with livewire regarding model relationships and how to bind data between the models.
you must do a default tag option for select, this way on change element this will bind the value to the property
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id">
<option>Select Team</option>
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
also in the validation rules you can add another for the "team_id" value that can't be null on submit
wire:model should be on option tag not on select
What I'm trying to achieve:
User can assign multiple supermarkets to a product, and supermarkets can be assigned to multiple products. When registering a product, I want the user to be able to select from check boxes which are populated from a database.
Product.php
class Product extends Model
{
//
protected $fillable = [
'name',
'summary',
'category_id',
'author_id',
'supermarket_id',
'gf_rank_id',
'average_price',
'photo_id',
'online_store_path',
'ingredients',
];
public function supermarket() {
return $this->belongsToMany('App\Supermarket');
}
}
Supermarket.php
class Supermarket extends Model
{
protected $fillable = [
'name',
'url',
];
public function products() {
return $this->belongsToMany('App\Products');
}
}
ProductsController.php
public function create()
{
$categories = Category::pluck('name', 'id')->all();
$supermarkets = Supermarket::pluck('name', 'id')->all();
return view('admin.products.create', compact(['categories', 'supermarkets']));
}
create.blade.php
#foreach ($supermarkets as $supermarket)
<div class="col-sm-3">
{!! Form::checkbox('supermarket_id[]', $supermarket->id) !!}
{!! Form::label('supermarkets', $supermarket) !!}
</div>
#endforeach
To explain what has been said in the comments:
You are not supplying an object in your $supermarkets data because you are using pluck('name','id'). You are supplying an associative array:
[
1 => 'supermarket A',
2 => 'supermarket B'
]
So you need to change your display code to:
#foreach ($supermarkets as $id => $name)
<div class="col-sm-3">
{!! Form::checkbox('supermarket_id[]', $id) !!}
{!! Form::label('supermarkets', $name) !!}
</div>
#endforeach
hello i have this error : ReflectionException Class App\User does not exist Previous exceptions syntax error, unexpected '{', expecting ')' (0)
but dont understand where is syntax error ,
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','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',
];
protected static function boot()
{
parent::boot();
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
}
public function getRouteKeyName()
{
return 'username';
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
}
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
show.blade.php
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{ $user->profile->getImage() }}" class="rounded-circle">
</div>
<div class="col-8">
<div class="d-flex align-items-baseline">
<div class="h4 mr-3 pt-2">{{ $user->username }}</div>
<button class="btn btn-primary">S'abonner</button>
</div>
<div class="d-flex">
<div class="mr-3">{{ $user->posts->count() }} article(s) en vente
</div>
#can('update', $user->profile)
Modifier Profile
#endcan
<div class="mt-3">
<div class="font-weight-bold">
{{ $user->profile->title }}
</div>
<div class="font-weight-bold">
{{ $user->profile->description }}
</div>
</div>
</div>
</div>
<div class="row mt-5">
#foreach ($user->posts as $post)
<div class="col-4">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
</div>
#endforeach
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $fillable = ['title'];
public function user()
{
return $this->belongsTo('App\User');
}
public function getImage()
{
$imagePath = $this->image ?? 'avatars/default.png';
return "/storage/" . $imagePath;
}
}
i try to create profile with upload image, someone can help me with this error?
Your IDE should give you an error in your overridden boot method, so change this:
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
to this:
static::created(function ($user) {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
Note the missing ) in your $user param.