boyjarv

Member Since 2 Years Ago

Experience Points
7,260
Total
Experience

2,740 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 2
7,260 XP
May
17
1 day ago
Activity icon

Replied to Filter Search Not Working - Meta Total Is Always 30

lol yes, I will let the Udemy author know

Activity icon

Replied to Filter Search Not Working - Meta Total Is Always 30

so just change the get to paginate?

$products = Product::when(
	$request->input('s'),
	fn ($builder) => $builder->where('title', 'LIKE', "%{$request->input('s')}%")->orWhere('description', 'LIKE', "%{$request->input('s')}%")
)->paginate();
Activity icon

Replied to Filter Search Not Working - Meta Total Is Always 30

normally I would use paginate,it odes it all for you, not sure why this udemy course is doing it this way, probably because it uses Redis?!

Activity icon

Replied to Filter Search Not Working - Meta Total Is Always 30

I'm following a Udemy course

Activity icon

Started a new Conversation Filter Search Not Working - Meta Total Is Always 30

my search is not working, In postman, when I go to my endpoint http://mydomain.test/api/ambassador/products/backend?s=quiakjhu the results Do not filter?!

here is my code:

use Illuminate\Support\Str;


public function backend(Request $request) { 
        $page = $request->input('page', 1);

        /** @var Collection $products */
        \Cache::forget('products_backend');
        $products =  \Cache::remember('products_backend', 30*60, fn() => Product::all());

        if($s = $request->input('s')) {
            $product = $products
                ->filter(
                    fn(Product $product) => Str::contains($product->title, $s) || Str::contains($product->description, $s)
                );
        }
        $total = $products->count();
        return [
            'data' => $products->forPage($page, 9)->values(),
            'meta' => [
                'total' => $total,
                'page' => $page,
                'last_page' => ceil($total / 9)
            ],
        ];
    }
May
15
3 days ago
Activity icon

Started a new Conversation Help, DROPPED DB Table, Created New One, Unable To Migrate

When I run php artisan migrate

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known (SQL: select * from information_schema.tables where table_schema = ambassador and table_name = migrations and table_type = 'BASE TABLE')

Docker is running, I have cleared config and cache I haven't changed any DB table names, it is still the same name

Please help

Activity icon

Started a new Conversation Middleware Class Does Not Exist - But It Does!!!

I get the error: "message": "Target class [Illuminate\Auth\Middleware\ScopeAdminMiddleware] does not exist.",

here is my ScopeAdminMiddleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ScopeAdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if(!$request->user()->tokenCan('admin')) {
            abort('unauthorized');
        }
        return $next($request);
    }
}

here is my API:

Route::middleware(['auth:sanctum', 'scope.admin'])->group(function() {
        Route::get('user', [AuthController::class, 'user']);
        Route::post('logout', [AuthController::class, 'logout']);
    });

here is my Kernel.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'scope.admin' => \Illuminate\Auth\Middleware\ScopeAdminMiddleware::class,
    ];

I even added 'admin' to my login JWT:

$jwt = $user->createToken('token', ['admin'])->plainTextToken;
May
05
1 week ago
Activity icon

Replied to Favourites

join tables on artwork.created_by with users.user_id

Activity icon

Replied to Favourites

Do I use an INNER JOIN?

May
04
2 weeks ago
Activity icon

Started a new Conversation Favourites

hi,

So I have Users table and in the user model, I added:

public function favorites()
    {
        return $this->belongsToMany(Artwork::class, 'favorites', 'created_id', 'id')->withTimeStamps();
    }

I have a favourites table and an artworks table

Artworks

