what is the update method in laravel 5.4 crud? - php

i just trying to crud system. for that into controller store function my code is
public function store(Request $request)
{
Article::create([
'user_id' => auth()->id(),
'content' => $request->content,
'live' => (boolean)$request->live,
'post_on' => $request->post_on
]);
return redirect('/articles');
}
it's enough to store data, but when i want to edit article & save again then what will be my edit function code? i have no idea. i trying same code into edit function & it create new article not update. so what will be right code for edit function? thanks

Resource controller method for update is update(). Eloquent method for update() is update() too, so you can do this:
public function update(Request $request, $id)
{
Article::where('id', $id)->update($request->all());
return redirect('/articles');
}
You also can use the same controller and Eloquent method for both crerate and update data updateOrCreate() method.

You can also update it as object format like this.
public function update(Request $request, $id)
{
$article = Article::find($id);
$article->user_id = auth()->id();
$article->content = $request->content;
$article->live = (boolean)$request->live;
$article->post_on = $request->post_on;
$article->save();
}`

//route//
Route::any('/update/{id}', 'ProductController#update');
//controller//
public function update(Request $request, $id) {
$product = $request - > all();
Product::find($id) - > update($product);
return redirect('/product') - > with('message', 'Success', compact('product'));
}

you can use
public function update(Request $request, $id)
{
$article = Article::find($id);
$article->fill($request->all());
}
sure you should add Your column attributes to $fillable array in Your model
protected $fillable = ['user_id', 'content', 'live'];

public function update(Request $request, $id) {
Article::where('id', $id)->update($request->except(['_token']));
return redirect('/articles');
}

If you auto-generate resource controller for a specific Model using php artisan make:model -a Artical then you have the update() function like below:
public function update(Request $request, Article $article)
{
//
}
Here, Lavarel automatically fetch the Article object into $article. So, you can save the $request data like below:
public function update(Request $request, Article $article)
{
$article->update($request->all());
return redirect()->route('article.index'); // or your desired location :)
}

public function update(Request $request, $id)
{
$info = array('user_id' =>$request->user()->id,
'content' => $request->content, 'live'=>$request->live);
DB::table('article')->where('id', $id)->update($info);
session()->flash('success', 'Update Successfully');
return redirect('/article');
}

First, you are having two actions right, the create and update, so for a real crud in laravel you might have these two in a separated logic methods the store() and update():
/**
* This is a resource create method which is a HTTP POST.
*/
public function store(Request $request) {
// create a new item in database
}
/**
* This is a resource update which is a HTTP PUT METHOD.
*/
public function update(Request $request, $id) {
// update the item in database
}
You set up your routes withPOST for creating and PUT to update then your doing a proper crud resource.
I recommend you to separate the create logic off the update logic and if you have sort of unique data then you should validate its value before creating a new resource.

Related

How can I set different sets of fields to create and update a resource in Laravel nova?

I want to show a different set of fields with different settings when creating and editing a resource.
how to implement it with Laravel Nova ?
You can use this condition inside the fields function to check if this is an update or create request,
For example
public function fields(Request $request)
{
if($request->resourceId === null)
{
//this is a create request
return
[
ID::make('ID', 'tenant_id')->sortable(),
Text::make('Userame', 'username'),
Image::make('Profile', 'user_file')
]
}
else
{
return
[
ID::make('ID', 'tenant_id')->sortable(),
Image::make('Profile', 'user_file')
]
}
}
Update:
Since v3.1.0 you can use the following methods:
public function fieldsForIndex(Request $request)
public function fieldsForDetail(Request $request)
public function fieldsForCreate(Request $request)
public function fieldsForUpdate(Request $request)

Reference same variable using two controllers in laravel

I am generating a pdf based on user input. I can call the databse and get ALL contract info using all(). However, I would only like to generate a pdf for one of the values. Each contract has a auto incrememnt id which i could use.
Whats the best way to communicate between controllers so only the contract I am referencing is used to generate a pdf?
PdfGenerateController:
public function pdfview(Request $request)
{
$users = DB::table("users")->get();
$contract = Contract::all();
view()->share('users',$users);
if($request->has('download')){
// Set extra option
PDF::setOptions(['dpi' => 150, 'defaultFont' => 'sans-serif']);
$users = DB::table("users")->get();
// pass view file
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML
($contract);
return $pdf->stream();
}
return view('sell.contract');
}
Contract Controller (user input)
public function store(Request $request)
{
$contract = new Contract;
$contract->buyer_first_name = $request->input('buyer_first_name');
$contract->listing_id = $request->input('listing_id');
$contract->save();
return redirect()->route('generate-pdf')->with('contracts',$contract);
}
Storing the contract id in the session is probably your best bet. If you need to use it only on the next request, you could just flash it (in fact, that's exactly what the redirect(..)->withInput(sessionKey, val) does).
Something like that:
Contract Controller
public function store(Request $request)
{
// ...
$contract->save();
session(['contract_id' => $contract->id]);
return redirect()->route('generate-pdf');
}
Or just flashing:
public function store(Request $request)
{
// ...
$contract->save();
return redirect()->route('generate-pdf')->with('contract_id', $contract->id);
}
PdfGeneratteController
public function pdfview(Request $request)
{
$contract = Contract::findOrFail(session('contract_id'));
// ...
}
I would probably create a PDF model class with a static method to generate the PDF.
class PDF
{
public static function generatePDF($id, $isDownload)
{
// ...
}
}
Then you could simply call the static method from the Contact controller and pass the required data as parameters.
public function store(Request $request)
{
// ...
\PDF::generatePDF($contract->id, $request->has('download'));
// ...
}

Saving both polymorphic relationships at the same time in Laravel 5.3

I want to correctly save both polymorphic relationships at the same time. The code below works, but I feel it could be a lot cleaner as I presume the two update() methods are calling the database twice.
A NewsModule::class can have different module items; VideoModule, TextModule, ImageModule, and a few more. Each containing their own content to be attached to the parent NewsModule.
As mentioned, the code works so the relationships are set up correctly, but I'm convinced there's a cleaner way of saving both at the same time.
I'm also open to suggestions about cleaning up the if statements too. But maybe that's another post.
public function update(Request $request, $id)
{
$module = NewsModule::find($id);
if ($module->type === 'text') {
$content = TextModule::find($module->content_id);
} elseif ($module->type === 'image') {
$content = ImageModule::find($module->content_id);
};
$module->update($request->all());
$content->update($request->all());
return fractal()
->item($module, new NewsModuleTransformer)
->parseIncludes(['content'])
->toArray();
}
Updated (more code by request)...
Structure:
news_modules
- id
- content_id
- content_type
- etc
text_modules
- id
- content
- etc
image_modules
- id
- image_id
- etc
NewsModule:
class NewsModule extends Model
{
public function content()
{
return $this->morphTo();
}
}
All item modules:
class TextModule extends Model
{
public function newsmodules()
{
return $this->morphMany(NewsModule::class, 'content');
}
}
public function update(Request $request, $id)
{
$modele = NewsModule::find($id);
$module->update($request->all());
$module->content->update($request->all());
return fractal()
->item($module, new NewsModuleTransformer)
->parseIncludes(['content'])
->toArray();
}
That will run 4 queries total. 1 for each module to retrieve and another to update. That can be cut down to 3 like:
public function update(Request $request, $id)
{
$modele = NewsModule::find($id);
$module->update($request->all());
$module->content()->update($request->all());
return fractal()
->item($module, new NewsModuleTransformer)
->parseIncludes(['content'])
->toArray();
}
The downside to $module->content()->update($request->all()); is it will throw an error if there is anything in $request->all() that isn't a column in that content model or there is an array as a value. You can avoid that by just calling update() on the $fillable properties (if you have them defined) of the related model like:
$fillable = $module->content()->getRelated()->getFillable();
$module->content()->update($request->only($fillable));
This way will also not fire any model event listeners you have since you are never retrieving the model from the database.
To take everything one step further, look into Route Model Binding. In your app\Providers\RouteServiceProvider's boot() method:
public function boot()
{
parent::boot();
Route::model('news', App\NewsModule::class);
}
This way 'news' will always resolve to an instance of NewsModule when using it as a route parameter. So your route would be something like:
Route::match(['patch', 'put'], '/news/{news}', 'NewsController#update');
So in your update method you could resolve the model by just type hinting it in the method allowing you to do:
public function update(Request $request, NewsModule $news)
{
$news->update($request->all());
$news->content->update($request->all());
return fractal()
->item($news, new NewsModuleTransformer)
->parseIncludes(['content'])
->toArray();
}

Laravel 5 modal form data not updating

My route:
Route::post('/edit/{id}',['as'=>'edit','uses'=>'datacontroller#update']);
My controller:
public function update(Request $request, $id)
{
$task = veriler::findOrFail($id);
$input = $request->all();
$task->fill($input)->save();
return redirect()->back();
}
My modal form page:
Only the last data updating. I could not solve the problem.
public function update(Request $request, $id)
{
$task = veriler::findOrFail($id);
$input = $request->all();
$task->fill($input);
$task->save();
return redirect()->back();
}
Fill function takes the input, and save function saves to the databaes.

ModelNotFoundException - No query results for model [App\User]

From the form in my edit view, I'm calling the update function:
public function update(Request $request)
{
$id = Auth::user();
$user = User::findOrFail($id);
$user->update($request->all());
return redirect('user');
}
but I'm getting the following error:
ModelNotFoundException in Builder.php line 125: No query results for model [App\User].
I'm not passing the $id because i'm updating the Auth Id.
Not sure what's wrong and how to debug
Following is just enough in case you want to update logged in User.
public function update(Request $request)
{
Auth::user()->update($request->all());
return redirect('user');
}
#pinkalvansia has a great answer and solution for you.
However, I also wanted to note that I believe you would need to use:
Auth::user()->id to get the currently logged in user's ID. Your code would like this:
public function update(Request $request)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$user->update($request->all());
return redirect('user');
}
Hope this is helpful!

Categories