When i submit the form is nothing happens.
here is my step.
php artisan make:request PostRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
public function messages()
{
return [
'title.required'=>['need title'],
'article.required'=>['need article'],
];
}
}
?>
App/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\PostRequest;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
public function store(PostRequest $request)
{
Post::create($request->all());
return redirect()->route('post.index');
}
}
?>
If i don't use PostRequest it work perfectly,like this.
app/Http/Controllers/PostController.php
public function store(Request $request)
{
$post=new Post;
$post->user_id=Auth::user()->id;
$post->title=$request->title;
$post->article=$request->article;
$post->image=$request->image;
$post->save();
return redirect()->route('post.index');
}
And i missing something step?
Thanks everyone.
Your rules() function has a return array.
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
Change it to
public function rules()
{
return [
'title'=>'required|max:255',
'article'=>'required',
'image'=>'image'
];
}
Related
I want to pass $defaultFrom from NewsletterController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\NewsletterMail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class NewsletterController extends Controller
{
public function send()
{
$defaultFrom = 'newsletter#stuttard.de';
DB::table('newsletter_mails')->insert(['from' => $defaultFrom]);
$emails = DB::select('select * from newsletters order by id desc');
foreach ($emails as $email) {
Mail::to($email)->send(new NewsletterMail());
}
}
}
to NewsletterMail.php:
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
class NewsletterMail extends Resource
{
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make('From', 'from')->default($defaultFrom)->placeholder($defaultFrom),
];
}
}
I've tried to put public $defaultFrom; above the fields() function or call new NewsletterMail($defaultFrom) but this seems to be wrong syntax. Sorry, I'm a bit new to Laravel.
I assume that you have Newsletter model. Move $defaultFrom to model as public const DEFAULT_FROM = 'newsletter#stuttard.de';. After doing this, you can call it's value in both places using Newsletter::DEFAULT_FROM.
I don't understand this mistake, can someone help me?
I am taking a course on ApiRestfull and the code works for the teacher but I can't get it to work for me
I am using laravel 5.8*
The error he shows me is this: Error:
Argument 1 passed to App\Http\Controllers\ApiController::showAll() must be an instance of Illuminate\Database\Eloquent\Collection, instance of Illuminate\Support\Collection given, called in C:\laragon\www\udemy-apirestfull\app\Http\Controllers\Buyer\BuyerProductController.php on line 23
BuyerProductController.php:
<?php
namespace App\Http\Controllers\Buyer;
use App\Buyer;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
class BuyerProductController extends ApiController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Buyer $buyer)
{
$products = $buyer->transactions()->with('product')
->get()
->pluck('product');
return $this->showAll($products);
}
}
ApiController:
<?php
namespace App\Http\Controllers;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
class ApiController extends Controller
{
use ApiResponser;
}
ApiResponser:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
trait ApiResponser
{
private function successResponse($data, $code)
{
return response()->json($data, $code);
}
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse(['data' => $collection], $code);
}
protected function showOne(Model $instance, $code = 200)
{
return $this->successResponse(['data' => $instance], $code);
}
}
Buyer model:
<?php
namespace App;
use App\Transaction;
use App\Scopes\BuyerScope;
class Buyer extends User
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new BuyerScope);
}
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
Product Model:
<?php
namespace App;
use App\Seller;
use App\Category;
use App\Transaction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
const PRODUCTO_DISPONIBLE = 'disponible';
const PRODUCTO_NO_DISPONIBLE = 'no disponible';
protected $dates = ['deleted_at'];
protected $fillable = [
'name',
'description',
'quantity',
'status',
'image',
'seller_id',
];
public function estaDisponible()
{
return $this->status == Product::PRODUCTO_DISPONIBLE;
}
public function seller()
{
return $this->belongsTo(Seller::class);
}
public function transactions()
{
return $this->hasMany(Transaction::class);
}
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Transaction Model:
<?php
namespace App;
use App\Buyer;
use App\Product;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Transaction extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'quantity',
'buyer_id',
'product_id',
];
public function buyer()
{
return $this->belongsTo(Buyer::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
Illuminate\Database\Eloquent\Collection extends Illuminate\Support\Collection
So if not mandatory, you can change the signature of showAll method to accept Illuminate\Support\Collection as a parameter
There will be no error if the parameter supplied will be an instance of Illuminate\Database\Eloquent\Collection
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection; //Changed here
trait ApiResponser
{
private function successResponse($data, $code)
{
return response()->json($data, $code);
}
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse(['data' => $collection], $code);
}
protected function showOne(Model $instance, $code = 200)
{
return $this->successResponse(['data' => $instance], $code);
}
}
I have a test in a Laravel project where I do a getJson request and some answer should be returned. But the method in the controller doesn't get hit.
The test
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class NotificationsTest extends TestCase
{
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
$this->signIn();
}
public function test_a_user_can_fetch_their_unread_notifications()
{
create(DatabaseNotification::class);
$response = $this->getJson(url('/profiles') . '/' . auth()->user()->name . '/notifications')->json();
$this->assertCount(1, $response);
}
The line in webp.php that should process this request:
Route::get('/profiles/{user}/notifications', 'UserNotificationsController#index');
The UserNotificationsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\User;
class UserNotificationsController extends Controller
{
public function __construct()
{
$this->middelware('auth');
}
public function index() {
dd(" UsderNotificationsController-Index method hit");
return auth()->user()->unreadNotifications;
}
public function destroy(User $user, $notificationId)
{
dd(' Destroy method hit');
auth()->user()->notifications()->findOrFail($notificationId)->markAsRead();
}
}
If I run the test with phpunit, I would expect that the DD() in the index method should be executed. But it doesn't.
I tried all kinds of variations to generate the URI, but always get the same result. Can anyone tell me why I do not generate the correct URI?
Kind regards,
HUbert
//start by doing that : in your controller
Route::get('/profiles/notifications', 'UserNotificationsController#index');
public function test_a_user_can_fetch_their_unread_notifications()
{
$this->withoutHandlingException();
create(DatabaseNotification::class,['user_id'=>$this->signIn()->id]);
$this->signIn()//i think it should return authenticated user
$response = $this->get('/profiles/notifications')
->assertStatus(200);
// $this->assertCount(1, $response);
}
-//in your index function
public function index() {
dd(" UsderNotificationsController-Index method hit");
return response()->json(auth()->user()->unreadNotifications,200);
}
It is OK in Get, Post, Delete in my laravel code.
But I can't update the field.
function update in BookController.php
$data = $this->request->all();
If show the dd($data), it is null.
What reason?
Help me please.
BookRequest.php Code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'coment' => 'required'
];
}
}
BookController.php Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
protected $request;
protected $book;
public function __construct(Request $request, Book $book) {
$this->request = $request;
$this->book = $book;
}
public function update(BookRequest $request, $id) {
$data = $this->request->all();
$book = $this->book->find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
return response()->json(['status' => Response::HTTP_OK]);
}
}
If i were you i would replace the Controller like below:
<?php
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
public function update(BookRequest $request, $id) {
$book = Book::find($id);
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
}
If you have set up Route:model binding then you can simplify Code more better. Below code only works if you have a Route::model setup in your route file web.php.
Check this docs for more details:
https://laravel.com/docs/5.6/routing#route-model-binding
public function update(BookRequest $request, Book $book) {
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
Try this:-
$request->all();
instead of
$this->request->all()
I have solved.
My request: http://127.0.0.1:8000/api/book
POST , key: _method: PUT
Update Code
$data = $request->all();
$book = Boook::find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
Regards.
I am trying to catch in Laravel 5.5 the eloquent.created event when a Post model is created, but for any reason it does not work. It looks like the event/listener mapping that is defined inside the EventServiceProvider.php does not work. My setup is as follows.
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\NotifyBlogSubscribers',
]
];
public function boot()
{
parent::boot();
//
}
}
NotifyBlogSubscribers.php listener
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyBlogSubscribers
{
public function __construct()
{
//
}
public function handle(PostWasPublished $event)
{
dd('Inside NotifyBlogSubscribers');
}
}
PostWasPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
dd('Inside PostWasPublished');
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Post.php
<?php
namespace App\Models;
use App\Events\PostWasPublished;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $events = [
'created' => PostWasPublished::class,
];
protected $fillable = ['user_id', 'title', 'body'];
public function comments() {
return $this->hasMany(Comment::class);
}
public function addComment($body) {
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function user() {
return $this->belongsTo('App\User');
}
public function scopeFilter($query, $filters) {
if (array_key_exists('month', $filters)) {
$month = $filters['month'];
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if (array_key_exists('year', $filters)) {
$year = $filters['year'];
$query->whereYear('created_at', $year);
}
}
public static function archives() {
return static::selectRaw('year(created_at) as year, monthname(created_at) as month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
How do I test?
My first approach is to use tinker in the following way:
>>> App\Models\Post::create(['user_id' => '1', 'title' => 'some title', 'body' => 'lorem ipsum'])
=> App\Models\Post {#732
user_id: "1",
title: "some title",
body: "lorem ipsum",
updated_at: "2017-08-07 05:06:32",
created_at: "2017-08-07 05:06:32",
id: 62,
}
Also, when I create a post in the front-end it does not run into the dd() methods.
Also composer dump-autoload, php artisan clear-compiled or php artisan optimize did not do the trick. Any idea what I am doing wrong?
In Laravel 5.5 you will need to define a $dispatchesEvents property instead of a $events property. ($events was used in older Laravel versions).