public function up()
    {
        Schema::create('artworks', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->string('status');
            $table->text('primary_art');
            $table->integer('height');
            $table->integer('width');
            $table->float('cost')->default(0.00)->nullable();
            $table->boolean('live')->default(false);
            $table->unsignedBigInteger('created_by');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

Favouries

public function up()
    {
        Schema::create('favorites', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('artwork_id')->unsigned();
            $table->timestamps();
        });
    }

how can I link my Artworks > Created_by with my Artworks > user_id in my FavouriteController?

public function index()
    {
        //
        $favourites = $this->user
		->favourites()
        ->when(request()->has('limit'), function ($builder) {
            $builder->take(request('limit'));
        })
//WHRE INNER JOIN ??
        ->get();
        return response()->json($faves->toArray());
    }
Apr
28
2 weeks ago
Activity icon

Replied to Rating Percentage For 1 - 5 Ideas On How To Go About This Please

great thanks but I'm getting something but my images are broken?!

<img src='{{asset(`images/$value->rating.png`)}}' /> ({{$value->count}})
<img src="http://feedback-form.test/">

it's not getting the 1.png filename?!

Apr
27
3 weeks ago
Activity icon

Started a new Conversation Rating Percentage For 1 - 5 Ideas On How To Go About This Please

hi,

So my form takes a 5 star rating, I would like to show a percentage of all users who have selected 5 all users who selected 4 and who selected 3 and so on

so something like this

***** (5 star - 76% of people left a 5 rating) **** (4 star - 21% of people left a 4 rating) **** (3 star - 0% of people left a 3 rating) **** (2 star - 0% of people left a 2 rating) **** (1 star - 3% of people left a 1 rating)

I believe this probably could be don using eloquent query?!

here is my reviews table:

Schema::create('reviews', function (Blueprint $table) {
            $table->id();
            $table->string('fullName');
            $table->string('postCode');
            $table->string('phoneNumber');
            $table->string('jobNumber');
            $table->string('status')->default('pending');
            $table->text('feedback');
            $table->integer('rating');
            $table->timestamps();
        });

and I've got a users table asnwell

Apr
26
3 weeks ago
Activity icon

Replied to Prefix A Value In A Column - So Each Number Starts With JOB-

WOW that's clever! Another reason to LOVE LARAVEL!

Activity icon

Replied to Prefix A Value In A Column - So Each Number Starts With JOB-

Call to undefined function getJobNumberPrefix()

here is where I am reading it

<div class="table-cell p-2">{{ getJobNumberPrefix($value->jobNumber) }}</div>

here is where I am setting it in my model:

public function getJobNumberPrefix($val)
    {
        return 'JC-' . $val;
    }
Activity icon

Started a new Conversation Prefix A Value In A Column - So Each Number Starts With JOB-

hi,

I was wondering how to add a prefix to a column by default

so I can add a job number like 123456 but in the database it shows as JOB-123456

Activity icon

Started a new Conversation How Can I Toggle Pending / Completed In Resource?

Hi, So I am using resource route for my crud:

Route

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ReviewController;
Route::resource('reviews', ReviewController::class);

// Route::get('addreview', '[email protected]')->name('addreview');
// Route::get('addreview', 'App\Http\Controllers\[email protected]')->name('addreview');

Route::get('/addreview', function () {
    return view('create');
})->name('addreview');

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

require __DIR__.'/auth.php';

I have a list which is showing all pending reviews from my index() method in my controller:

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Review::where('status', '=', 'pending')->paginate(5);

        return view('reviews.index',compact('data'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

I have another method to show completed reviews:

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function showcompleted()
    {
        $data = Review::where('status', '=', 'completed')->paginate(5);

        return view('reviews.index',compact('data'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

How is the best way I can using this?

Apr
23
3 weeks ago
Activity icon

Started a new Conversation Calla Function In Laravel

I would like to call this method from my controller in my blade template, how can I do this?

public function getAverageRating(){
        $averageRating = Rating::selectRaw('SUM(rating)/COUNT(id) AS avg_rating')->first()->avg_rating;

        return $averageRating;
    }

so I tried the following and nothing is output:

<h3>Average rating {{ $getAverageRating ?? '' }}</h3>
Apr
22
3 weeks ago
Activity icon

Started a new Conversation Route [addreview] Not Defined.

but it should be going to the welcome view, here is my web route file

Route::get('/addreview', function () {
    return view('create');
});

Route::get('/', function () {
    return view('welcome');
});

and in my browser I am going here: http://bobreview.test/ not here http://bobreview.test/addreview

Activity icon

Started a new Conversation Target Class [ReviewController] Does Not Exist.

So, I have clicked on my link addreview and I get : Target class [ReviewController] does not exist.

Route::get('addreview', '[email protected]')->name('addreview');

but it does exist?! here is my create method:

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('reviews.create');
    }

I have even got a reviews.create view setup!

Apr
19
4 weeks ago
Activity icon

Started a new Conversation DELETE Method Not Working

Method App\Http\Controllers\AllArtworkController::destroy does not exist.

public function destroy(artwork $id)
    {
        $artwork = Artwork::find($id);

        if($artwork->delete()) {
            return response()->json([
                'status' => true,
                'artwork' => $artwork
                ]
            );
        } else {
            return response()->json([
                'status' => false,
                'message' => 'oops the artwork could not be deleted'
            ]);
        }
    }

and here is my API call

deleteFind(id){
    return this.http.delete<Find>(this.apiURL + '/api/allartworks/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }
Apr
16
1 month ago
Activity icon

Replied to PUT Creates A New Item

api routes

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers',
    'prefix' => 'auth'
], function($router) {
    Route::post('login', '[email protected]');
    Route::post('register', '[email protected]');
    Route::post('logout', '[email protected]');
    Route::get('profile', '[email protected]');
    Route::post('refresh', '[email protected]');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers'
], function($router) {
    Route::resource('todos', 'TodoController');
    Route::resource('artworks', 'ArtworkController');
    Route::resource('allartworks', 'AllArtworkController');
    Route::resource('favefilms', 'FavFilmController');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});

Activity icon

Replied to PUT Creates A New Item

and here is my API call:

updateFind(id, find): Observable<Find> {
    return this.http.put<Find>(this.apiURL + '/api/allartworks/' + id, JSON.stringify(find), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }
Activity icon

Replied to PUT Creates A New Item

pretty sure I am, here is my angular ts file:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FindsService } from 'src/app/services/finds.service';

@Component({
  selector: 'app-find-edit',
  templateUrl: './find-edit.component.html',
  styleUrls: ['./find-edit.component.scss']
})
export class FindEditComponent implements OnInit {
  destroy$: Subject<boolean> = new Subject<boolean>();
  id = this.actRoute.snapshot.params['id'];
  findData: any = {};
  
  constructor(
    private restApi: FindsService,
    private actRoute: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.restApi.getFind(this.id)
    .pipe(takeUntil(this.destroy$))
    .subscribe((data: {}) => {
      console.log('data: ',data);
      this.findData = data;
    })
  }

  // Update employee data
  updateFind() {
    if(window.confirm('Are you sure, you want to update?')){
      this.restApi.updateFind(this.id, this.findData)
      .pipe(takeUntil(this.destroy$))
      .subscribe(data => {
        this.router.navigate(['/finds-list'])
      })
    }
  }

  ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }
}

Activity icon

Replied to PUT Creates A New Item

so I changed my update method to this:

public function store(Request $request, $id)
    {
        $user_id = auth()->user()->id;
        $validator = Validator::make($request->all(), [
            'title' => 'required|string',
            'description' => 'required|string'
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'errors' => $validator->errors()
            ], 400);
        }

        $artwork = Artwork::find($id);

        $artwork->title = $request->title;
        $artwork->description = $request->description;
        $artwork->status = $request->status;
        $artwork->primary_art = $request->primary_art;
        $artwork->latitude = $request->latitude;
        $artwork->longitude = $request->longitude;
        $artwork->height = $request->height;
        $artwork->width = $request->width;
        $artwork->cost = $request->cost;
        $artwork->live = $request->live;
        $artwork->created_by = $request->created_by;
        $artwork->updated_at = $request->updated_at;

        $artwork->save();

    }

still creating a new item

Activity icon

Replied to PUT Creates A New Item

I need it to update it not create a new one

Activity icon

Started a new Conversation PUT Creates A New Item

here is my object

{
    "title": "new artx",
    "description": "Here is a new piecexx",
    "status": "2",
    "primary_art": "https://drsustainable.files.wordpress.com/2012/08/transmission.jpg",
    "height": "322",
    "width": "422",
    "cost": "33.33",
    "live": true
}

here is my response a new ID (23) is created?!:

{
    "status": true,
    "artwork": {
        "title": "new artx",
        "description": "Here is a new piecexx",
        "status": "2",
        "primary_art": "https://drsustainable.files.wordpress.com/2012/08/transmission.jpg",
        "height": "322",
        "width": "422",
        "cost": "33.33",
        "live": true,
        "created_by": 2,
        "updated_at": "2021-04-16T19:50:37.000000Z",
        "created_at": "2021-04-16T19:50:37.000000Z",
        "id": 23
    }
}

here is my update:

public function store(Request $request)
    {
        $user_id = auth()->user()->id;
        $validator = Validator::make($request->all(), [
            'title' => 'required|string',
            'description' => 'required|string'
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'errors' => $validator->errors()
            ], 400);
        }

        $artwork = new Artwork();
        $artwork->title = $request->title;
        $artwork->description = $request->description;
        $artwork->status = $request->status;
        // $artwork->primary_art = $request->primary_art;
        $request->validate([
            'primary_art' => 'required:mimes:jpeg,jpg,png,gif',
        ]);
        if($request->hasFile('primary_art')){
            $file = $request->file('primary_art');
            $ext = $file->getClientOriginalExtension();
            $filename = time().'.'.$ext;
            $file->move('uploads/gallery/', $filename);
            // User::where('id',$user_id)->update([
            //     'primary_art'=>$filename
            // ]);
            $artwork->primary_art = $filename;
        } else {
            $artwork->primary_art = $request->primary_art;
        }
        $artwork->height = $request->height;
        $artwork->width = $request->width;
        $artwork->cost = $request->cost;
        $artwork->live = $request->live;

        if($this->user->artworks()->save($artwork)){
            return response()->json([
                'status' => true,
                'artwork' => $artwork
                ]
            );
        } else {
            return response()->json([
                'status' => false,
                'message' => 'oops the artwork could not be saved'
            ]);
        }
    }
Apr
15
1 month ago
Activity icon

Replied to My Edit Page Outputs An Empty Array

I have since changed my show function to this:

public function show(Artwork $artwork)
    {
        $artworks = Artwork::find($artwork);
        return response()->json($artworks->toArray());
    }

still getting empty array?!

Activity icon

Replied to My Edit Page Outputs An Empty Array

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers',
    'prefix' => 'auth'
], function($router) {
    Route::post('login', '[email protected]');
    Route::post('register', '[email protected]');
    Route::post('logout', '[email protected]');
    Route::get('profile', '[email protected]');
    Route::post('refresh', '[email protected]');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers'
], function($router) {
    Route::resource('todos', 'TodoController');
    Route::resource('artworks', 'ArtworkController');
    Route::resource('allartworks', 'AllArtworkController');
    Route::resource('favefilms', 'FavFilmController');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});
