My Controller Action Method is like below:
public function store(Request $request)
{
$IsActive = $request->input('IsActive');
echo $IsActive;
die();
}
My View is like below
{!! Form::open(array('method' => 'POST', 'action' => 'DepartmentController#store')) !!}
{!! Form::checkbox('IsActive', 0, null, array('class' => "flat")) !!}
{!! Form::submit('Save', array('class' => "btn btn-success"))!!}
{!! Form::close() !!}
Problem
On Form submit, I always get value = 0 for CheckBox. Am I missing
something ?
You are getting 0 as value on form submit is because, you have explicitly declared value as 0. Replace 0 with whatever value you want, and you will get the result as per your desire.
From the api source code:
/**
* Create a checkbox input field.
*
* #param string $name
* #param mixed $value
* #param bool $checked
* #param array $options
* #return string
*/
public function checkbox($name, $value = 1, $checked = null, $options = array())
{
return $this->checkable('checkbox', $name, $value, $checked, $options);
}
/**
* Create a checkable input field.
*
* #param string $type
* #param string $name
* #param mixed $value
* #param bool $checked
* #param array $options
*
* #return string
*/
protected function checkable($type, $name, $value, $checked, $options)
{
$checked = $this->getCheckedState($type, $name, $value, $checked);
if ($checked) {
$options['checked'] = 'checked';
}
return $this->input($type, $name, $value, $options);
}
Hope this helps you out.
Related
I'm working on a Project where I have a lot of decimal fields in every model and want to put comma all of them.
I can use helper mutators or PHP number_format() while fetching. The problem is I have to do it for every field.
Is there any simple solution for this??
Want to put Comma Form
Create Form Sample:
Index Page/Show Page Sample:
The best way to do this is to use custom casts :
https://laravel.com/docs/8.x/eloquent-mutators#castables
So for example
create a ReadableNumber class :
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class ReadableNumber implements CastsAttributes
{
/**
* Prepare the given value for storage.
*
* #param \Illuminate\Database\Eloquent\Model $model
* #param string $key
* #param array $value
* #param array $attributes
* #return string
*/
public function get($model, $key, $value, $attributes)
{
return number_format($value, 2, ',', ' ');
}
public function set($model, $key, $value, $attributes)
{
return str_replace(" ", "", str_replace(",", ".", $value));
}
}
protected $casts = [
'size' => ReadableNumber::class,
'rate' => ReadableNumber::class,
'value' => ReadableNumber::class,
[...]
];
then in your blade vues :
{{ $appart->value }}
will show : 3 000,00
In my app, users can create personal 'groups'. Each user has a user profile and I show the groups that they've created on their profile like this {{ ucwords(trans($groupCreated->group_title)) }} which works great.
I want their group title to be inside a green box, and to show a grey box if no groups have been created by the user.
Here's the full code for the green box:
#foreach($user->groupsCreated as $groupCreated)<div class="alert alert-success" role="alert"> {{ ucwords(trans($groupCreated->group_title)) }}</div>#endforeach
Here's what I want to show if no groups created:
<!-- <small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
<div class="alert alert-secondary" role="alert">
This user has no active groups</div> -->
Here's my if else statement to make this happen:
#if ($groupCreated())
<small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
#foreach($user->groupsCreated as $groupCreated)
<div class="alert alert-success" role="alert">
{{ ucwords(trans($groupCreated->group_title)) }}
</div>
#endforeach
#else
<!-- Show if no groups created -->
<!-- <small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
<div class="alert alert-secondary" role="alert">
This user has no active groups</div> -->
#endif
The error I get is Undefined variable: groupCreated
Here is my GroupController.php
<?php
namespace App\Http\Controllers;
use App\Group;
use Illuminate\Http\Request;
// All Groups pages require login except 'show'
class GroupsController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => 'show']);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$groups = Group::where('created_by_user_id', auth()->id())->get();
return view('groups/index', compact('groups'));
}
/**
* Store the group that a user has joined in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function join(Request $request)
{
$request->validate([
'group_id' => 'required',
]);
$user_id = auth()->id();
$group = Group::find($request->get('group_id'));
if (!$group->isLoggedInUserJoined())
$group->joinedUsers()->attach($user_id);
$redirect = $request->get('redirect', 'groups/joined');
return redirect($redirect)->with('success', 'You joined the group!!');
}
/**
* Remove the user from a group that they have joined in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function unjoin(Request $request)
{
$request->validate([
'group_id' => 'required',
]);
$group = Group::find($request->get('group_id'));
if ($group->isLoggedInUserJoined())
$group->joinedUsers()->detach(auth()->id());
$redirect = $request->get('redirect', 'groups/joined');
return redirect($redirect)->with('success', 'You\'ve left the group.');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function joined()
{
//#todo change query to show groups joined
// $groups = Group::where('created_by_user_id', auth()->id())->get();
// $groups = Group::with('joinedUsers')
$groups = auth()->user()->groupsJoined()->get();
return view('groups/joined', compact('groups'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('groups.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'group_title' => 'required',
'group_description' => 'required',
'group_date' => 'required',
'group_time' => 'required',
]);
$group = new Group([
'group_title' => $request->get('group_title'),
'group_description' => $request->get('group_description'),
'group_date' => $request->get('group_date'),
'group_time' => $request->get('group_time'),
]);
$group->save();
return redirect('/groups')->with('success', 'Group saved!!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
// $group = Group::find($id);
$group = Group::with('createdByUser')->where('id', $id)->first();
return view('groups.show', compact('group'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$group = Group::find($id);
return view('groups.edit', compact('group'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'group_title' => 'required',
'group_description' => 'required',
'group_date' => 'required',
'group_time' => 'required',
]);
$group = Group::find($id);
$group->group_title = $request->get('group_title');
$group->group_description = $request->get('group_description');
$group->group_date = $request->get('group_date');
$group->group_time = $request->get('group_time');
$group->save();
return redirect('/groups')->with('success', 'Group updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$group = Group::find($id);
$group->delete();
return redirect('/groups')->with('success', 'Group deleted!');
}
}
and the Group Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $fillable = [
'group_title',
'group_description',
'group_date',
'group_time',
'created_by_user_id'
];
public static function boot()
{
parent::boot();
static::creating(function ($group) {
$group->created_by_user_id = auth()->id();
});
}
/**
* Get the user that created the group.
*/
public function createdByUser()
{
return $this->belongsTo(User::class, 'created_by_user_id');
}
/**
* Get the users that joined the group.
*/
public function joinedUsers()
{
return $this->belongsToMany(User::class, 'group_joined_user', 'group_id', 'user_id')
->withTimestamps();
}
/**
* Checks whether the currently logged in user is joined to the group.
*/
public function isLoggedInUserJoined()
{
return $this->joinedUsers()->where('users.id', auth()->id())->exists();
}
}
So, I added the following to Model
/**
* Fetch the groups created by user
*/
public function groupCreated()
{
return $this->groupCreated()->where('groups.show', auth()->id());
}
But the error is:
Undefined variable: groupCreated
Any help?
The problem is probably #if ($groupCreated()). What is this line supposed to do?
If you just want to check if the user has any groups you can use #if ($user->groupsCreated->count() > 0).
I am currently building a timetable generation system, I have these models below which are Subject and Teacher as the two main models with their nova resources, I have created a pivot model SubjectAllocation (has a nova resource) with a pivot table subject_allocations with fields teacher_id and subject_id. I would like to be able to use SubjectAllocation nova resource to select a teacher and allocate multiple subjects to this teacher but currently, I have no lack of it. Tried pulling in this package dillingham/nova-attach-many to attach to the SubjectAllocation model and this package to pick teachers records sloveniangooner/searchable-select but it cannot store data in the pivot table.
Subject Allocation Resource
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Http\Requests\NovaRequest;
use NovaAttachMany\AttachMany;
use Sloveniangooner\SearchableSelect\SearchableSelect;
class SubjectAllocation extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\SubjectAllocation';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),
AttachMany::make('Subjects')
->showCounts()
->help('<b>Tip: </b> Select subjects to be allocated to the teacher'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
Fields Methods in Subject Resource
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Subject Name', 'name')
->withMeta(['extraAttributes' => ['placeholder' => 'Subject Name']])
->sortable()
->creationRules('required', 'max:255', 'unique:subjects,name')
->updateRules('required', 'max:255'),
Text::make('Subject Code', 'code')
->withMeta(['extraAttributes' => ['placeholder' => 'Subject Code']])
->sortable()
->creationRules('required', 'max:255', 'unique:subjects,code')
->updateRules('required', 'max:255')
,
Textarea::make('Description')
->nullable(),
BelongsToMany::make('Teachers'),
];
}
Fields method in Teacher Resource
public function fields(Request $request)
{
return [
ID::make()->sortable(),
BelongsTo::make('User')
->searchable(),
Text::make('First Name', 'first_name')
->withMeta(['extraAttributes' => ['placeholder' => 'First Name']])
->sortable()
->rules('required', 'max:50'),
Text::make('Middle Name', 'middle_name')
->withMeta(['extraAttributes' => ['placeholder' => 'Middle Name']])
->sortable()
->nullable()
->rules('max:50'),
Text::make('Last Name', 'last_name')
->withMeta(['extraAttributes' => ['placeholder' => 'Last Name']])
->sortable()
->rules('required', 'max:50'),
Text::make('Teacher Code', 'teacher_code')
->withMeta(['exraAttributes' => [ 'placeholder' => 'Teacher Code']])
->sortable()
->creationRules('required', 'max:50', 'unique:teachers,teacher_code')
->updateRules('required', 'max:50'),
BelongsToMany::make('Subjects'),
];
}
Any suggestion on how I can make it work or a better solution, would appreciate very much
Without build custom tool, use following method:
// app\Nova\SubjectAllocation.php
public function fields(Request $request)
{
return [
ID::make()->sortable(),
// SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),
SearchableSelect::make('Teacher', 'teacher_id')->resource(\App\Nova\Teacher::class)
->displayUsingLabels(),
AttachMany::make('Subjects','subject_id')
->showCounts()
->help('<b>Tip: </b> Select subjects to be allocated to the teacher')
->fillUsing(function($request, $model, $attribute, $requestAttribute) {
$a = json_decode($request->subject_id, true);
$teacher = \App\Teacher::find($request->teacher_id);
if(count($a)==0){
// Error processing because no subject is choosen
}else if(count($a)==1){
$model['subject_id'] = $a[0];
}else{
$model['subject_id'] = $a[0];
array_shift ($a); // Remove $a[0] in $a
$teacher->subjects()->sync(
$a
);
}
})
];
}
Hello dear i have an problem when user need too delete or edit post , laravel show error " you can't edit post ... " i use a model and controller in laravel and user "auth" system id for access post for delete or edit now see my work :
Index View
#extends('layouts.app')
#section('content')
#auth
<h6 class="alert alert-dark">Dear Guest {{ Auth::user()->name }} for send a post <a class="btn btn-success" href="{{ route('ads.create') }}">Click</a> Here</h6>
#endauth
#guest
<div class="alert alert-primary">for send a post you can <a class="btn btn-success" href="{{ route('register') }}">Register</a></div>
#endguest
#if(count($adses) > 0)
<div class="row">
#foreach($adses as $ads)
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="card mb-4">
<img class="card-img-top img-fluid" src="/storage/cover_images/{{$ads->cover_image}}" alt="Card image cap">
<div class="card-body">
<h6 class="card-title">{{ $ads->title }}</h6>
#if(!Auth::guest())
#if(Auth::user()->id == $ads->user_id)
<div class="row">
{!!Form::open(['action' => ['AdsController#destroy', $ads->id], 'method' => 'POST',]) !!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close() !!}
Edit
</div>
#endif
#endif
</div>
</div>
</div>
#endforeach
{{ $adses->links() }}
#else
<p class="alert alert-warning" role="alert">any post !</p>
</div>
#endif
#endsection
Ads Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ads extends Model
{
protected $table = 'ads';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function adses(){
return $this->hasMany('App\Ads');
}
}
Ads Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Ads;
class AdsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$adses = Ads::orderBy('created_at', 'desc')->paginate(16);
return view('ads.index')->with('adses', $adses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('ads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'image|nullable|max:1999',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$ads = new Ads();
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
$ads->user_id = auth()->user()->id;
$ads->cover_image = $fileNameToStore;
$ads->save();
return redirect('/home')->with('success', 'آگهی شما با موفقیت درج شد .');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$ads = Ads::find($id);
return view('ads.show')->with('ads', $ads);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant edit other user's post');
}
return view('ads.edit')->with('ads', $ads);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'required',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$ads = Ads::find($id);
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
if($request->hasFile('cover_image')){
$ads->cover_image = $fileNameToStore;}
$ads->save();
return redirect('/')->with('success', 'your post is update');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant delete other user's post');
}
if($ads->cover_image != 'noimage.jpg'){
// Delete Image
Storage::delete('public/cover_images/'.$ads->cover_image);
}
$ads->delete();
return redirect('/')->with('success', 'Post Removed');
}
}
Routs
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('/', 'AdsController');
Route::resource('ads', 'AdsController');
now , after send a post and login in system user cant delete or edit her post .
Thank you
auth()->user()->id !== $ads->user_id .
Уou have this line. And if user not login when he creating post, you are will be have user_id == null. Check in DB than user_id?
I solved my problem
if(auth()->user()->id !== $ads->user_id)
Since you're using !==, make sure your user_id is integer
When generating a selectRange in Laravel, is it possible to append or pre-append text to the select options label? Like a % sign for instance, so all the labels will read {number}%.
{!! Form::selectRange('number', 1, 99) !!}
There is no such thing in Laravel Collective core. I have created my own utility class which extends from Laravel Collective form builder.
In your blade, you can simply write:
{!! MyCustomForm::selectRange('number', 1, 99, ' %') !!}
This is my custom class which extends from Laravel Collectives Form builder:
<?php
namespace App\Models\Utilities;
use Collective\Html\FormFacade;
class MyCustomForm extends FormFacade
{
/**
* Create a select range field with appending text.
* This function overrides Laravel Collective Form::selectRange()
* function.
*
* #param string $name
* #param string $begin
* #param string $end
* #param string $appended_text
* #param string $selected
* #param array $options
* #return string
*/
public static function selectRange($name, $begin, $end, $appended_text = null, $selected = null, $options = array()){
$html = parent::selectRange($name, $begin, $end, $selected, $options);
$dom = new \DOMDocument();
$dom->loadHTML($html);
$xpath = new \DOMXPath($dom);
$options = $xpath->query("*/select[#name='" . $name . "']/option");
foreach ($options as $option) {
$option->nodeValue = $option->nodeValue . $appended_text;
}
$html = self::innerHTML($dom->documentElement->firstChild);
return $html;
}
/**
* This function removes HTML DOCTYPE, html tag and body tag from the
* generated DOM HTML.
*
* #param DOMNode $node
* #return string
*/
public static function innerHTML($node){
$doc = new \DOMDocument();
foreach ($node->childNodes as $child)
$doc->appendChild($doc->importNode($child, true));
return $doc->saveHTML();
}
}
Let me know if there is still something vague.