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
Related
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');
}
}
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.
Hi I am trying to insert data into db but it says:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a
default value (SQL: insert into projects (owner_id, updated_at,
created_at) values (1, 2019-06-28 13:17:11, 2019-06-28 13:17:11))
I am following Laracasts Laravel from scratch tutorial
controller:
public function store()
{
$attributes = $this->validateProject();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
//Project::create($attributes);
//Project::create(request(['title', 'description']));
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
model:
protected $guarded = [];
table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('owner_id');
$table->string('title');
$table->text('description');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});
blade file:
<form method="POST" action="/projects">
#csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title" value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
<div class="field">
<label class="label" for="title">Description</label>
<div class="control">
<textarea name="description" class="textarea {{ $errors->has('description') ? 'is-danger' : ''}}" placeholder="Project description">{{ old('description') }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
#include('errors')
</form>
how to solve this issue
You have the field title on the projects table however you are not assigning it a value. As it is set as Not Nullable this will give this error.
You will need all attributes to be in the $fillable attribute on the model when using Project::create($attributes); which you do not seem to have.
An example of the $fillable would be :
protected $fillable = [
'title',
'description',
'owner_id',
];
There are several other potential causes however it is impossible to tell without you including your full Project model and the view which this request is from.
Edit
You will need to change your function to this :
public function store(ProjectRequest $request)
{
$attributes = $request->all();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
You can create the ProjectRequest class by running php artisan make:request ProjectRequest and then putting your validation rules in there instead.
Read more here.
Add your column name in fillable like this in your model (I guess your model name is Project.php)
So your model class should like this.
<?php
mnamespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $guarded = [];
protected $fillable = [
'title', 'owner_id','description'
];
public function owner()
{
return $this->belongsTo(User::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
public function addTask($task)
{
$this->tasks()->create($task);
}
}
And then update your controller store method like this.
public function store(Request $request)
{
$attributes = $this->validateProject();
$attributes->owner_id = auth()->id();
$attributes->title = $this->request->title;
$attributes->description= $this->request->description;
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
The error itself is self explanatory, check this code:
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
here you are creating a new record in project table, and for that you are taking only one column i.e. owner_id, but in the table there is a column title which do not have a default value.
So either take all the column while creating a new record or provide those column a default value (null or something else).
To set null as default value in migration:
$table->string('title')->nullable();
or you can directly change the column in database and set its default value as null, see the below screenshot:
Unable to trace the problem you are facing. Give this code a try and please comment if you got any problem.
Inside your route file
Route::post('project', 'ProjectController#store')->name('project.store');
In your create view
<form method="POST" action="{{route('project.store')}}">
#csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title"
value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
...
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
#include('errors')
</form>
In your ProjectController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class UserController extends Controller{
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
]);
$post = Post::create([
'title' => $request->title,
'owner_id' => auth()->id()
]);
return redirect('/projects');
}
EDIT 1
In your previous code inside ProjectsController, instead of using $attributes try using
public function store()
{
$project = Project::create([
'title' => request('title'),
'owner_id' => request('owner_id')
]);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
EDIT 2
Instead of using create method, try this one
public function store()
{
$project = new Project();
$project->title = request('title');
$project->owner_id = request('owner_id');
$project->save();
...
}
I want to get the title, description, and price which are stored in a pivot table between users and services called userservices. I want to be able to display this information I'll get from the userservices table, inside the user profile view page.
I have 4 tables for that which include,
A User table with id, name, surname, email, phone, area_id.
A Service table with id, name, description, and category_id.
A category table with id, name, description
and I have pivot table btw users and services called service_user which stores the service_id, user_id, title, description and price
I wish to know how can I get the title, description and price for a service that belongs to a particular user, provided the information exists in the userservice table in the database using Laravel.
In my user Controller, I did something like this
public function jobberDetails($id) {
$profiledetail = User::with('area.town.region.country')
->with('userservice')
->find($id);
DB::update("UPDATE users SET visit = visit + 1 WHERE id = '$id'");
// dd($jobdetail);
return view('Users.profileDetail', compact('profiledetail'));
}
in my web file
// Route qui permet d'afficher,le profil d'un Jobbeur
Route::get('/jobber/profiledetails/{id}', 'UserController#jobberDetails')->where(array('id' => '[0-9]+'))->name('profileDetails');
In my model I did something like this
public function area(): BelongsTo
{
return $this->belongsTo(Area::class);
}
public function getTownAttribute(): Town
{
return $this->area->town;
}
public function getRegionAttribute(): Region
{
return $this->area->town->region;
}
public function getCountryAttribute(): Country
{
return $this->area->town->region->country;
}
public function userservice(): BelongsTo
{
return $this->belongsTo(UserServices::class);
}
and in my profile detail blade I did this
<div class="row">
<div class="col-lg-8">
<div class="job-single-head3">
<div class="job-single-info3">
<h3>{{ $profiledetail->name }} {{ $profiledetail->surname }}</h3>
<span><i class="la la-map-marker"></i>{{ $profiledetail->town->name}}, {{ $profiledetail->region->name}}</span>
<span class="job-is ft" id="more" onclick="$('.details').slideToggle(function(){$('#more').html($('.details').is(':visible')?'Cacher le numero':'Voir le numero');});">Voir le numero</span>
</div>
</div><!-- Job Head -->
</div>
</div>
</div>
<div class="job-wide-devider">
<div class="row">
<div class="col-lg-8 column">
<div class="extra-job-info details" style="display:none">
<p style="text-align: center; padding: 10px; font-size: 45px;"><i class="la la-phone"></i> {{ $profiledetail->phone }}</p>
</div>
<div class="job-details">
<h3>Description</h3>
<p> {{ $profiledetail->userservices->description }}.</p>
<h3>Conditions et tarifs</h3>
<ul>
<li>{{ $profiledetail->userservices->price }}</li>
</ul>
<h3>Title</h3>
<ul>
<li>{{ $profiledetail->userservices->title }}</li>
</ul>
</div>
Here's how you can do it using pivot as suggested by #DigitalDrifter
Start by adding services relationship method to the User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class User extends Authenticatable
{
use Notifiable;
//...
public function services(): BelongsToMany
{
return $this->belongsToMany(Service::class)->withPivot('title', 'description', 'price');
}
}
Add reverse relationship to the User from within Services model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Service extends Model
{
protected $fillable = ['category_id', 'name', 'description'];
public function country(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
Now you can use it like so
$profileDetail = User::with(['area.town.region.country', 'services'])->find($id);
foreach($profileDetail->services as $service) {
{{ $service->pivot->title }}
{{ $service->pivot->description }}
{{ $service->pivot->price }}
{{ $service->category->name }}
}
Here's the test (containing all previous code example as well)
<?php
namespace Tests\Unit;
use App\Area;
use App\Town;
use App\User;
use App\Region;
use App\Service;
use App\Country;
use App\Category;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase;
/**
* #test
*/
public function pulls_area_town_region_and_country()
{
$country = Country::create([
'name' => 'United Kingdom',
'description' => 'United Kingdom'
]);
$region = Region::create([
'country_id' => $country->id,
'name' => 'Somerset',
'description' => 'Somerset'
]);
$town = Town::create([
'region_id' => $region->id,
'name' => 'Bristol',
'description' => 'Bristol'
]);
$area = Area::create([
'town_id' => $town->id,
'name' => 'South',
'description' => 'South'
]);
$category = Category::create([
'name' => 'Animals',
'description' => 'Animals'
]);
$service = Service::create([
'category_id' => $category->id,
'name' => 'Service',
'description' => 'Service'
]);
$user = factory(User::class)->create([
'area_id' => $area->id
]);
$user->services()->attach($service->id, [
'title' => 'Attached service',
'description' => 'Attached service description',
'price' => 12575
]);
$user = User::with('area.town.region.country')->first();
$recentJobbers = User::with(['area.town.region.country', 'services.category'])
->limit(5)
->whereType('jobber')
->orderBy('updated_at', 'desc')
->get();
$this->assertEquals('United Kingdom', $user->area->town->region->country->name);
$this->assertEquals('Somerset', $user->area->town->region->name);
$this->assertEquals('Bristol', $user->area->town->name);
$this->assertEquals('South', $user->area->name);
$this->assertEquals('United Kingdom', $user->country->name);
$this->assertEquals('Somerset', $user->region->name);
$this->assertEquals('Bristol', $user->town->name);
$this->assertEquals('South', $user->area->name);
$this->assertEquals('Attached service', $user->services->get(0)->pivot->title);
$this->assertEquals('Attached service description', $user->services->get(0)->pivot->description);
$this->assertEquals(12575, $user->services->get(0)->pivot->price);
$this->assertEquals('Animals', $user->services->get(0)->category->name);
}
}