Activity icon

Awarded Best Reply on Angular Frontend API Requests

I have sorted this by following this: https://www.positronx.io/angular-7-httpclient-http-service/

Activity icon

Started a new Conversation My Edit Page Outputs An Empty Array

https://mydomain.com/api/allartworks/11

outputs []

here is my show method:

public function show(Artwork $artwork)
    {
        return $artwork;
    }
Activity icon

Started a new Conversation Angular Frontend API Requests

Both my Service file and my component return the same array of 12 items, great but surely, I should just be using one or the other?!

here is my Service file:

getAllFinds(): Observable<any> {
    const currentUser = localStorage.getItem('currentUser');
    const token = JSON.parse(currentUser).token;

    const httpHeaders = {
      headers: new HttpHeaders({
        'content-type': 'application/json',
        'Authorization': 'Bearer '+token
      })
    }

    return this.http.get<any>("https://lookwhatfound.me/api/allartworks", httpHeaders)
      .pipe(map(finds => {
        console.log('finds: ',finds)
        return finds;
      }))
  }

and here is my component:

ngOnInit(): void {
    this.loadAllFinds();
    this.findsService.getAllFinds();
  }

  loadAllFinds() {
    this.findsService.getAllFinds()
    .pipe(takeUntil(this.destroy$))
    .subscribe(Finds => {
      console.log('Finds: ', Finds)
    });
  }
