Show an attribute from other model in blade (Laravel) - laravel

I´ve got this exception in my blade template. I made a relation between my two models (RegisteredCourses y User) and I can see it works in the rest of Blade´s template, except form.blade.php
Trying to get property 'user' of non-object (View: C:\laragon\www\hr-english\resources\views\registeredCourse\form.blade.php) (View: C:\laragon\www\hr-english\resources\views\registeredCourse\form.blade.php)
My idea is to show in my blade template the name of the user, but I need in the value of input the correspondant user_id.
I don´t what is the correct approach to this problem.
<div class="form-group {{ $errors->has('course_id') ? 'has-error' : '' }}">
<label for="course_id" class="col-md-2 control-label">Course</label>
<div class="col-md-10">
<select class="form-control" id="course_id" name="course_id">
<option value="" style="display: none;" {{ old('course_id', optional($registeredCourse)->course_id ?: '') == '' ? 'selected' : '' }} disabled selected>Select course</option>
#foreach ($courses as $key => $course)
<option value="{{ $key }}" {{ old('course_id', optional($registeredCourse)->course_id) == $key ? 'selected' : '' }}>
{{ $course }}
</option>
#endforeach
</select>
{!! $errors->first('course_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('user_id') ? 'has-error' : '' }}">
<label for="status_course" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input class="form-control" name="user_id" type="text" id="user_id" value="{{ old('user_id', optional($registeredCourse->user->name)) }}" minlength="1" placeholder="Enter name here..."> <!--Problwm here-->
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('status_course') ? 'has-error' : '' }}">
<label for="status_course" class="col-md-2 control-label">Status Course</label>
<div class="col-md-10">
<input class="form-control" name="status_course" type="text" id="status_course" value="{{ old('status_course', optional($registeredCourse)->status_course) }}" minlength="1" placeholder="Enter status course here...">
{!! $errors->first('status_course', '<p class="help-block">:message</p>') !!}
</div>
</div>

Use the null coalescing operator: $registeredCourse->user->name ?? null instead of optional($registeredCourse->user->name) in your blade
UPS: Here's a demo showing how this works depending on whether $registeredCourse->user is set or not.

Related

Form Switch from Eloquent

I'm using a Creative Tim template for my first Laravel project: Argon Pro 2 for Laravel, I can't get the form-switch field formatting to work for me using eloquent for my Crud. No problem with HTML. Any ideas?
With HTML (Blade):
<div class="form-check form-switch">
<input id="repetition" name="repetition" class="form-check-input" type="checkbox" id="CheckRepetition" value="{{ old('repetition') }}">
<label class="form-check-label" for="CheckRepetition">Activa para Repetición</label>
</div>
With Eloquent:
<div class="col-3 mb-3">
{{ Form::label('Tarea Repetitiva Checkbox *') }}
{{ Form::checkbox('repetition', $task->repetition, ['class' => 'form-switch ' .($errors->has('repetition') ? ' is-invalid' : '')]) }}
{!! $errors->first('repetition', '<div class="invalid-feedback">:message</div>') !!}
</div>
Thanks in advance ;)
Solved!
My code:
<div class="form-group">
<div class="col-2 mb-3">
{{ Form::label('Tarea Repetitiva') }}
{{ Form::hidden('repetition', '0') }}
<div class="form-check form-switch">
{{ Form::checkbox('repetition', '1', $task->repetition, ['class' => 'form-check-input' . ($errors->has('repetition') ? ' is-invalid' : '')]) }}
</div>
{!! $errors->first('repetition', '<div class="invalid-feedback">:message</div>') !!}
</div>
</div>

I get "SQLSTATE[23000]: Integrity constraint violation" when I try to add a command

