How to fix a strange behaviour with laravel livewire and pagination? - laravel

I started with Laravel 8 and livewire a few days ago. I still have a lot to discover but I am on my way.
Lastly, I encountered a behaviour I have trouble understanding.
My goal
I want to create a page to CRUD posts. What I want is to have a post list that is paginated displayed at the bottom of the page, a button to create a new post and the possibility to click a button on each post line to edit the post.
I also want the editor of the post displayed at the top of the page while the list is hidden (but this last possibility is not absolutely necessary).
I could manage to have this working as long as the post list is not paginated but not with pagination.
To do this I use a liveewire component whose code is herebelow:
Component's code in app/Http/livewire/posts/Posts.php
<?php
namespace App\Http\Livewire\Posts;
use App\Models\Post;
use Livewire\Component;
class Posts extends Component
{
public $posts;
public $links;
public $post_id,$title, $abstract, $body,$category,$diaporama_dir,
$beg_date,$end_date,$close_date,$receive_registration,
$sticky,$user_id,$inscription_directive;
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function render()
{
$this->mode='list';
$this->posts=Post::select('id','title')->orderBy('created_at','DESC')->paginate(15)->toArray();
$this->links=$this->posts['links'];
//dd($this->links);
$this->user_id=auth()->user()->id;
return view('livewire.posts.posts');
}
public function donothing(){
}
/*
* The attributes that are mass assignable.
*
* #var array
*/
public function resetInputFields(){
$this->title = '';
$this->body = '';
$this->title='';
$this->abstract='';
$this->body='';
$this->category='';
$this->diaporama_dir='';
$this->beg_date='';
$this->end_date='';
$this->close_date='';
$this->receive_registration='';
$this->sticky='';
$this->inscription_directive='';
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function store()
{
$validatedData = $this->validate([
'title' => 'required',
'body' => 'required',
'abstract'=>'required',
'category'=>'',
'diaporama_dir'=>'',
'beg_date'=>'sometimes',
'end_date'=>'sometimes',
'close_date'=>'sometimes',
'receive_registration'=>'',
'sticky'=>'',
'user_id'=>'required',
'inscription_directive'=>''
]);
Post::create($validatedData);
session()->flash('message', 'Bravo ! Votre article a été enregistré.');
// $this->resetInputFields(); //user may want to keep the input stable
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function edit($id)
{
$post = Post::findOrFail($id);
$this->post_id = $id;
$this->title = $post->title;
$this->abstract=$post->abstract;
$this->body=$post->body;
$this->category=$post->category;
$this->diaporama_dir=$post->diaporama_dir;
$this->beg_date=$post->beg_date;
$this->end_date=$post->end_date;
$this->close_date=$post->close_date;
$this->receive_registration=$post->receive_registration;
$this->sticky=$post->sticky;
$this->inscription_directive=$post->inscription_directive;
$this->dispatchBrowserEvent('notify','je passe en mode edit');//to switch browser page to edit mode
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function update()
{
$validatedData = $this->validate([
'title' => 'required',
'body' => 'required',
'abstract'=>'required',
'category'=>'',
'diaporama_dir'=>'',
'beg_date'=>'sometimes',
'end_date'=>'sometimes',
'close_date'=>'sometimes',
'receive_registration'=>'',
'sticky'=>'',
'user_id'=>'required',
'inscription_directive'=>''
]);
$post = Post::find($this->post_id);
$post->update([
'title' => $this->title,
'body'=> $this->body,
'abstract'=> $this->abstract,
'category'=> $this->category,
'diaporama_dir'=>$this->diaporama_dir,
'beg_date'=>$this->beg_date,
'end_date'=>$this->end_date,
'close_date'=>$this->close_date,
'receive_registration'=>$this->receive_registration,
'sticky'=>$this->sticky,
'user_id'=>$this->user_id,
'inscription_directive'=>$this->inscription_directive
]);
session()->flash('message', "Bravo ! L'article a été mis à jour.");
// $this->resetInputFields();//user may like to keep the input fields stable
}
}
and views are these:
View 1 : the main page in resources/views/livewire/posts/posts.blade.php
<div class="container m-auto w-10/12">
<div x-data="{ mode: 'list' }">
#if (session()->has('message'))
<div class="bg-green-200 p-4 w-full my-8 text-xl text-orange-500">
{{ session('message') }}
</div>
#endif
<div x-on:notify.window="mode = 'update'">
<div x-show="mode==='update'">
#include('livewire.posts.update')
</div>
<div x-show="mode === 'edit'">
#include('livewire.posts.create')
</div>
</div>
{{-- <div x-show="mode === 'list'" class="">--}}
<div>
<div>
<button x-on:click="mode = 'edit'" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Nouvel
article</button>
</div>
<table class=" bg-green-400 w-full table table-bordered mt-5 ">
<thead>
<tr class="bg-red-50 mb-2">
<th>Id.</th>
<th>Titre</th>
<th width="150px">Action</th>
</tr>
</thead>
<tbody>
#for ($i = 0; $i < $posts['per_page']; $i++)
<tr class="bg-red-400 mb-2 p-2 space-y-2 border-8 border-red-50 ">
<td>{{ $posts['data'][$i]['id'] }}</td>
<td>{{ $posts['data'][$i]['title'] }}</td>
<td>{{--les actions--}}
<button wire:click="edit({{ $posts['data'][$i]['id'] }})"
class="btn btn-primary btn-sm">Edit</button>
{{-- <button wire:click="delete({{ $post->id }})"
class="btn btn-danger btn-sm">Delete</button>--}}
</td>
</tr>
#endfor
</tbody>
</table>
<div class="flex flex-row mt-2">
#for ($i = 0; $i < count($links); $i++)
<div class="flex p-2 mr-2 border w-max-content">
{{$links[$i]['label']}}
</div>
#endfor
</div>
</div>
</div>
2- create include in resources/views/livewire/posts/create.blade.php
<div class="container bg-green-500 p-4">
<form>
This is the create form
<input type="hidden" name="user_id" wire:model="user_id" >
<div class="flex flex-col md:flex-row" >
<div class=" mt-2 flex flex-col w-max-content">
<label for="category">Catégorie:</label>
<select class="" name="category" id="category" wire:model="category">
<option value="Sans">Sans</option>
<option value="Annoncement">Annonce d'un événement</option>
</select>
#error('category') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class=" mt-2 flex flex-col flex-auto ml-4">
<label for="title">Title:</label>
<input type="text" class="form-control" name="title" id="title" placeholder="Saisissez un titre"
wire:model="title" value="">
#error('title') <span class="text-danger">{{ $message }}</span>#enderror
</div>
</div>
<div class="flex flex-col md:flex-row" >
<div class=" mt-2 flex flex-col w-max-cbeg_date ">
<label for="beg_date">Date de début</label>
<input type="text" class="" name="beg_date" id="beg_date" wire:model="beg_date">
#error('beg_date') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class=" mt-2 flex flex-col w-max-cbeg_date ml-4">
<label for="end_date">Datend_date</label>
<input type="text" class="" name="end_date" id="end_date" wire:model="end_date">
#error('end_date') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class=" mt-2 flex flex-col w-max-cbeg_date ml-4">
<label for="close_dclose">Date limite</label>
<input type="text" class="" name="close_date" id="close_date" wire:model="close_date">
#error('close_date') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class=" mt-2 flex flex-col w-max-content ml-4">
<label for="receive_registration">Accepte les inscriptions:</label>
<select class="" name="receive_registration" id="receive_registration" wire:model="receive_registration">
<option value="no">Non</option>
<option value="yes">Oui</option>
</select>
#error('receive_registration') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class=" mt-2 flex flex-col flex-auto ml-4">
<label for="title">Dossier du diaporama</label>
<input type="text" class="form-control" name="diaporama_dir" id="diaporama_dir" placeholder="ex: admin/1"
wire:model="diaporama_dir">
#error('diaporama_dir') <span class="text-danger">{{ $message }}</span>#enderror
</div>
</div>
<div class="mt-2 flex flex-col">
<label for="abstract">Résumé</label>
<textarea class="form-control" name="abstract" id="abstract" wire:model="abstract"
placeholder="Saisissez votre article"></textarea>
#error('abstract') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class="mt-2 flex flex-col">
<label for="body">Corps de l'article</label>
<textarea class="form-control" name="body" id="body" wire:model="body" rows=30
placeholder="Saisissez votre article"></textarea>
#error('body') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<button wire:click.prevent="store()" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Enregistrer</button>
<button wire:click.prevent="resetInputFields()" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Effacer tout</button>
<button #click.prevent="mode = 'list'" class="bg-red-400 px-2 py-1 border rounded-lg mt-2 ml-16">Retour à la liste</button>
</form>
update include
The update include is exactly the same as the create include except an additional hidden field for the post id.
What is happening?
At startup, I mean when I visit the localhost:8000/posts page, the page 1 is correctly displayed and the links at the bottom of the page are like localhost:8000/posts?page=3 whichever the number of the page may be.
From this page I can normally go to another page using the bottom links, and this several times.
The troube arises when I click a link to edit a post. The post is correctly sent back by the server but instantly we are switched to page 1 of the paginated posts and the bottom links take a strange form such as localhost:8000/livewire/message/posts.posts?page=3 wichever the page number may be.
The trouble arises also when, after having displayed the create form, I type a first char in the fields. In fact it seems that it arises each time a sync is required.
How can I fix this?

replace
<div class="flex flex-row mt-2">
#for ($i = 0; $i < count($links); $i++)
<div class="flex p-2 mr-2 border w-max-content">
{{$links[$i]['label']}}
</div>
#endfor
</div>
with
<div class="flex flex-row mt-2">
{{ $posts->links() }}
</div>
and in component
use WithPagination;
ref link https://laravel-livewire.com/docs/2.x/pagination

Related

How to speed up requests in livewire?

I’ve made a very simple profile card with two views once is showing me the profile id,name and email and the second view just show the input fields for this three attributes.
This is working but it is “very” slow. When i’m hitting the button Edit on the show view, it takes more than 650ms(in best scenario, sometimes it takes more than 1.2sec) to load the edit view and vice versa.
How can I make this a little bit faster ?
Profile Component:
namespace App\Http\Livewire\User;
use App\User;
use Illuminate\Validation\Rule;
use Livewire\Component;
class Profile extends Component
{
public $user, $user_id, $name, $email;
public $updateMode = false;
public function mount(User $user)
{
$this->user = $user;
$this->user_id = $user->id;
$this->name = $user->name;
$this->email = $user->email;
}
public function render()
{
return view('livewire.user.profile.resource');
}
public function edit()
{
$this->updateMode = true;
}
public function cancel()
{
$this->updateMode = false;
}
public function submit()
{
$attributes = $this->validate([
'name' => 'required|min:6',
'email' => ['required', 'email', Rule::unique('users')->ignore($this->user->id)],
]);
$this->user->update($attributes);
$this->updateMode = false;
}
}
And this are the views:
resource.blade.php:
<div class="p-3">
#includeWhen(!$updateMode,'livewire.user.profile.show')
#includeWhen($updateMode,'livewire.user.profile.edit')
</div>
show.blade.php:
<div>
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Id:</span>
</div>
<div class="w-3/4" >
<span class="text-gray-700 font-semibold">{{ $user_id }}</span>
</div>
</div>
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Name:</span>
</div>
<div class="w-3/4" >
<span class="text-gray-700 font-semibold">{{ $name }}</span>
</div>
</div>
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Email:</span>
</div>
<div class="w-3/4" >
<span class="text-gray-700 font-semibold">{{ $email }}</span>
</div>
</div>
<!-- Editing Buttons -->
<div class="pt-3">
<button type="button" wire:click.prevent="edit" class="py-1 px-2 rounded bg-blue-500 text-white font-semibold">Edit</button>
</div>
</div>
edit.blade.php:
<form wire:submit.prevent="submit">
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Id:</span>
</div>
<div class="w-3/4" >
<span class="text-gray-700 font-semibold">{{ $user_id }}</span>
</div>
</div>
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Name:</span>
</div>
<div class="w-3/4" >
<input type="text" class="w-1/2 border appearance-none py-1 px-2 rounded shadow focus:outline-none" wire:model="name">
</div>
</div>
<div class="flex items-center py-2">
<div class="w-1/4">
<span class="text-gray-800">Email:</span>
</div>
<div class="w-3/4" >
<input type="text" class="w-1/2 border appearance-none py-1 px-2 rounded shadow focus:outline-none" wire:model="email">
</div>
</div>
<!-- Editing Buttons -->
<div class="pt-3">
<button type="submit" class="py-1 px-2 rounded bg-blue-500 text-white font-semibold" >Save</button>
Cancel
</div>
</form>
I ran into the same issue, with the same implementation approach. I also noticed that it was a bit slow when Livewire would change the state to show/hide the form, so what I did was use Alpine.js for determining whether to show the form or not.
<div x-data="{ mode: 'view' }">
<div x-show="mode === 'edit'">
<div>
<!-- display form here -->
</div>
<button wire:click="update">
Save
</button>
<button #click.prevent="mode = 'view'">
Cancel
</button>
</div>
<div x-show="mode !== 'edit'">
<div>
<!-- profile displayed here -->
</div>
<button #click.prevent="mode = 'edit'">
Edit
</button>
</div>
</div>
Doing it this way resolved the issue with displaying the form, which feels really snappy and quick. I have run into a different issue since that I’m not sure how to address.
If I begin to type in the form to update the name, and quickly hit the save button before the requests to update the component properties complete, then what ever the properties were at the time that I hit the save button are what gets saved to the database, creating a race condition.
I’m still relatively new to the Livewire paradigm so I don’t have a good answer for this yet.

Add [title] to fillable property to allow mass assignment on [App\Profile]

I am trying to create edit profile, but when I click on edit profile button I'm getting below error:
Illuminate \ Database \ Eloquent \ MassAssignmentException Add [title]
to fillable property to allow mass assignment on [App\Profile]
show.blade.php :
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="https://scontent-cdt1-1.cdninstagram.com/vp/dcca3b442819fc8b9b63f09b2ebde320/5DA9E3CB/t51.2885-19/s150x150/40101184_290824334847414_1758201800999043072_n.jpg?_nc_ht=scontent-cdt1-1.cdninstagram.com" 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>
Modifier Profile
<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
ProfileController :
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$data = request()->validate([
'title' => 'required',
'description' => 'required'
]);
$user->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
edit.blade.php :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Modifier profile</div>
<div class="card-body">
<form method="POST" action="{{ route('profile.update', ['user' => $user]) }}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="form-group">
<label for="title">Titre</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile->title }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" autocomplete="description" autofocus>{{ old('description') ?? $user->profile->description }}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input #error('image') is-invalid #enderror" id="validatedCustomFile" >
<label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Modifier profile
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarder = [];
public function user()
{
return $this->belongsTo('App\User');
}
}
What am I doing wrong here and how can I get rid of this error?
You have a spelling error, instead of $guarder add this in your model:
protected $guarded = [];
I won't advise using empty guarded but use $fillable instead.
In the same controller model, free access to database fields with
protected $guarded = [];
or
protected $fillable = [];

How to fix query in edit view?

i'm setting up a new project to perform multi language form but i'm stuck in edit form i don't know how to handle that
I created my controller and create view the only thing i need is edit view
so you can check my create view in bellow that work fine :
<div class="card-body text-center">
{!! Form::open(['route' => 'content.store', 'method' => 'Post']) !!}
<div class="card">
<div class="card-body">
<div class="form-group">
<label class="mx-4" for="my-input">{{ __('content/form.country_t') }}:</label>
<input id="my-input " type="text" name="country" placeholder="{{ __('content/form.country') }}">
<label class="mx-4" for="my-input">{{ __('content/form.city_t') }}:</label>
<input id="my-input" type="text" name="city" placeholder="{{ __('content/form.city') }}">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="card col-xs-12 p-0">
<nav>
<div class="nav nav-pills nav-fill card-header" id="nav-tab" role="tablist">
#foreach (config('translatable.locales') as $la=>$desc)
<a class="nav-item nav-link" id="nav-home-tab" data-toggle="tab" href="#{{ $la }}" role="tab" aria-controls="nav-home" aria-selected="true">{{ $desc }}</a> #endforeach
</div>
<div class="tab-content py-3 px-3 px-sm-0 card-body" id="nav-tabContent">
#foreach (config('translatable.locales') as $la=>$desc)
<div class="tab-pane fade px-4" id="{{ $la }}" role="tabpanel" aria-labelledby="nav-home-tab">
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.title') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][title]">
</div>
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.body') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][body]">
</div>
</div>
#endforeach
</div>
</nav>
</div>
<button type="submit" class="row col-12 mt-2 mx-auto btn btn-primary">{{ __('content/form.submit') }}</button>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
and this is my controller :
public function store(Request $request)
{
$contents = new Content;
// $contents->fill($request->all());
$this->fillRequest($request,$contents);
$contents->User()->associate(\Auth::user());
$contents->saveOrFail();
return redirect()->route('content.index')->with('success','با موفقیت ساخته شد');
}
private function fillRequest(Request $request, Content $model)
{
//fill model on fillable variables
$model->fill($request->only($model->getFillable()));
$model->saveOrFail();
foreach ($request->translations as $la => $desc) {
//if title field is null ignore the translations
// in case of there is a translation... delete it
if (!$desc["title"]) {
if ($model->hasTranslation($la)) {
$model->deleteTranslations($la);
}
continue;
}
//create new translation if not exists
$model->translateOrNew($la)->fill($desc);
$model->saveOrFail();
}
return $model;
}
I need to know how can i create edit view exactly same as my create view above

When I click on edit button give me error

When I click in edit button it gives me a error, what is problem I can not understand now, please help me
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\ytl\resources\views\profile\edit.blade.php)
This is my userprofilecontroller
public function edit( Request $request, $id){
$user_profile_id = UserProfile::where('id', '=', $id)->firstOrFail();
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$countries = Country::pluck('country','id')->all();
$brokerage_company = BrokerageCompany::pluck ('brokerage_company','id')->all();
$user_profile = UserProfile::pluck('charge_intraday','charge_delivery','charge_per_lot','charge_per_order')->all();
return view('profile.edit', compact('user_profile_id','exchanges','markets','countries','brokerage_company','user_profile'));
}
public function update(Request $request, $id){
$user_profile_id = UserProfile::findOrFail($id);
$input = $request->except( 'brokerage_company','user_profile');
$user_id = $user_profile->update($input);
return redirect('/profile');
}
This is profile\index.blade.php file
<div class="card card-table">
<div class="card-header">Basic Tables
<div class="tools dropdown"><span class="icon mdi mdi-download"></span><a class="dropdown-toggle" href="#" role="button" data-toggle="dropdown"><span class="icon mdi mdi-more-vert"></span></a>
<div class="dropdown-menu" role="menu"><a class="dropdown-item" href="#">Action</a><a class="dropdown-item" href="#">Another action</a><a class="dropdown-item" href="#">Something else here</a>
<div class="dropdown-divider"></div><a class="dropdown-item" href="#">Separated link</a>
</div>
</div>
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th style="width:10%;">Country</th>
<th style="width:10%;">Exchange</th>
<th class="number">Market</th>
<th class="number">Company</th>
<th class="actions">Charges</th>
</tr>
</thead>
#if($user_profile)
<tbody>
#foreach($user_profile as $user_profiles)
<tr>
<td>{{$user_profiles->country->country}}</td>
<td>{{$user_profiles->exchange->exchange}}</td>
<td>{{$user_profiles->market->market}}</td>
<td>{{$user_profiles->brokerage_company->brokerage_company}}</td>
<td class="cell-detail"><span>Intaday-charge</span>{{$user_profiles->charge_intraday}}
<span class="cell-detail-description">Delivery-charge</span>
{{$user_profiles->charge_delivery}}</td>
{{--<td>{{$user_profiles->charge_per_lot}}</td>--}}
{{--<td>{{$user_profiles->charge__per_order}} </td>--}}
<td> <a class="btn btn-info btn-sm" href="{{route('profile.edit', $user_profiles->id)}}">Edit</a></td>
</tr>
#endforeach
</tbody>
#endif
</table>
</div>
</div>
This is profile\edit.blade.php file
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Charge</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{--<form method="PATCH", id="form", action="{{action('Profile\UserProfileController#update',$user_profile_id->id)}} ", accept-charset="UTF-8">--}}
{{--{{ csrf_field() }}--}}
{{--{{ method_field('PATCH') }}--}}
{!! Form::model($user_profile,['method'=>'PATCH', 'action'=> ['Profile\UserProfileController#update',$user_profile->id]]) !!}
<div class="row">
<div class="col-md-6 mb-3 form-group">
Country:<select name="country_id" id="country" class="form-control " onchange="myfunc()" >
<option value="">Select</option>
#foreach($countries as $key=>$val )
<option value="{{ $val->id }}">{{ $val->country }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Exchange:<select name="exchange_id" id="exchange" class="form-control notselect" onchange="myfunc1()">
<option value="">Select</option>
{{--#foreach($exchanges as $key=>$val )--}}
{{--<option value="{{ $val->id }}">{{ $val->exchange }}</option>--}}
{{--#endforeach--}}
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Market<select name="market_id" id="market" class="form-control bindselect" >
<option value="">Select</option>
{{--#foreach($markets as $key=>$val )--}}
{{--<option value="{{ $val->id }}">{{ $val->market }}</option>--}}
{{--#endforeach--}}
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Company:<select name="brokerage_company_id" id="brokerage_company_id" class="form-control " >
<option value="">Select</option>
#foreach($brokerage_company as $key=>$val)
<option value="{{ $val->id }}">{{ $val->brokerage_company }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Intraday_charge: <input type="text" name="charge_intraday" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_delivery" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_lot" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_order" class="form-control"><br>
</div>
{!! Form::close() !!}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" value="Submit" name="form1" class="btn btn-primary">Save changes</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
It seems like you misunderstood the Pluck method. Pluck is to take several properties out an array by their key. Nothing to do with selecting columns from a Database.
I guess you want to select a single UserProfile. And the right way of doing this is as follows:
public function edit(Request $request, $id){
$user_profile = UserProfile::findOrFail($id); // Select a UserProfile by ID or fail
$exchanges = Exchange::all('exchange', 'id');
$markets = Market::all('market','id');
$countries = Country::all('country','id');
$brokerage_company = BrokerageCompany::all ('brokerage_company','id');
// I dont know what you want with this statement?
// $user_profile = UserProfile::pluck('charge_intraday','charge_delivery','charge_per_lot','charge_per_order')->all();
return view('profile.edit', compact('user_profile','exchanges','markets','countries','brokerage_company'));
}

Laravel pass id from blade template to store controller

I am trying to pass id to store controller as I need to save business_id that is being retrieved from another table. However I get:
Missing argument 2 for App\Http\Controllers\EventController::store()
Here's my view:
#extends('master') #section('title', 'Live Oldham')
#section('content')
<div class="col-lg-y col-lg-offset-3">
<ul class="list-group-list">
#foreach ($business->businesses as $business)
<li class="list-group-item">
<a target="_blank" href="{{ url('business/' . $business->id) }}"> {{($business->name) }}</a>
</li>
#endforeach
</ul>
</div>
#endsection
Controller:
class EventController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$id = Auth::id();
$business = User::where('id', $id)
->with('businesses')
->first();
return view('events.viewEvent', compact('business'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
return view('events.addEvent')
->with('Business', Business::find($id));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
$event = new Event;
$event->startdate = $request->input('startdate');
$event->enddate = $request->input('enddate');
$event->title = $request->input('title');
$event->frequency = $request->input('frequency');
$event->description = $request->input('description');
$event->business_id = $id;
$event->save();
}
form:
#extends('master') #section('title', 'Live Oldham')
#section('content')
<div class="container">
<!-- Alert Messages -->
#if (session('message'))
#if (session('message')=="success")
<div class="alert alert-success">
Event Created
</div>
#else
<div class="alert alert-danger">
There has been a fatal error! Apologies, we are working to fix it!
</div>
#endif
#endif
<!-- JQuery UI init -->
<script>
$( function() {
$( document ).tooltip();
} );
</script>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Create Event</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ action('EventController#store') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<div style="display:none;" class="title_message form-control alert-warning"></div>
<label for="title" class="col-md-4 control-label">Event Title</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control" placeholder="Event title"
title="What is the event title?" name="title" value="{{ old('title') }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('frequency') ? ' has-error' : '' }}">
<div style="display:none ;" class="frequency_message form-control alert-warning"></div>
<label id="frequency2" for="frequency" class="col-md-4 control-label">Frequency</label>
<div class="col-md-6">
<select class="form-control" name="frequency" id="frequency">
<option selected disabled>Choose event frequency...</option>
<option value="One">One-time Event</option>
<option value="Daily">Daily</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Yearly">Yearly</option>
</select>
#if ($errors->has('frequency'))
<span class="help-block">
<strong>{{ $errors->first('frequency') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('startdate') ? ' has-error' : '' }}">
<div style="display:none ;" class="startdate_message form-control alert-warning"></div>
<label id="startdate2" for="startdate" class="col-md-4 control-label">Event Start Date</label>
<div class="col-md-6">
<input id="startdate" type="date" class="form-control" placeholder="Start Date"
title="When does the event start?" name="startdate" value="{{ old('startdate') }}">
#if ($errors->has('startdate'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('enddate') ? ' has-error' : '' }}">
<div style="display:none ;" class="enddate_message form-control alert-warning"></div>
<label id="address3" for="enddate" class="col-md-4 control-label">Event End Date</label>
<div class="col-md-6">
<input id="enddate" type="date" class="form-control" placeholder="End Date"
title="When does the event end?" name="enddate" value="{{ old('enddate') }}">
#if ($errors->has('enddate'))
<span class="help-block">
<strong>{{ $errors->first('enddate') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<div style="display:none ;" class="description_message form-control alert-warning"></div>
<label id="description2" for="description" class="col-md-4 control-label">Event Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control" placeholder="Event description"
title="Here goes event description" name="description" value="{{ old('description') }}">
</textarea>
#if ($errors->has('description'))
<span class="help-block">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" id="submit" class="btn btn-success">
Add Event
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
You can pass the id to the form action
<form method="POST" action="{{ action('EventController#store', $business->id) }}" class="form-horizontal" role="form">
...
</form>

Resources