Apr
11
1 month ago
Activity icon

Started a new Conversation Create A Migration To Change A Data Type From A String To A Double

hi, I would like to change a column from a string to a double, how can I do this? create a new migration?

thanks

Apr
09
1 month ago
Activity icon

Replied to API Routes Messed Up - Unable To Post To: Https://mydomain.com/api/allartworks

I'm with you, 1 controller per resource api

Activity icon

Started a new Conversation API Routes Messed Up - Unable To Post To: Https://mydomain.com/api/allartworks

here is my api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers',
    'prefix' => 'auth'
], function($router) {
    Route::post('login', '[email protected]');
    Route::post('register', '[email protected]');
    Route::post('logout', '[email protected]');
    Route::get('profile', '[email protected]');
    Route::post('refresh', '[email protected]');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers'
], function($router) {
    Route::resource('todos', 'TodoController');
    Route::resource('artworks', 'ArtworkController');
    Route::resource('allartworks', '[email protected]');
    Route::resource('favefilms', 'FavFilmController');
    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization'); 
});

|        | GET|HEAD  | /                                 |                     | Closure                                                   | web        |
|        | POST      | api/allartworks                   | allartworks.store   | App\Http\Controllers\[email protected]@store   | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | GET|HEAD  | api/allartworks                   | allartworks.index   | App\Http\Controllers\[email protected]@index   | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | GET|HEAD  | api/allartworks/create            | allartworks.create  | App\Http\Controllers\[email protected]@create  | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | DELETE    | api/allartworks/{allartwork}      | allartworks.destroy | App\Http\Controllers\[email protected]@destroy | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | PUT|PATCH | api/allartworks/{allartwork}      | allartworks.update  | App\Http\Controllers\[email protected]@update  | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | GET|HEAD  | api/allartworks/{allartwork}      | allartworks.show    | App\Http\Controllers\[email protected]@show    | api        |
|        |           |                                   |                     |                                                           | auth:api   |
|        | GET|HEAD  | api/allartworks/{allartwork}/edit | allartworks.edit    | App\Http\Controllers\[email protected]@edit    | api        |
|        |           |                                   |                     |                                                           | auth:api   |