When I try to get a product and command it I get "Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into commande (name, familyname, quantity, mobile, ville, adresse, id_product, user_id, updated_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, 2022-11-21 21:30:27, 2022-11-21 21:30:27))"
I am trying here to command a product where every product has a different user. I am using a foreign key in products table (user_id) and every command has a user to inspect it.
This is my function in the controller:
public function getProduct($id, Request $request)
{
$product = Product::find($id);
$commande = new AppCommande;
$commande->name = $request->input('name');
$commande->familyname = $request->input('familyname');
$commande->quantity = $request->input('quantity');
$commande->mobile = $request->input('mobile');
$commande->ville = $request->input('ville');
$commande->adresse = $request->input('adresse');
$commande->id_product = $request->input('id_product');
$commande->user_id = $request->input('id_user');
$commande->save();
return view('product', ['product' => $product], ['commande' => $commande]);
}
This is my route :
Route::get('/product/{id}', \[ 'uses' =\> 'CommandeUserController#getProduct', 'as' =\> 'product.single' \]);
and this is the view:
#extends('layouts.app')
#section('content')
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="{{ asset('uploads/product/'.$product->image) }}" width="90px" alt="image">
<div class="caption">
<h3> {{$product->name}} </h3>
<p class="discription"> {{$product->description}} </p>
<div class="clearfix">
<div class="pull-left price"/>$ {{$product->price}}</div>
{{-- Commander ce produit --}}
</div>
</div>
</div>
<div class="card">
<div class="card-header">
Create Commande
</div>
<div class="card-body">
<form action="{{ route("admin.commandes.store") }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" value="{{ old('name', isset($commande) ? $commande->name : '') }}">
#if($errors->has('name'))
<em class="invalid-feedback">
{{ $errors->first('name') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('familyname') ? 'has-error' : '' }}">
<label for="name">Family Name</label>
<input type="text" id="familyname" name="familyname" class="form-control" value="{{ old('familyname', isset($commande) ? $commande->familyname : '') }}">
#if($errors->has('name'))
<em class="invalid-feedback">
{{ $errors->first('name') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('mobile') ? 'has-error' : '' }}">
<label for="quantity">Mobile</label>
<input type="number" id="mobile" name="mobile" class="form-control" value="{{ old('mobile', isset($commande) ? $commande->mobile : '') }}" step="1">
#if($errors->has('mobile'))
<em class="invalid-feedback">
{{ $errors->first('mobile') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.price_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="quantity">Quantity</label>
<input type="number" id="quantity" name="quantity" class="form-control" value="{{ old('quantity', isset($commande) ? $commande->quantity : '') }}" step="1">
#if($errors->has('price'))
<em class="invalid-feedback">
{{ $errors->first('price') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.price_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('ville') ? 'has-error' : '' }}">
<label for="ville">City</label>
<input type="text" id="ville" name="ville" class="form-control" value="{{ old('ville', isset($commande) ? $commande->familyname : '') }}">
#if($errors->has('ville'))
<em class="invalid-feedback">
{{ $errors->first('ville') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('adresse') ? 'has-error' : '' }}">
<label for="adress">Adresse</label>
<input type="text" id="adresse" name="adresse" class="form-control" value="{{ old('adresse', isset($commande) ? $commande->adresse : '') }}">
#if($errors->has('adresse'))
<em class="invalid-feedback">
{{ $errors->first('adresse') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<input type="hidden" name="id_product" value=" {{ $product->id }}" />
<input type="hidden" name="user_id" value=" {{ $product->user_id }}" />
<input class="btn btn-danger" type="submit" value="{{ trans('global.save') }}">
</div>
</form>
</div>
</div>
#endsection
Hello I changed the getProduct() to and it works:
public function getProduct($id, Request $request)
{
$product = Product::find($id);
return view('product', ['product' => $product]);
}
and I used in the form a new store funtion for the command:
public function store(StoreProductRequest $request)
{
$user_id=auth()->user()->id;
$commande = new AppCommande();
$commande->name = $request->input('name');
$commande->familyname = $request->input('familyname');
$commande->quantity = $request->input('quantity');
$commande->mobile = $request->input('mobile');
$commande->ville = $request->input('ville');
$commande->adresse = $request->input('adresse');
$commande->id_product = $request->input('id_product');
$commande->user_id=$user_id;
$commande->save();
return redirect('/commandeuser/confirm')->with('status', 'commande ajoutée!');
}
Since I feel weird that your error message doesn't take any value from your request, try to add your $commande variable to a standard bracket '()' to your last model initiation.
$commande = new AppComande();

how to display pdf in embed tag after click button?

I have a form with a filter and a submit button. I would like to display a pdf in an embed tag on the same page with the filter fields used when generating the pdf with Dompdf. Thanks in advance.
here is the form :
#section('content')
<!-- Your html goes here -->
<div class='panel panel-default'>
<div class='panel-heading'>Customer Statement</div>
<div class='panel-body'>
<form method='get' action="{{ route('getStatement') }}" id="statementForm">
#csrf
<div class="row">
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="start_date"><strong>Start Date</strong></label>
<input type="date" required name="start_date" value="{{ date('Y-m-d') }}"
class="form-control" id="start_date">
</div>
</div>
<div class='col-sm-6 form-group'>
<div class="form-group col-6">
<label for="end_date"><strong>End Date</strong></label>
<input type="date" required name="end_date" value="{{ date('Y-m-d') }}"
class="form-control" id="end_date">
</div>
</div>
</div>
<div class='col-sm-12 form-group'>
<label> Customers :</label>
<select style="font-size: 12px; width:100%" id="customer_id" name="customer_id"
class="select2 mb-2 select2-multiple">
<option value=''> Choose </option>
#if ($customers)
#foreach ($customers as $item)
#php $selected = ''; #endphp
#if (isset($customerdirect) == $item->id)
#php $selected = 'selected'; #endphp
#endif
<option data-name="{{ $item->name }}" value='{{ $item->id }}' {{ $selected }}>
{{ $item->name }} </option>
#endforeach
#endif
</select>
</div>
</div>
<div class='panel-footer'>
<input type='submit' class='btn btn-success' value='Generate'/>
</div>
</form>
</div>
#endsection
the code in controller
public function getStatement(Request $request)
{
$pdf = PDF::loadView('customerslocations::customerstatementpdf');
return $pdf->stream();
}

Syntax form create

I want to remove this syntax for my form
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', null, array('class' => 'form-control')) }}
<br>
{!! $errors->first('name', '<span class="help-block">:message</span>') !!}
</div>
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
{{ Form::label('firstname', 'Student Firstname') }}
{{ Form::textarea('firstname', null, array('class' => 'form-control')) }}
<br>
{!! $errors->first('firstname', '<span class="help-block">:message</span>') !!}
{{ Form::submit('Create Student', array('class' => 'btn btn-success btn-lg btn-block')) }}
{{ Form::close() }}
</div>
And put that syntax:
{{csrf_field()}}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<fieldset class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="form-group-input-1">Name</label>
<input type="text" name="name" id="name" class="form-control" required="required" value="{{ old('name')}}"/>
{!! $errors->first('name', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="form-group-input-1">Firstname</label>
<input type="text" name="firstname" id="firstname" class="form-control" required="required" value="{{ old('firstname')}}"/>
{!! $errors->first('firstname', '<span class="help-block">:message</span>') !!}
</fieldset>
Is it a version problem? I am currently with version 5.4.13.
I have to update my version is that right?
If there is a problem it could be because the Form helper is not included in Laravel anymore since 5.0, as mentioned on this page.
The Form and HTML helpers have been deprecated in Laravel 5.0

How to display selected tags in select option value in laravel?

This is my Post Create View
<div class="col-lg-12">
<form action="{{ route('admin.post.store') }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ old('title') }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ old('body') }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-success btn-block">Publish</button>
</form>
</div>
Tags have many to many relationship.
Here I can select many tags, but in the post edit view I cant see the selected tags that selected by me in the post create view.
I want to show selected tags in select option value and edit theme.
post update methods:
public function edit(Post $post)
{
$tags = Tag::all()->pluck('name', 'id');
$cats = Category::all();
return view('admin.post.edit', compact(['post', 'cats', 'tags']));
}
public function update(Post $post, Request $request)
{
$this->validate($request, [
'title' => 'required|min:3|max:255',
'slug' => 'nullable|string',
'image' => 'sometimes|mimes:jpeg,bmp,png,jpg,gif',
'body' => 'required',
'category' => 'nullable',
'views' => 'nullable',
'tags' => 'nullable',
]);
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->category_id = $request->category;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldfilename = $post->image;
$post->image = $filename;
Storage::delete($oldfilename);
}
$post->save();
$post->tags()->sync($request->tags, false);
Session::flash('update', 'Post Updated Successfully');
return redirect()->route('admin.post.index');
}
post edit view:
<div class="col-lg-12">
<form action="{{ route('admin.post.update',$post->id) }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
{{ method_field('patch') }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ $post->title }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select class="js-example-basic-single form-control" name="tags[]" id="tags" multiple="multiple">
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ $post->body }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option <?php if ($cat->id == $post->category_id) {
echo 'selected';
} ?> value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary btn-block">Edit</button>
</form>
</div>
here:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}</option>
#endforeach
</select>
</div>
how can I pass selected post tags from database and show theme here and edit them.
I am using select2 plugin
In select2 I should pass data in jQuery:
$('.js-example-basic-single').select2().val({{ json_decode($post->tags()->getRelatedIds()) }}).trigger('change');
but it doesnt work :(
and I get this error
Method Illuminate\Database\Query\Builder::getRelatedIds does not exist. (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\post\edit.blade.php
Please help me, Thanks!
You have put the code in wrong place:
Try this:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}" {{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $name }}</option>
#endforeach
</select>
</div>

Resources