Property [costo] does not exist on this collection instance - laravel

i need to print the price of a service, but can't find the column with the price.
maybe I'm doing something wrong with relationships, but I can't figure it out on my own
database:
Controller:
public function details(Request $request,$id){
$datax = [
'category_name' => 'apps',
'page_name' => 'calendar',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$evento = Eventos::find($id);
$servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
$event = Eventos::find($id);
$event->asistencia = $request->asistencia;
$event->cancelado = $request->cancelado;
$event->save();
return view("evento",[
"event" => $event,
"servicio" => $servicio
])->with($datax);
}
blade.php
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text"></span>
</div>
</div>
I need to print the "costo" column in relation to service_id
help please

you can use laravel elequent relationship one to one.
if you have this two Servicio.php & Evento.php in App/Models or whatever your models name is, only replace your models in below code do this:
1-
in App/Models/Servicio.php define this relationship:
public function evento()
{
return $this->hasOne(Evento::class);
}
in App/Models/Evento.php define this relationship:
public function servicio()
{
return $this->belongsTo(Servicio::class);
}
now in controller add this:
$evento = Eventos::where('id' , $id)->with('servicio')->first();
in blade use this:
<input type="text" value="{{$evento->servicio->costo}}" >
2- also you can do this but i suggest you the first one:
only in your Codes change this:
$servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();

Related

How to insert record in 2 tables using single form (Laravel)?

CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}

Update Comment in Laravel

I am new at Laravel and I want to use if statement inside Laravel Controller.
So I have a form tag where I can add comments. I want to edit comments in the same form.
Here is my form tag:
<form method="post" action="/hotels/{{$id}}" name="review_hotel">
#csrf
<div class="form-group">
<textarea name="comment" id="comment" class="form-control" style="height:100px"
placeholder="Write your review"></textarea>
#error('comment')
<p class="text-danger">{{$message}}</p>
#enderror
</div>
<input type="submit" value="Submit" class="btn_1" id="submit-review">
</form>
I have a script, with the help of this script I can add a comment that I want to change to the textarea.
After this I have no idea how to update it in my controller.
This is CommentController:
public function comment(CommentRequest $request, $id)
{
$comment = new Comment();
$comment->object_id = $id;
$comment->user_id = Auth::id();
$comment->comment = $request['comment'];
$comment->save();
return redirect('/hotels/'.$id);
}
I think I need to write "if" statement in my controller, but I don't know how.
maybe there is a simpler way to update comment?
On your model Comment.php mark form variables as fillable
public $fillable = ['object_id', 'user_id', 'comment'];
then use this Model function (Eloquent)
Comment::updateOrCreate(
[
'object_id' => ...,
'user_id' => ...,
],
[
'object_id' => ...,
'user_id' => ...,
'comment' => ...,
]
);
https://laravel.com/docs/5.8/eloquent#other-creation-methods

Laravel use sync on a many to many that includes a multiple extra fields

I'm trying to use sync on a many to many that includes a status and a comment. I can sync the applications without status and comment just fine.
NewUserAccount Model
public function applications()
{
return $this->belongsToMany('App\Application', 'new_user_account_applications', 'new_user_id')->withPivot('application_comment', 'status');
}
Application Model
public function newUserAccounts()
{
return $this->belongsToMany('App\NewUserAccount', 'new_user_accounts_applications', 'new_user_id')->withPivot('application_comment', 'status');
}
My NewUserAccountController
public function store(StoreRequest $request)
{
$userAccount = NewUserAccount::create(array_merge(
$request->all(),
['submitted_by' => $requester->id],
['start_date' => Carbon::parse($request->input('start_date'))],
['account_expires' => $request->accountExpires('newAccountExpireDate')],
['company_id' => $requester->company_id],
['username' => $request->manuallyAssignId()]
));
// Here I sync applications and include application comment and status
$userAccount->applications()->sync($request->applications, ['application_comment' => $request->application_comment, 'status' => 0]);
....
}
My pivot showing status and comment correctly
My form. Here is where I'm not sure how to handle the comment and get it to save with each application pivot record.
#foreach($applications as $application)
<label class="k-checkbox">
<input value="{{ $application->id }}" name="applications[]" type="checkbox">{{ $application->application_name }} <span></span>
</label>
<div class="form-group col-lg-4 mb-3">
<label>Comments</label>
<textarea name="application_comment[]" class="form-control" rows="2"></textarea>
</div>
#endforeach
First, you need to set the correct index for the application_comment attribute in your textarea. It's needed to correctly determine the comment for each application.
#foreach($applications as $application)
...
<textarea name="application_comment[{{ $application->id }}]" class="form-control" rows="2"></textarea>
...
#endforeach
Then, you just need to format your data to:
$userAccount->applications()->sync([
application_id_1 => ['application_comment' => 'comment for application_id 1'],
application_id_2 => ['application_comment' => 'comment for application_id 2'],
...
]);
So, here it is
$applications = collect($request->applications)->mapWithKeys(function ($appId) use ($request) {
return [$appId => [
'application_comment' => $request->input('application_comment')[$appId],
'status' => 0,
]];
});
$userAccount->applications()->sync($applications);

Laravel checkbox problem which I cannot update the pivot table

I'm working on a laravel application. In laravel I'm trying to update a row from a pivot table. In this application I have three tables:
issues: id, title, description
categories: id, name
category_issues:(pivot table) id, issue_id, category_id
In laravel I'm trying to update a row from a pivot table. I have this relationships:
Issue.php
public function categories() {
return $this->belongsToMany('App\Category', 'category_issues');
}
Category.php
public function issues() {
return $this->belongsToMany('App\Issue', 'category_issues');
}
A issue can have many categories.
Html code for displaying category section:
<div class="form-group row">
<label for="category" class="col-md-4 col-form-label text-md-right">{{ __('Category :') }}</label>
<div class="form-check col-md-6">
#foreach ($categories as $category)
<input type="checkbox" name="category[]" id="{{ $category->id }}" value="{{ $category->id }}"
{{ in_array($category->id, $issue->categories->pluck('id')->toArray()) ? 'checked' : '' }}>
<label for="{{ $category->id }}"> {{ $category->name }} </label>
#endforeach
</div>
</div>
Here is the update function file:
public function update(Issue $issue)
{
request()->validate([
'title'=> ['required', 'min:3'],
'description'=> ['required', 'min:3'],
'category' => ['required']
]);
$issue->title = request('title');
$issue->description = request('description');
$issue->save();
//Category_Issue Update
$categoryIssue = new CategoryIssue;
$cats = request('category');
foreach ($cats as $cat) {
$categoryIssue->updateOrCreate([
'issue_id'=> $issue->id,
'category_id' => $cat
]);
}
return redirect('issues')->with('success', 'Issue has been updated');
}
Instead of doing the creation / update on the CategoryIssue model (do you even have a CategoryIssue model?), Laravel makes this really easy to update the pivots of a relationship all at once, with the sync() method. You've set up the relationships correctly already per your code above.
In your update() method, you already have your Issue model, and have saved it. You have a set of categories coming in from the form via the $request object (or none if user didn't choose any), so you can then update the pivot like this:
$issue->categories()->sync($request->get('category', []));
Leaving a blank array as the second argument is optional. One small suggestion: maybe make the name of the field on the form 'categories' instead of 'category' just to keep it easy to remember it is an array coming in.

SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value

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();
...
}

Resources