here is my ArtworkController method:

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function allArtwork()
    {
        $artworks = Artwork::get(['id', 'title', 'description', 'status', 'primary_art', 'height', 'width', 'cost', 'live']);
        return response()->json($artworks->toArray());
    }
Apr
05
1 month ago
Activity icon

Replied to The GET Method Is Not Supported For This Route.

when I post to it via my phone, I get : 301 Moved Permanently

Activity icon

Replied to The GET Method Is Not Supported For This Route.

here is my api.php routes

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers',
    'prefix' => 'auth'
], function($router) {
    Route::post('login', '[email protected]');
    Route::post('register', '[email protected]');
    Route::post('logout', '[email protected]');
    Route::get('profile', '[email protected]');
    Route::post('refresh', '[email protected]');
});

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers'
], function($router) {
    Route::resource('todos', 'TodoController');
    Route::resource('artworks', 'ArtworkController');
    Route::resource('favefilms', 'FavFilmController');
});

here is my URL: http://www.lookwhatfound.me/api/auth/register

here is my post body:

{
    "name": "abc",
    "email": "[email protected]",
    "password": "abcabc",
    "password_confirmation": "abcabc"
}

here is my post headers:

Accept: application/json
Content-Type: application/json

and here is the Auth Controller:

<?php

