Laravel 5, can't insert via request method doesn't exist - laravel-5

That's what i'm trying to do without any success:
In welcome.blade I have a foreach with some boards and subboards(random generated by user) where you can click on subboard and go something like this /subboardOne. I got this on my routes.php
Route::get('/{subboaName}', 'ThreadController#index');
Route::post('/{subboaName}', 'ThreadController#store');
then you can post a thread on this subboard via form but since i really don't know how laravel knows where he is, the form is something like this:
<form class="form col-md-12 center-block" role="form" method="POST" action="/{{$subboardcoll->id}}">
this $subboardcoll->id comes from the controller, where it sends via the index function the collection:
public function index($subboard)
{
$subboardcoll = Subboard::where('subboaName', $subboard)->first();
$threads = Thread::where('subboaId', $subboardcoll->id)
->orderBy('created_at', 'desc')
->get();
return view('threads.thread', compact('threads', 'subboardcoll'));
}
then i'm trying to send my form and store the thread autoinserting the subboardId but laravel doesn't recognize subboards method:
public function store(Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
$request->subboards()->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
return redirect()->back();
}
And gives me this erorr:
BadMethodCallException in Macroable.php line 81: Method subboards does not exist.
Can you guys helpme to know why? also is there better form to do what i'm trying? im newbie on laravel, thanks
EDIT:
Thread.php
public function subboard()
{
return $this->belongsTo(Subboard::class, 'subboaId');
}
Subboard.php
public function thread()
{
return $this->hasMany(Thread::class);
}

The method subboards do not exist in a request object. Consider doing this
public function store($id, Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
Subboard::find($id)->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
//Alternative query statement
Subboard::where('id', $id)->first()->threads()->create([.....
return redirect()->back();
}

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Laravel Livewire Dynamic Form Data Not Working

Quite new to Laravel Livewire. I'm trying to create a dynamic form for application but I couldn't quite understand how to attach additional data when storing.
The user selects the instructor(faculty_id), schoolyear(sy) and semester(sem). And new schedule and option to add more rows()
This is from my controller store() method
public function store()
{
$order = Emp_sched::create([
'faculty_id'=>$this->faculty_id,
'sem'=>$this->sem,
'sy'=>$this->sy,
]);
foreach ($this->createScheds as $sched) {
$order=(['corsdes' => $sched['corsdes']],
['c_time' => $sched['c_time']], ['day' => $sched['day']], ['room' => $sched['room']]);
}
return 'Schedules Saved!';
}
You must call Model::create inside loop
public function store()
{
foreach ($this->createScheds as $sched) {
$createArray = array_merge([
'faculty_id' => $this->faculty_id,
'sem' => $this->sem,
'sy' => $this->sy,
],[
'corsdes' => $sched['corsdes'],
'c_time' => $sched['c_time'],
'day' => $sched['day'],
'room' => $sched['room'],
]);
Emp_sched::create($createArray);
}
return 'Schedules Saved!';
}

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Error : undefined variable in laravel view

I am getting this error: undefined variable. I read a lot of posts about it but, none of them helped with the problem i am facing. (Why I get "Undefined variable" in Laravel view? )
This is Project_Controller :
class Project_Controller extends Controller
{
public function create()
{
$arrondissement = Arrondissements::pluck('arrondissement', 'id');
return view::make('projets.create', compact('arrondissement'));
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'intitule' => 'required|max:255',
'code' => 'required|max:255',
'dateDebut' => 'required|max:255',
'dateFin' => 'required|max:255',
'estimation' => 'required|max:255',
'arrondissement' => $request->arrondissement,
]);
if ($validator->fails()) {
return back()
->withInput()
->with(['arrondissement'=>$arrondissement])
->withErrors($validator);
}
$projet = new Projet;
$projet->intitule = $request->intitule;
$projet->code = $request->code;
$projet->dateDebut = $request->dateDebut;
$projet->dateFin = $request->dateFin;
$projet->estimation = $request->estimation;
$projet->arrondissement = $request->arrondissement;
$projet->save();
return view('/submit', compact('arrondissement'));
}
}
submit.blade.php :
<select name="arrondissement_id">
#if (!empty($arrondissement))
Whoops! Something went wrong
#else
#foreach($arrondissement as $id => $arrondissement)
<option value="{{$id}}">{{$arrondissement}}</option>
#endforeach
#endif
</select>
and this is routes.php :
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/', function () {
$projets = \App\Projet::all();
return view('welcome', compact('projets'));
});
Route::get('/submit', function () {
return view('submit');
});
Route::post('submit/projects', 'Project_Controller#store');
I can't see what's causing this error ??
I am using 'arrondissement' as a foreign key of table 'arrondissements'
When returning the view, you should also pass the variable with data:
$arrondissement = ....
return view('/submit', compact('arrondissement'));
I solved the problem. It's simple, I had to remove exclamation mark. Because, I need to test if the value is empty not unempty.
$arrondissement = Arrondissements::pluck('arrondissement', 'id');
You should also add this line into the store function

laravel's validator doesnt return input fields

problems with returning inputs. after form submitted, if validator fails it doesnt return 'old' inputs. here's my controller
$validator = Validator::make($request->all(), [
'user_rate' => 'required|integer|between:1,5',
'user_comment' => 'required',
], [
"user_rate.integer" => trans('errors.rate-required'),
"user_rate.between" => trans('errors.rate-required'),
"user_rate.required" => trans('errors.rate-required'),
"user_comment.required" => trans('errors.com-required'),
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->input());
//return redirect()->back()->with(Input::all());
}
i have tried several ways(also $request->flash(), but it doesnt return 'old' inputs
In your controller
public function someFunction(Request $request)
{
//Validation Logic
if($v->fails())
{
return redirect()->back()->withInput();
}
}
In your view
<input type="text" name="some_name" value="{{old('some_name')}}">
Hope this helps.
Don't pass any arguments to the withInput function
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
//return redirect()->back()->with(Input::all());
}
and how are you getting the old inputs in your form?

Resources