namespace App\Http\Controllers;

use App\Models\Artworks;
use App\Models\Todo;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    //
    public function __construct() 
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    public function login(Request $request) {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6'
        ]);
        
        if($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $token_validity = 24 * 60;

        $this->guard()->factory()->setTTL($token_validity);

        if(!$token = $this->guard()->attempt($validator->validated())) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);

    }

    public function register(Request $request) {
        $validator = Validator::make(
            $request->all(),
            [
                'name'     => 'required|string|between:2,100',
                'email'    => 'required|email|unique:users',
                'password' => 'required|confirmed|min:6',
            ]
        );

        if($validator->fails()) {
            return response()->json([
                $validator->errors()
            ], 422);
        }

        $user = User::create(array_merge(
            $validator->validated(),
            ['password' => bcrypt($request->password)]
        ));

        return response()->json(['message' => 'user created successfully', 'user' => $user]);
    }

    public function logout() {
        $this->guard()->logout();
        return response()->json(['message' => 'user logged out successfully']);
    }

    public function profile() {
        return response()->json($this->guard()->user());
    }
    
    public function refresh() {
        return $this->respondWithToken($this->guard()->refresh());   
    }

    protected function respondWithToken($token) {
        return response()->json([
            'token' => $token,
            'token_type' => 'bearer',
            'token_validity' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    protected function guard() {
        return Auth::guard();
    }
}

Activity icon

Replied to The GET Method Is Not Supported For This Route.

I'm testing in POSTMAN, I know this works locally

Activity icon

Started a new Conversation The GET Method Is Not Supported For This Route.

The GET method is not supported for this route. Supported methods: POST.

I am actually using POST not GET so very confused as to why I am getting this 405Method Not Allowed

Activity icon

Started a new Conversation POSTING To Api 404 Not Found

so I just uploaded my laravel project to : http://www.lookwhatfound.me/api

when I try to POST to the api on the following URL I get 404 Not Found

http://www.lookwhatfound.me/api/auth/login

I have also tried:

http://www.lookwhatfound.me/api/api/auth/login

I have setup the database and run php artisan migrate successfully

Activity icon

Replied to Php Artisan Route:list Shows Error In Code

can I not just change my code?

Activity icon

Replied to Php Artisan Route:list Shows Error In Code

PHP 7.3.27, how can I update it to 7.4 using command line?

Activity icon

Started a new Conversation Php Artisan Route:list Shows Error In Code

when I run php artisan route:list on my server, I get:

syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')'

  at app/Http/Controllers/TodoController.php:34
     30▕         // return response()->json($todos->toArray());
     31▕ 
     32▕         $todos = $this->user
     33▕ 		->todos()
  ➜  34▕ 		->when(request()->has('limit'), fn ($builder) => $builder->take(request('limit')))
     35▕         ->get(['id', 'title', 'body', 'completed', 'created_by']);
     36▕         return response()->json($todos->toArray());
     37▕     }
     38▕     
Mar
28
1 month ago
Activity icon

Replied to Handshake Error On Flutter With Laravel 7

I am also having this issue after I set my port number as 80

String url = "https://choosapi.test:80/api/auth/login";

    final response = await http.post(
      Uri.parse(url),
      headers: <String, String>{
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(loginRequestModel)
    );
Mar
19
1 month ago
Activity icon

Replied to Unable To Destroy An ID

Nothing in Network tab

I have changed my method to this:

public function destroy(FavFilm $FavFilm)
    {
        //
        if($FavFilm->delete()) {
            return response()->json([
                'status' => true,
                'FavFilm' => $FavFilm
                ]
            );
        } else {
            return response()->json([
                'status' => false,
                'message' => 'oops the Fav could not be deleted'
            ]);
        }
    }

still not working?!